生成一个java版贪吃蛇游戏
时间: 2024-05-01 07:23:45 浏览: 86
好的,以下是一个简单的Java版贪吃蛇游戏:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SnakeGame extends JFrame implements ActionListener {
private static final int ROWS = 20;
private static final int COLS = 20;
private static final int CELL_SIZE = 25;
private static final int WINDOW_WIDTH = ROWS * CELL_SIZE;
private static final int WINDOW_HEIGHT = COLS * CELL_SIZE;
private JButton startButton = new JButton("Start");
private JButton stopButton = new JButton("Stop");
private JPanel buttonPanel = new JPanel();
private JPanel gamePanel = new JPanel();
private Timer timer;
private int[][] gameBoard = new int[ROWS][COLS];
private int[] snakeX = new int[ROWS * COLS];
private int[] snakeY = new int[ROWS * COLS];
private int snakeLength = 3;
private int direction = KeyEvent.VK_RIGHT;
private int foodX, foodY;
private boolean gameOver = false;
public SnakeGame() {
setTitle("Snake Game");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonPanel.add(startButton);
buttonPanel.add(stopButton);
add(buttonPanel, BorderLayout.NORTH);
gamePanel.setBackground(Color.WHITE);
gamePanel.setPreferredSize(new Dimension(WINDOW_WIDTH, WINDOW_HEIGHT));
add(gamePanel, BorderLayout.CENTER);
startButton.addActionListener(this);
stopButton.addActionListener(this);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_DOWN) {
direction = keyCode;
}
}
});
setResizable(false);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == startButton) {
startGame();
} else if (source == stopButton) {
stopGame();
}
}
private void startGame() {
initGame();
timer = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent e) {
moveSnake();
checkCollision();
repaint();
}
});
timer.start();
}
private void stopGame() {
timer.stop();
gameOver = true;
JOptionPane.showMessageDialog(this, "Game Over");
}
private void initGame() {
// Initialize game board
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
gameBoard[i][j] = 0;
}
}
// Initialize snake
snakeX[0] = ROWS / 2;
snakeY[0] = COLS / 2;
snakeX[1] = snakeX[0] - 1;
snakeY[1] = snakeY[0];
snakeX[2] = snakeX[1] - 1;
snakeY[2] = snakeY[1];
snakeLength = 3;
// Generate food
generateFood();
gameOver = false;
}
private void generateFood() {
foodX = (int) (Math.random() * ROWS);
foodY = (int) (Math.random() * COLS);
if (gameBoard[foodX][foodY] != 0) {
generateFood();
}
}
private void moveSnake() {
// Move snake body
for (int i = snakeLength - 1; i > 0; i--) {
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
// Move snake head
switch (direction) {
case KeyEvent.VK_LEFT:
snakeY[0]--;
break;
case KeyEvent.VK_RIGHT:
snakeY[0]++;
break;
case KeyEvent.VK_UP:
snakeX[0]--;
break;
case KeyEvent.VK_DOWN:
snakeX[0]++;
break;
}
// Check if snake eats food
if (snakeX[0] == foodX && snakeY[0] == foodY) {
// Increase snake length
snakeLength++;
// Generate new food
generateFood();
}
// Update game board
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
gameBoard[i][j] = 0;
}
}
for (int i = 0; i < snakeLength; i++) {
gameBoard[snakeX[i]][snakeY[i]] = 1;
}
gameBoard[foodX][foodY] = 2;
}
private void checkCollision() {
// Check if snake hits wall
if (snakeX[0] < 0 || snakeX[0] >= ROWS || snakeY[0] < 0 || snakeY[0] >= COLS) {
stopGame();
return;
}
// Check if snake hits itself
for (int i = 1; i < snakeLength; i++) {
if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
stopGame();
return;
}
}
}
public void paint(Graphics g) {
super.paint(g);
// Draw game board
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
switch (gameBoard[i][j]) {
case 0:
g.setColor(Color.WHITE);
break;
case 1:
g.setColor(Color.GREEN);
break;
case 2:
g.setColor(Color.RED);
break;
}
g.fillRect(j * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE);
}
}
}
public static void main(String[] args) {
new SnakeGame();
}
}
```
该游戏基于 Swing UI 框架,使用了 Java 的定时器来控制游戏进程,通过监听键盘事件来改变蛇的方向。在游戏界面中,使用``JPanel``和``JButton``来创建一个简单的界面。游戏窗口的大小为20*20,每个格子的大小为25*25。游戏的主要逻辑在``startGame()``和``moveSnake()``方法中实现,其中``moveSnake()``方法控制蛇的移动和食物的生成,``startGame()``方法初始化游戏,并启动定时器。
阅读全文