写一个贪吃蛇JAVA
时间: 2023-02-23 13:00:10 浏览: 33
java写的贪吃蛇
写贪吃蛇游戏需要编写代码,可以使用 Java 语言实现。以下是一个简单的 Java 贪吃蛇代码的例子:
```
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
import javax.swing.JFrame;
public class SnakeGame extends JFrame {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 300, HEIGHT = 300;
private static final int DOT_SIZE = 10;
private static final int ALL_DOTS = 900;
private static final int RAND_POS = 29;
private static final int DELAY = 140;
private int x[] = new int[ALL_DOTS];
private int y[] = new int[ALL_DOTS];
private int dots;
private int apple_x;
private int apple_y;
private boolean leftDirection = false;
private boolean rightDirection = true;
private boolean upDirection = false;
private boolean downDirection = false;
private boolean inGame = true;
private Timer timer;
public SnakeGame() {
initGame();
}
private void initGame() {
setBackground(Color.black);
setSize(WIDTH, HEIGHT);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
addKeyListener(new Keyboard());
timer = new Timer(DELAY, new GameCycle());
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
private void doDrawing(Graphics g) {
if (inGame) {
g.setColor(Color.red);
g.fillOval(apple_x, apple_y, DOT_SIZE, DOT_SIZE);
for (int i = 0; i < dots; i++) {
if (i == 0) {
g.setColor(Color.green);
} else {
g.setColor(Color.yellow);
}
g.fillOval(x[i], y[i], DOT_SIZE, DOT_SIZE);
}
} else {
gameOver(g);
}
}
private void gameOver(Graphics g) {
String message = "Game Over";
g.setColor(Color.white);
g.drawString(message, 125, HEIGHT / 2);
}
private class Keyboard extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) {
leftDirection = true;
upD
阅读全文