使用Java实现一个贪吃蛇游戏(运行即可玩)
public class SnakeGame extends JFrame {
private int gameSize = 10;
private int gameWidth = 50;
private int gameHeight = 50;
private int direction = KeyEvent.VK_RIGHT;
private List<Point> snake;
private Point food;
public SnakeGame() {
setTitle("贪吃蛇游戏");
setSize(gameWidth * gameSize, gameHeight * gameSize);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
snake = new ArrayList<>();
snake.add(new Point(0, 0));
generateFood();
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if ((key == KeyEvent.VK_LEFT && direction != KeyEvent.VK_RIGHT) ||
(key == KeyEvent.VK_RIGHT && direction != KeyEvent.VK_LEFT) ||
(key == KeyEvent.VK_UP && direction != KeyEvent.VK_DOWN) ||
(key == KeyEvent.VK_DOWN && direction != KeyEvent.VK_UP)) {
direction = key;
}
}
});
Timer timer = new Timer(200, e -> {
move();
checkCollision();
repaint();
});
timer.start();
}
@Override
public void paint(Graphics g) {
super.paint(g);
for (Point point : snake) {
drawSquare(g, point, Color.GREEN);
}
drawSquare(g, food, Color.RED);
}
private void drawSquare(Graphics g, Point point, Color color) {
g.setColor(color);
g.fillRect(point.x * gameSize, point.y * gameSize, gameSize, gameSize);
}
private void move() {
Point head = new Point(snake.get(0));
if (direction == KeyEvent.VK_LEFT) {
head.x--;
} else if (direction == KeyEvent.VK_RIGHT) {
head.x++;
} else if (direction == KeyEvent.VK_UP) {
head.y--;
} else if (direction == KeyEvent.VK_DOWN) {
head.y++;
}
snake.add(0, head);
if (head.equals(food)) {
generateFood();
} else {
snake.remove(snake.size() - 1);
}
}
private void generateFood() {
Random random = new Random();
int x, y;
do {
x = random.nextInt(gameWidth);
y = random.nextInt(gameHeight);
} while (snake.contains(new Point(x, y)));
food = new Point(x, y);
}
private void checkCollision() {
Point head = snake.get(0);
if (head.x < 0 || head.x >= gameWidth || head.y < 0 || head.y >= gameHeight) {
gameOver();
}
for (int i = 1; i < snake.size(); i++) {
if (head.equals(snake.get(i))) {
gameOver();
}
}
}
private void gameOver() {
JOptionPane.showMessageDialog(this, "Game Over");
System.exit(0);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
SnakeGame game = new SnakeGame();
game.setVisible(true);
});
}
}
效果如图:(代码中有注释,可以自行更改,方向键移动,方向键下为开始游戏)
