帮我用Java写一个贪吃蛇‘
时间: 2023-05-20 18:03:13 浏览: 85
好的,我可以为您提供一个简单的贪吃蛇游戏的Java代码,如下所示:
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SnakeGame extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel gamePanel;
private JLabel statusLabel;
private Timer timer;
private int delay = 100;
private int score = 0;
private int snakeX[] = new int[1000];
private int snakeY[] = new int[1000];
private int snakeLength = 3;
private int foodX, foodY;
private int direction = 0;
private boolean gameOver = false;
public SnakeGame() {
setTitle("贪吃蛇");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
gamePanel = new JPanel();
gamePanel.setBackground(Color.WHITE);
gamePanel.setLayout(null);
add(gamePanel);
statusLabel = new JLabel("得分: 0");
statusLabel.setBounds(10, 10, 100, 20);
gamePanel.add(statusLabel);
timer = new Timer(delay, this);
timer.start();
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT && direction != 1) {
direction = 0;
} else if (key == KeyEvent.VK_RIGHT && direction != 0) {
direction = 1;
} else if (key == KeyEvent.VK_UP && direction != 3) {
direction = 2;
} else if (key == KeyEvent.VK_DOWN && direction != 2) {
direction = 3;
}
}
});
initGame();
}
private void initGame() {
snakeLength = 3;
snakeX[0] = 50;
snakeY[0] = 50;
snakeX[1] = 40;
snakeY[1] = 50;
snakeX[2] = 30;
snakeY[2] = 50;
direction = 1;
score = 0;
statusLabel.setText("得分: " + score);
generateFood();
gameOver = false;
}
private void generateFood() {
foodX = (int) (Math.random() * 38) * 10;
foodY = (int) (Math.random() * 38) * 10;
}
private void move() {
for (int i = snakeLength - 1; i > 0; i--) {
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
if (direction == 0) {
snakeX[0] -= 10;
} else if (direction == 1) {
snakeX[0] += 10;
} else if (direction == 2) {
snakeY[0] -= 10;
} else if (direction == 3) {
snakeY[0] += 10;
}
if (snakeX[0] < 0 || snakeX[0] > 380 || snakeY[0] < 0 || snakeY[0] > 380) {
gameOver = true;
}
for (int i = 1; i < snakeLength; i++) {
if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
gameOver = true;
}
}
if (snakeX[0] == foodX && snakeY[0] == foodY) {
snakeLength++;
score += 10;
statusLabel.setText("得分: " + score);
generateFood();
}
}
public void paint(Graphics g) {
super.paint(g);
if (!gameOver) {
g.setColor(Color.RED);
g.fillRect(foodX, foodY, 10, 10);
g.setColor(Color.BLACK);
for (int i = 0; i < snakeLength; i++) {
g.fillRect(snakeX[i], snakeY[i], 10, 10);
}
} else {
g.setColor(Color.BLACK);
g.drawString("游戏结束", 180, 180);
}
}
public void actionPerformed(ActionEvent e) {
if (!gameOver) {
move();
repaint();
} else {
timer.stop();
}
}
public static void main(String[] args) {
new SnakeGame().setVisible(true);
}
}
```
希望这个代码对您有所帮助!
阅读全文