请用Java编写一段贪吃蛇程序
时间: 2023-08-08 19:04:54 浏览: 224
以下是一个简单的Java贪吃蛇程序的代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SnakeGame extends JFrame implements KeyListener, ActionListener {
private int width = 600; // 窗口宽度
private int height = 600; // 窗口高度
private int blockSize = 10; // 方块大小
private int blockNum = width / blockSize * height / blockSize; // 方块数量
private int[] snakeX = new int[blockNum]; // 蛇身x坐标
private int[] snakeY = new int[blockNum]; // 蛇身y坐标
private int snakeLength = 3; // 蛇身长度
private int foodX; // 食物x坐标
private int foodY; // 食物y坐标
private int direction = 0; // 蛇头方向(0:向上,1:向下,2:向左,3:向右)
private Timer timer; // 定时器
public SnakeGame() {
setTitle("贪吃蛇");
setSize(width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
addKeyListener(this);
// 初始化蛇身位置
snakeX[0] = width / blockSize / 2 * blockSize;
snakeY[0] = height / blockSize / 2 * blockSize;
// 初始化食物位置
newFood();
// 启动定时器
timer = new Timer(100, this);
timer.start();
}
public void paint(Graphics g) {
super.paint(g);
// 绘制蛇身
g.setColor(Color.GREEN);
for (int i = 0; i < snakeLength; i++) {
g.fillRect(snakeX[i], snakeY[i], blockSize, blockSize);
}
// 绘制食物
g.setColor(Color.RED);
g.fillRect(foodX, foodY, blockSize, blockSize);
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
// 改变蛇头方向
if (key == KeyEvent.VK_UP && direction != 1) {
direction = 0;
}
if (key == KeyEvent.VK_DOWN && direction != 0) {
direction = 1;
}
if (key == KeyEvent.VK_LEFT && direction != 3) {
direction = 2;
}
if (key == KeyEvent.VK_RIGHT && direction != 2) {
direction = 3;
}
}
public void actionPerformed(ActionEvent e) {
// 移动蛇身
for (int i = snakeLength - 1; i > 0; i--) {
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
// 移动蛇头
if (direction == 0) {
snakeY[0] -= blockSize;
}
if (direction == 1) {
snakeY[0] += blockSize;
}
if (direction == 2) {
snakeX[0] -= blockSize;
}
if (direction == 3) {
snakeX[0] += blockSize;
}
// 判断是否吃到食物
if (snakeX[0] == foodX && snakeY[0] == foodY) {
snakeLength++;
newFood();
}
// 判断是否撞墙或自身
for (int i = 1; i < snakeLength; i++) {
if (snakeX[i] == snakeX[0] && snakeY[i] == snakeY[0]) {
gameOver();
}
}
if (snakeX[0] < 0 || snakeX[0] >= width || snakeY[0] < 0 || snakeY[0] >= height) {
gameOver();
}
// 重绘窗口
repaint();
}
private void newFood() {
foodX = (int) (Math.random() * (width / blockSize)) * blockSize;
foodY = (int) (Math.random() * (height / blockSize)) * blockSize;
}
private void gameOver() {
timer.stop();
JOptionPane.showMessageDialog(this, "游戏结束");
System.exit(0);
}
public static void main(String[] args) {
new SnakeGame();
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}
```
这个程序使用Java的Swing框架实现了一个简单的贪吃蛇游戏。游戏窗口大小为600x600,每个方块大小为10x10,蛇身和食物都是方块。通过键盘上下左右箭头控制蛇头方向,蛇身长度随着吃到食物逐渐增加,当蛇头碰到墙或者自身时游戏结束。程序使用了定时器来不断更新蛇身和食物位置,并通过重绘窗口来实现动态效果。
阅读全文