用Java编写一个贪吃蛇游戏
时间: 2023-09-16 11:15:00 浏览: 75
好的,下面是一个简单的Java贪吃蛇游戏示例代码:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SnakeGame extends JPanel implements Runnable, KeyListener {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public static final int DOT_SIZE = 10;
private static final int INITIAL_SNAKE_SIZE = 10;
private List<Point> snake = new ArrayList<Point>();
private int direction = KeyEvent.VK_RIGHT;
private Point food = new Point(0, 0);
private Random random = new Random();
private boolean running = true;
public SnakeGame() {
JFrame frame = new JFrame("Snake Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.setResizable(false);
frame.add(this);
frame.addKeyListener(this);
frame.setVisible(true);
for (int i = 0; i < INITIAL_SNAKE_SIZE; i++) {
snake.add(new Point(50 - i * DOT_SIZE, 50));
}
spawnFood();
}
private void spawnFood() {
int x = random.nextInt(WIDTH / DOT_SIZE) * DOT_SIZE;
int y = random.nextInt(HEIGHT / DOT_SIZE) * DOT_SIZE;
food.setLocation(x, y);
}
private void move() {
Point head = snake.get(0);
Point newHead = new Point(head);
switch (direction) {
case KeyEvent.VK_LEFT:
newHead.x -= DOT_SIZE;
break;
case KeyEvent.VK_RIGHT:
newHead.x += DOT_SIZE;
break;
case KeyEvent.VK_UP:
newHead.y -= DOT_SIZE;
break;
case KeyEvent.VK_DOWN:
newHead.y += DOT_SIZE;
break;
}
if (newHead.equals(food)) {
snake.add(0, newHead);
spawnFood();
} else {
snake.remove(snake.size() - 1);
snake.add(0, newHead);
}
if (snakeCollidesWithItself()) {
running = false;
}
if (snakeHitsWall()) {
running = false;
}
}
private boolean snakeCollidesWithItself() {
Point head = snake.get(0);
for (int i = 1; i < snake.size(); i++) {
Point part = snake.get(i);
if (head.equals(part)) {
return true;
}
}
return false;
}
private boolean snakeHitsWall() {
Point head = snake.get(0);
if (head.x < 0 || head.x >= WIDTH || head.y < 0 || head.y >= HEIGHT) {
return true;
}
return false;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
for (Point part : snake) {
g.fillRect(part.x, part.y, DOT_SIZE, DOT_SIZE);
}
g.setColor(Color.RED);
g.fillRect(food.x, food.y, DOT_SIZE, DOT_SIZE);
}
public static void main(String[] args) {
new SnakeGame().start();
}
public void start() {
Thread t = new Thread(this);
t.start();
}
@Override
阅读全文