用java写一个贪吃蛇代码
时间: 2024-05-12 16:13:37 浏览: 82
java写贪吃蛇代码
好的,以下是一个简单的Java贪吃蛇代码:
```java
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class Snake extends JFrame implements KeyListener {
private static final long serialVersionUID = 1L;
private final int width = 400;
private final int height = 400;
private final int size = 20;
private final int rows = height / size;
private final int cols = width / size;
private int snakeX, snakeY;
private int foodX, foodY;
private int snakeLength = 2;
private int direction = KeyEvent.VK_RIGHT;
private ArrayList<Integer> snakeXList = new ArrayList<Integer>();
private ArrayList<Integer> snakeYList = new ArrayList<Integer>();
private Timer timer;
public Snake() {
super("Snake");
setPreferredSize(new Dimension(width, height));
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
addKeyListener(this);
startGame();
}
public void startGame() {
snakeX = cols / 2 * size;
snakeY = rows / 2 * size;
snakeXList.clear();
snakeYList.clear();
for (int i = 0; i < snakeLength; i++) {
snakeXList.add(snakeX - i * size);
snakeYList.add(snakeY);
}
newFood();
timer = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent e) {
moveSnake();
}
});
timer.start();
}
public void newFood() {
foodX = (int) (Math.random() * cols) * size;
foodY = (int) (Math.random() * rows) * size;
}
public void moveSnake() {
switch (direction) {
case KeyEvent.VK_LEFT:
snakeX -= size;
break;
case KeyEvent.VK_RIGHT:
snakeX += size;
break;
case KeyEvent.VK_UP:
snakeY -= size;
break;
case KeyEvent.VK_DOWN:
snakeY += size;
break;
}
snakeXList.add(0, snakeX);
snakeYList.add(0, snakeY);
if (snakeX == foodX && snakeY == foodY) {
newFood();
snakeLength++;
} else {
snakeXList.remove(snakeLength);
snakeYList.remove(snakeLength);
}
if (snakeX < 0 || snakeX >= width || snakeY < 0 || snakeY >= height ||
snakeXList.indexOf(snakeX) != 0 || snakeYList.indexOf(snakeY) != 0) {
timer.stop();
JOptionPane.showMessageDialog(this, "Game Over");
startGame();
}
repaint();
}
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
g.setColor(Color.RED);
g.fillRect(foodX, foodY, size, size);
g.setColor(Color.BLACK);
for (int i = 0; i < snakeLength; i++) {
g.fillRect(snakeXList.get(i), snakeYList.get(i), size, size);
}
}
public void keyPressed(KeyEvent e) {
int newDirection = e.getKeyCode();
if (newDirection == KeyEvent.VK_LEFT && direction != KeyEvent.VK_RIGHT ||
newDirection == KeyEvent.VK_RIGHT && direction != KeyEvent.VK_LEFT ||
newDirection == KeyEvent.VK_UP && direction != KeyEvent.VK_DOWN ||
newDirection == KeyEvent.VK_DOWN && direction != KeyEvent.VK_UP) {
direction = newDirection;
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
new Snake();
}
}
```
这个程序使用Java Swing在窗口中绘制游戏界面,使用ArrayList来存储蛇的位置,使用Java Timer来控制蛇的移动。你可以使用键盘上的方向键来控制蛇的方向,吃到食物后蛇的长度会增加。当蛇碰到墙壁或自己时,游戏结束。
阅读全文