用java写一个贪吃蛇游戏
时间: 2023-05-23 20:04:54 浏览: 85
A:
下面是一个简单的贪吃蛇游戏的Java代码,注释中有详细解释。这个代码实现了一个基础的轮廓,你可以根据自己的需要添加更多的功能。
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SnakeGame extends JFrame implements KeyListener {
// 游戏面板的大小
private static final int WIDTH = 20, HEIGHT = 20;
// 蛇的长度、蛇的位置、食物的位置
private int length;
private int[] snakeX = new int[WIDTH * HEIGHT];
private int[] snakeY = new int[WIDTH * HEIGHT];
private int foodX;
private int foodY;
// 方向
private boolean up, down, left, right;
// 游戏是否进行中
private boolean isPlaying;
public SnakeGame() {
// 初始化
isPlaying = true;
length = 3;
up = false;
down = false;
left = false;
right = true;
// 设置窗口属性
setTitle("贪吃蛇小游戏");
setSize(500, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// 添加键盘监听器
addKeyListener(this);
// 设置画布属性
JPanel gamePanel = new JPanel();
gamePanel.setPreferredSize(new Dimension(500, 500));
gamePanel.setBackground(Color.gray);
add(gamePanel);
// 设置食物的位置
generateFood();
// 开始游戏
playGame(gamePanel);
}
// 绘制游戏面板
public void drawGamePanel(Graphics g) {
// 绘制蛇的头部和身体
for (int i = 0; i < length; i++) {
if (i == 0) {
g.setColor(Color.red);
g.fillRect(snakeX[i] * 20, snakeY[i] * 20, 20, 20);
} else {
g.setColor(Color.green);
g.fillRect(snakeX[i] * 20, snakeY[i] * 20, 20, 20);
}
}
// 绘制食物
g.setColor(Color.yellow);
g.fillRect(foodX * 20, foodY * 20, 20, 20);
}
// 生成食物
public void generateFood() {
foodX = (int) (Math.random() * WIDTH);
foodY = (int) (Math.random() * HEIGHT);
}
// 游戏逻辑
public void playGame(JPanel gamePanel) {
while (isPlaying) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 移动蛇的身体
for (int i = length; i > 0; i--) {
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
// 移动蛇的头部
if (up) snakeY[0]--;
if (down) snakeY[0]++;
if (left) snakeX[0]--;
if (right) snakeX[0]++;
// 判断是否吃到食物
if (snakeX[0] == foodX && snakeY[0] == foodY) {
length++;
generateFood();
}
// 判断是否撞墙或撞到自己
if (snakeX[0] < 0 || snakeX[0] >= WIDTH || snakeY[0] < 0 || snakeY[0] >= HEIGHT) {
isPlaying = false;
JOptionPane.showMessageDialog(gamePanel, "游戏结束!");
}
for (int i = 1; i < length; i++) {
if (snakeX[i] == snakeX[0] && snakeY[i] == snakeY[0]) {
isPlaying = false;
JOptionPane.showMessageDialog(gamePanel, "游戏结束!");
}
}
// 重新绘制游戏面板
gamePanel.repaint();
}
}
// 键盘事件
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_UP && !down) {
up = true;
right = false;
left = false;
}
if (key == KeyEvent.VK_DOWN && !up) {
down = true;
right = false;
left = false;
}
if (key == KeyEvent.VK_LEFT && !right) {
left = true;
up = false;
down = false;
}
if (key == KeyEvent.VK_RIGHT && !left) {
right = true;
up = false;
down = false;
}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
public static void main(String[] args) {
new SnakeGame().setVisible(true);
}
}
```
阅读全文