编程语言
首页 > 编程语言> > 基于java开发贪吃蛇小游戏

基于java开发贪吃蛇小游戏

作者:互联网

本项目有三个JAVA类,Data类存放外部数据,StartGames类用来绘制静态窗口,GamePanel类用来实现游戏逻辑。

第一步:导入项目所需素材,创建一个statics包存放素材。
在这里插入图片描述

第二步,绘制一个静态窗口,使用JFrame

public static void main(String[] args) {
    //绘制一个静态窗口,JFrame
    JFrame frame = new JFrame("贪吃蛇 by 阿中");
    //设置界面的大小
    frame.setBounds(10,10,900,720);
    frame.setResizable(false);//窗口大小不可改变
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭事件,游戏可以关闭了

    //2.画板 JPanel 可以加入到JFrame中


    frame.setVisible(true);//设置窗口可以显现出来



}

Data类,存放外部数据

public class Data {
    //头部的图片 URL : 定位图片的地址    ImageIcon : 图片
    public static URL headerURL = Data.class.getResource("/statics/header.png");
    public static ImageIcon header = new ImageIcon(headerURL);

    //身体
    public static URL bodyURL = Data.class.getResource("/statics/body.png");
    public static ImageIcon body = new ImageIcon(bodyURL);
    //食物
    public static URL foodURL = Data.class.getResource("/statics/food.png");
    public static ImageIcon food = new ImageIcon(foodURL);
    //头部
    public static URL downURL = Data.class.getResource("/statics/down.png");
    public static URL leftURL = Data.class.getResource("/statics/left.png");
    public static URL rightURL = Data.class.getResource("/statics/right.png");
    public static URL upURL = Data.class.getResource("/statics/up.png");
    public static ImageIcon down = new ImageIcon(downURL);
    public static ImageIcon left = new ImageIcon(leftURL);
    public static ImageIcon right = new ImageIcon(rightURL);
    public static ImageIcon up = new ImageIcon(upURL);

}

第三步,画一个游戏界面,继承 JPanel类,重写paintComponent方法

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);//清屏
    this.setBackground(Color.white);//设置背景的颜色
    Data.header.paintIcon(this, g, 25, 11);//绘制头部广告栏
    g.fillRect(25, 75, 850, 600);//绘制游戏区域
    }

绘制小蛇:

//画一条静态的小蛇
if (fx.equals("R")) {
    Data.right.paintIcon(this, g, snakeX[0], snakeY[0]);
} else if (fx.equals("L")) {
    Data.left.paintIcon(this, g, snakeX[0], snakeY[0]);
} else if (fx.equals("U")) {
    Data.up.paintIcon(this, g, snakeX[0], snakeY[0]);
} else if (fx.equals("D")) {
    Data.down.paintIcon(this, g, snakeX[0], snakeY[0]);
}
for (int i = 1; i < length; i++) {
    Data.body.paintIcon(this, g, snakeX[i], snakeY[i]);//蛇的长度通过length来控制
}

定时器,监听时间,让小蛇动起来

@Override
public void actionPerformed(ActionEvent e) {
    //如果处于开始状态
    if (isStart && isFail == false) {
        //右移
        for (int i = length - 1; i > 0; i--) {//身体移动
            snakeX[i] = snakeX[i - 1];
            snakeY[i] = snakeY[i - 1];
        }

        //通过控制方向让头部移动
        if (fx.equals("R")) {
            snakeX[0] = snakeX[0] + 25;//头部移动
            if (snakeX[0] > 850) {
                snakeX[0] = 25;
                //isFail=true;
            }//边界判断
        } else if (fx.equals("L")) {
            snakeX[0] = snakeX[0] - 25;//头部移动
            if (snakeX[0] < 25) {
                snakeX[0] = 850;
            }//边界判断
        } else if (fx.equals("U")) {
            snakeY[0] = snakeY[0] - 25;//头部移动
            if (snakeY[0] < 75) {
                snakeY[0] = 650;
            }//边界判断
        } else if (fx.equals("D")) {
            snakeY[0] = snakeY[0] + 25;//头部移动
            if (snakeY[0] > 650) {
                snakeY[0] = 75;
            }//边界判断
        }
        //如果小蛇的头和食物的坐标重合了
        if (snakeX[0] == foodx && snakeY[0] == foody) {
            //长度加1
            length++;
            //重新生成食物
            foodx = 25 + 25 * random.nextInt(34);
            foody = 75 + 25 * random.nextInt(24);
            score+=10;
        }
        //结束判断
        for (int i = 1; i < length; i++) {
            if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
                isFail = true;
            }
        }

        repaint();//刷新界面
    }
    timer.start();
}

