写个贪吃蛇java代码
时间: 2023-07-02 22:14:02 浏览: 232
好的,以下是一个简单的Java贪吃蛇游戏代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SnakeGame extends JFrame implements ActionListener {
private JPanel board;
private JButton start;
private JLabel score;
private Timer timer;
private int delay = 100;
private int[] x = new int[100];
private int[] y = new int[100];
private int bodyParts = 3;
private int applesEaten = 0;
private int appleX;
private int appleY;
private char direction = 'R';
public SnakeGame() {
setTitle("Snake Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
board = new JPanel();
board.setBackground(Color.BLACK);
board.setLayout(null);
add(board);
start = new JButton("Start");
start.setBounds(150, 300, 100, 30);
start.addActionListener(this);
board.add(start);
score = new JLabel("Score: 0");
score.setForeground(Color.WHITE);
score.setBounds(10, 10, 100, 20);
board.add(score);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
if (direction != 'R') direction = 'L';
break;
case KeyEvent.VK_RIGHT:
if (direction != 'L') direction = 'R';
break;
case KeyEvent.VK_UP:
if (direction != 'D') direction = 'U';
break;
case KeyEvent.VK_DOWN:
if (direction != 'U') direction = 'D';
break;
}
}
});
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == start) {
start();
} else {
move();
checkCollision();
checkApple();
board.repaint();
}
}
public void start() {
start.setEnabled(false);
x[0] = 0;
y[0] = 0;
x[1] = -10;
y[1] = 0;
x[2] = -20;
y[2] = 0;
generateApple();
timer = new Timer(delay, this);
timer.start();
}
public void generateApple() {
appleX = (int) (Math.random() * 39) * 10;
appleY = (int) (Math.random() * 39) * 10;
}
public void move() {
for (int i = bodyParts; i > 0; i--) {
x[i] = x[i - 1];
y[i] = y[i - 1];
}
switch (direction) {
case 'L':
x[0] -= 10;
break;
case 'R':
x[0] += 10;
break;
case 'U':
y[0] -= 10;
break;
case 'D':
y[0] += 10;
break;
}
}
public void checkCollision() {
for (int i = bodyParts; i > 0; i--) {
if (x[0] == x[i] && y[0] == y[i]) {
gameOver();
}
}
if (x[0] < 0 || x[0] > 390 || y[0] < 0 || y[0] > 390) {
gameOver();
}
}
public void checkApple() {
if (x[0] == appleX && y[0] == appleY) {
bodyParts++;
applesEaten++;
score.setText("Score: " + applesEaten);
generateApple();
}
}
public void gameOver() {
start.setEnabled(true);
timer.stop();
JOptionPane.showMessageDialog(this, "Game Over!");
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.RED);
g.fillRect(appleX, appleY, 10, 10);
for (int i = 0; i < bodyParts; i++) {
if (i == 0) {
g.setColor(Color.GREEN);
} else {
g.setColor(Color.WHITE);
}
g.fillRect(x[i], y[i], 10, 10);
}
}
public static void main(String[] args) {
new SnakeGame();
}
}
```
这个代码创建了一个简单的贪吃蛇游戏,玩家可以使用方向键控制贪吃蛇的移动,吃掉苹果得分。如果贪吃蛇撞到边界或者自己的身体,则游戏结束。
阅读全文