服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Java实现简易GUI贪吃蛇小游戏

Java实现简易GUI贪吃蛇小游戏

2021-12-30 12:16姜泥誓杀徐凤年 Java教程

这篇文章主要为大家详细介绍了Java实现简易GUI贪吃蛇小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Java实现贪吃蛇小游戏的具体代码,供大家参考,具体内容如下

主启动类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import javax.swing.*;
 
/**
 * @author The Setting sun
 * @create 2021-09-11 15:19
 */
//主启动类
public class StartGame {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
 
        frame.setResizable(false);//窗口大小不可变
        frame.setSize(900, 720);//窗口大小
        frame.setLocationRelativeTo(null);//窗口居中
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//窗口关闭事件
 
        frame.add(new GamePanel());
 
        frame.setVisible(true);//窗口可见
    }
}

资源类(图标)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import javax.swing.*;
import java.net.URL;
 
/**
@author The Setting sun
@create 2021-09-11 15:40
*/
public class Data {
    public static URL headerURL = Data.class.getResource("img/header.png");
    public static ImageIcon header = new ImageIcon(headerURL);
 
    public static URL upURL = Data.class.getResource("img/tx.png");
    public static ImageIcon up = new ImageIcon(upURL);
 
    public static URL downURL = Data.class.getResource("img/down.png");
    public static ImageIcon down = new ImageIcon(downURL);
 
    public static URL rightURL = Data.class.getResource("img/right.png");
    public static ImageIcon right = new ImageIcon(rightURL);
 
    public static URL leftURL = Data.class.getResource("img/left.png");
    public static ImageIcon left = new ImageIcon(leftURL);
 
    public static URL bodyURL = Data.class.getResource("img/body.png");
    public static ImageIcon body = new ImageIcon(bodyURL);
 
    public static URL foodURL = Data.class.getResource("img/food.png");
    public static ImageIcon food = new ImageIcon(foodURL);
}

程序类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
 
/**
 * @author The Setting sun
 * @create 2021-09-11 15:24
 */
//游戏面板
public class GamePanel extends JPanel implements KeyListener, ActionListener {
    //蛇
    int length;//蛇的长度
    int[] snakeX = new int[600];//蛇的x坐标 25*25
    int[] snakeY = new int[500];//蛇的y坐标 25*25
    String orient;//初始方向
 
    //食物
    int foodX;
    int foodY;
    Random random = new Random();
 
    boolean isStart = false;//游戏当前状态:默认为停止
    boolean isFail = false;//游戏是否失败了,默认为没有
 
    int score;//积分
 
    //定时器 ms为单位
    Timer timer = new Timer(140, this);//100毫秒刷新一次
 
    //构造器
    public GamePanel() {
        init();//初始化
        setFocusable(true);//获得焦点
        addKeyListener(this);//获得键盘监听事件
        timer.start();//游戏一开始定时器就启动
    }
 
    //初始化
    public void init() {
        length = 3;//初始长度为3
 
        snakeX[0] = 100;
        snakeY[0] = 100;//头的坐标
 
        snakeX[1] = 75;
        snakeY[1] = 100;//第1个身体的坐标
 
        snakeX[2] = 50;
        snakeY[2] = 100;//第2个身体的坐标
 
        orient = "R";//初始方向向右
 
        //让食物随机分布在界面上
        foodX = 25 + 25 * random.nextInt(34);
        foodY = 75 + 25 * random.nextInt(24);
 
        score = 0;//积分
    }
 
 
    //绘制面板,游戏中的东西都用这个来画
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);//清屏
        setBackground(Color.pink);
 
        //绘制静态面板
        Data.header.paintIcon(this, g, 25, 11);
        g.fillRect(25, 75, 850, 600);
 
        //绘制积分面板
        g.setColor(Color.GREEN);
        g.setFont(new Font("微软雅黑", Font.BOLD, 16));
        g.drawString("长度:" + length, 750, 35);
        g.drawString("积分:" + score, 750, 50);
 
        //绘制食物
        Data.food.paintIcon(this, g, foodX, foodY);
 
        //绘制蛇
        switch (orient) {
            case "R":
                Data.right.paintIcon(this, g, snakeX[0], snakeY[0]);//蛇初始化向右,通过判断转变方向
                break;
            case "L":
                Data.left.paintIcon(this, g, snakeX[0], snakeY[0]);//蛇初始化向右,通过判断转变方向
                break;
            case "U":
                Data.up.paintIcon(this, g, snakeX[0], snakeY[0]);//蛇初始化向右,通过判断转变方向
                break;
            case "D":
                Data.down.paintIcon(this, g, snakeX[0], snakeY[0]);//蛇初始化向右,通过判断转变方向
                break;
        }
 
 
        //动态添加身体
        for (int i = 1; i < length; i++) {
            Data.body.paintIcon(this, g, snakeX[i], snakeY[i]);
        }