StartGames类:

package com.zdz.sanke;

import javax.swing.*;

public class StartGames {
    public static void main(String[] args) {
        //绘制一个静态窗口,JFrame
        JFrame frame = new JFrame("贪吃蛇 by 阿中");
        //设置界面的大小
        frame.setBounds(10,10,900,720);
        frame.setResizable(false);//窗口大小不可改变
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭事件,游戏可以关闭了

        //2.画板 JPanel 可以加入到JFrame中
        frame.add(new GamePanel());


        frame.setVisible(true);//设置窗口可以显现出来



    }


}

Data类:

package com.zdz.sanke;


import javax.swing.*;
import java.net.URL;

public class Data {
    //头部的图片 URL : 定位图片的地址    ImageIcon : 图片
    public static URL headerURL = Data.class.getResource("/statics/header.png");
    public static ImageIcon header = new ImageIcon(headerURL);

    //身体
    public static URL bodyURL = Data.class.getResource("/statics/body.png");
    public static ImageIcon body = new ImageIcon(bodyURL);
    //食物
    public static URL foodURL = Data.class.getResource("/statics/food.png");
    public static ImageIcon food = new ImageIcon(foodURL);
    //头部
    public static URL downURL = Data.class.getResource("/statics/down.png");
    public static URL leftURL = Data.class.getResource("/statics/left.png");
    public static URL rightURL = Data.class.getResource("/statics/right.png");
    public static URL upURL = Data.class.getResource("/statics/up.png");
    public static ImageIcon down = new ImageIcon(downURL);
    public static ImageIcon left = new ImageIcon(leftURL);
    public static ImageIcon right = new ImageIcon(rightURL);
    public static ImageIcon up = new ImageIcon(upURL);




}

GamePanel类:

package com.zdz.sanke;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;

public class GamePanel extends JPanel implements KeyListener, ActionListener {
    int length;//蛇的长度
    int[] snakeX = new int[600];//蛇的坐标X
    int[] snakeY = new int[500];//蛇的坐标Y
    String fx;//蛇头的方向
    boolean isStart = false;//游戏是否开始

    Timer timer = new Timer(300, this);

    //定义一个食物
    int foodx;
    int foody;
    Random random = new Random();

    //定义一个失败
    boolean isFail = false;
    //积分系统
    int score;

    //构造器
    public GamePanel() {
        init();
        //获取键盘的监听事件
        this.setFocusable(true);//获取键盘的焦点
        this.addKeyListener(this);//获取当前的键盘监听
    }

    //初始化
    public void init() {
        length = 3;
        snakeX[0] = 100;
        snakeY[0] = 100;//头部坐标
        snakeX[1] = 75;
        snakeY[1] = 100;//第一个身体坐标
        snakeX[2] = 50;
        snakeY[2] = 100;//第二个身体坐标
        fx = "R";
        timer.start();
        foodx = 25 + 25 * random.nextInt(34);
        foody = 75 + 25 * random.nextInt(24);
        score = 0;
    }


