基于java中的main方法 生成贪吃蛇
时间: 2024-03-16 22:46:17 浏览: 14
好的,生成贪吃蛇的代码如下所示:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Snake extends JFrame implements ActionListener {
private final int WIDTH = 300;
private final int HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private 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;
private Image ball;
private Image apple;
private Image head;
public Snake() {
setTitle("Snake");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(WIDTH, HEIGHT);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
initGame();
}
private void initGame() {
dots = 3;
for (int i = 0; i < dots; i++) {
x[i] = 50 - i * 10;
y[i] = 50;
}
locateApple();
timer = new Timer(DELAY, this);
timer.start();
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (inGame) {
g.drawImage(apple, apple_x, apple_y, this);
for (int i = 0; i < dots; i++) {
if (i == 0) {
g.drawImage(head, x[i], y[i], this);
} else {
g.drawImage(ball, x[i], y[i], this);
}
}
Toolkit.getDefaultToolkit().sync();
} else {
gameOver(g);
}
}
private void gameOver(Graphics g) {
String message = "Game Over";
Font font = new Font("Helvetica", Font.BOLD, 14);
FontMetrics metrics = getFontMetrics(font);
g.setColor(Color.black);
g.setFont(font);
g.drawString(message, (WIDTH - metrics.stringWidth(message)) / 2, HEIGHT / 2);
}
private void checkApple() {
if ((x[0] == apple_x) && (y[0] == apple_y)) {
dots++;
locateApple();
}
}
private void move() {
for (int i = dots; i > 0; i--) {
x[i] = x[(i - 1)];
y[i] = y[(i - 1)];
}
if (leftDirection) {
x[0] -= DOT_SIZE;
}
if (rightDirection) {
x[0] += DOT_SIZE;
}
if (upDirection) {
y[0] -= DOT_SIZE;
}
if (downDirection) {
y[0] += DOT_SIZE;
}
}
private void checkCollision() {
for (int i = dots; i > 0; i--) {
if ((i > 4) && (x[0] == x[i]) && (y[0] == y[i])) {
inGame = false;
}
}
if (y[0] >= HEIGHT) {
inGame = false;
}
if (y[0] < 0) {
inGame = false;
}
if (x[0] >= WIDTH) {
inGame = false;
}
if (x[0] < 0) {
inGame = false;
}
if (!inGame) {
timer.stop();
}
}
private void locateApple() {
int r = (int) (Math.random() * RAND_POS);
apple_x = r * DOT_SIZE;
r = (int) (Math.random() * RAND_POS);
apple_y = r * DOT_SIZE;
}
@Override
public void actionPerformed(ActionEvent e) {
if (inGame) {
checkApple();
checkCollision();
move();
}
repaint();
}
public static void main(String[] args) {
new Snake();
}
}
```
这里我们使用了 Java 的图形界面组件库 Swing 和 AWT 来实现贪吃蛇游戏。该游戏含有基本的贪吃蛇的操作,包括蛇的移动、吃苹果、碰撞检测等。