//        Data.body.paintIcon(this,g,snakeX[1],snakeY[1]);//第1个身体的坐标
//        Data.body.paintIcon(this,g,snakeX[2],snakeY[2]);//第2个身体的坐标
 
        //游戏状态
        if (isStart == false) {
            g.setColor(Color.WHITE);
            g.setFont(new Font("微软雅黑", Font.BOLD, 40));
            g.drawString("按下空格开始游戏", 300, 300);
        }
 
        if (isFail) {
            g.setColor(Color.RED);
            g.setFont(new Font("微软雅黑", Font.BOLD, 40));
            g.drawString("犹豫就会败北!", 300, 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();
            }
        }
 
        //修复了一个蛇可以反向移动的bug
        if (orient.equals("U") && keyCode == KeyEvent.VK_DOWN){
            keyCode = KeyEvent.VK_UP;
        }
 
        if (orient.equals("D") && keyCode == KeyEvent.VK_UP){
            keyCode = KeyEvent.VK_DOWN;
        }
 
        if (orient.equals("L") && keyCode == KeyEvent.VK_RIGHT){
            keyCode = KeyEvent.VK_LEFT;
        }
 
        if (orient.equals("R") && keyCode == KeyEvent.VK_LEFT){
            keyCode = KeyEvent.VK_RIGHT;
        }
 
        //控制蛇改变方向移动
        switch (keyCode) {
            case KeyEvent.VK_UP:
 
                orient = "U";
                break;
            case KeyEvent.VK_DOWN:
                orient = "D";
                break;
            case KeyEvent.VK_LEFT:
                orient = "L";
                break;
            case KeyEvent.VK_RIGHT:
                orient = "R";
                break;
        }
 
 
    }
 
    //事件监听:需要通过固定事件来刷新,1秒10次(帧率)
    @Override
    public void actionPerformed(ActionEvent e) {
        if (isStart && isFail == false) {//如果游戏是开始状态,就让蛇动起来
            //吃食物
            if (snakeX[0] == foodX && snakeY[0] == foodY) {
                //长度+1
                length++;
                score += 10;
 
                //再次让食物随机出现
                foodX = 25 + 25 * random.nextInt(34);
                foodY = 75 + 25 * random.nextInt(24);
            }
 
            //身体移动
            for (int i = length - 1; i > 0; i--) {
                snakeX[i] = snakeX[i - 1];
                snakeY[i] = snakeY[i - 1];
            }
 
            //走向
            switch (orient) {
                case "R":
                    snakeX[0] = snakeX[0] + 25;
                    //边界判断
                    if (snakeX[0] > 850) {
                        snakeX[0] = 25;
                    }
                    break;
                case "L":
                    snakeX[0] = snakeX[0] - 25;
                    //边界判断
                    if (snakeX[0] < 25) {
                        snakeX[0] = 850;
                    }
                    break;
                case "U":
                    snakeY[0] = snakeY[0] - 25;
                    //边界判断
                    if (snakeY[0] < 75) {
                        snakeY[0] = 650;
                    }
                    break;
                case "D":
                    snakeY[0] = snakeY[0] + 25;
                    //边界判断
                    if (snakeY[0] > 650) {
                        snakeY[0] = 75;
                    }
                    break;
            }
 
            //失败判断,撞到自己就GG
            for (int i = 1 ; i < length; i++) {
                if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]){
                    isFail = true;
                }
            }
 
            repaint();//刷新页面
        }
 
        timer.start();//定时器开启
    }
 
    @Override
    public void keyTyped(KeyEvent e) {
 
    }
 
    @Override
    public void keyReleased(KeyEvent e) {
 
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/m0_51642083/article/details/120256042

延伸 · 阅读

精彩推荐