    //画板,画界面,画蛇
    //Graphics :画笔
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);//清屏
        this.setBackground(Color.white);//设置背景的颜色
        Data.header.paintIcon(this, g, 25, 11);//绘制头部广告栏
        g.fillRect(25, 75, 850, 600);//绘制游戏区域

        //画一条静态的小蛇
        if (fx.equals("R")) {
            Data.right.paintIcon(this, g, snakeX[0], snakeY[0]);
        } else if (fx.equals("L")) {
            Data.left.paintIcon(this, g, snakeX[0], snakeY[0]);
        } else if (fx.equals("U")) {
            Data.up.paintIcon(this, g, snakeX[0], snakeY[0]);
        } else if (fx.equals("D")) {
            Data.down.paintIcon(this, g, snakeX[0], snakeY[0]);
        }

        for (int i = 1; i < length; i++) {
            Data.body.paintIcon(this, g, snakeX[i], snakeY[i]);//蛇的长度通过length来控制
        }
        //画食物
        Data.food.paintIcon(this, g, foodx, foody);
        //画积分
        g.setColor(Color.white);
        g.setFont(new Font("微软雅黑", Font.BOLD, 18));
        g.drawString("长度"+length, 750, 35);
        g.drawString("分数"+score, 750, 50);


        //游戏提示:是否开始
        if (isStart == false) {
            //画一个文字,String
            g.setColor(Color.white);
            g.setFont(new Font("微软雅黑", Font.BOLD, 40));
            g.drawString("按下空格开始游戏", 300, 300);
        }
        //失败提醒
        if (isFail) {
            //画一个文字,String
            g.setColor(Color.RED);
            g.setFont(new Font("微软雅黑", Font.BOLD, 40));
            g.drawString("游戏失败,按下空格键重新开始", 200, 300);
        }

    }


    //接受键盘的输入:监听
    @Override
    public void keyPressed(KeyEvent e) {
        //键盘按下,未释放
        //获取按下的键盘是哪个键
        int keyCode = e.getKeyCode();
        if (keyCode == KeyEvent.VK_SPACE) {//如果按下的是空格键
            if (isFail) {//失败,游戏重新再来一遍
                isFail = false;
                init();//重新初初始化游戏
            } else {//暂停游戏
                isStart = !isStart;
            }
            repaint();//刷新界面
        }

        //键盘控制走向
        if (keyCode == KeyEvent.VK_LEFT) {
            fx = "L";
        } else if (keyCode == KeyEvent.VK_RIGHT) {
            fx = "R";
        } else if (keyCode == KeyEvent.VK_UP) {
            fx = "U";
        } else if (keyCode == KeyEvent.VK_DOWN) {
            fx = "D";
        }
    }

    //定时器,监听时间
    @Override
    public void actionPerformed(ActionEvent e) {
        //如果处于开始状态
        if (isStart && isFail == false) {
            //右移
            for (int i = length - 1; i > 0; i--) {//身体移动
                snakeX[i] = snakeX[i - 1];
                snakeY[i] = snakeY[i - 1];
            }

            //通过控制方向让头部移动
            if (fx.equals("R")) {
                snakeX[0] = snakeX[0] + 25;//头部移动
                if (snakeX[0] > 850) {
                    snakeX[0] = 25;
                    //isFail=true;
                }//边界判断
            } else if (fx.equals("L")) {
                snakeX[0] = snakeX[0] - 25;//头部移动
                if (snakeX[0] < 25) {
                    snakeX[0] = 850;
                }//边界判断
            } else if (fx.equals("U")) {
                snakeY[0] = snakeY[0] - 25;//头部移动
                if (snakeY[0] < 75) {
                    snakeY[0] = 650;
                }//边界判断
            } else if (fx.equals("D")) {
                snakeY[0] = snakeY[0] + 25;//头部移动
                if (snakeY[0] > 650) {
                    snakeY[0] = 75;
                }//边界判断
            }
            //如果小蛇的头和食物的坐标重合了
            if (snakeX[0] == foodx && snakeY[0] == foody) {
                //长度加1
                length++;
                //重新生成食物
                foodx = 25 + 25 * random.nextInt(34);
                foody = 75 + 25 * random.nextInt(24);
                score+=10;
            }
            //结束判断
            for (int i = 1; i < length; i++) {
                if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
                    isFail = true;
                }
            }

            repaint();//刷新界面
        }
        timer.start();
    }

    @Override
    public void keyReleased(KeyEvent e) {
        //键盘释放
    }

    @Override
    public void keyTyped(KeyEvent e) {
        //敲击键盘,键盘弹起
    }


}

游戏运行界面:
在这里插入图片描述

标签:ImageIcon,java,snakeX,snakeY,小游戏,static,贪吃蛇,Data,public
来源: https://blog.csdn.net/A_Zhong20/article/details/115010263