贪吃蛇小游戏
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Random;
public class SnakeGame extends JPanel implements ActionListener {
private final int WIDTH = 800;
private final int HEIGHT = 600;
private final int SIZE = 20;
private ArrayList<Point> snake;
private Point food;
private String direction = "RIGHT";
private boolean running = true;
public SnakeGame() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
if (!direction.equals("DOWN")) direction = "UP";
break;
case KeyEvent.VK_DOWN:
if (!direction.equals("UP")) direction = "DOWN";
break;
case KeyEvent.VK_LEFT:
if (!direction.equals("RIGHT")) direction = "LEFT";
break;
case KeyEvent.VK_RIGHT:
if (!direction.equals("LEFT")) direction = "RIGHT";
break;
}
}
});
snake = new ArrayList<>();
snake.add(new Point(5, 5));
spawnFood();
Timer timer = new Timer(100, this);
timer.start();
}
private void spawnFood() {
Random random = new Random();
int x = random.nextInt(WIDTH / SIZE);
int y = random.nextInt(HEIGHT / SIZE);
food = new Point(x, y);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(food.x * SIZE, food.y * SIZE, SIZE, SIZE);
g.setColor(Color.GREEN);
for (Point p : snake) {
g.fillRect(p.x * SIZE, p.y * SIZE, SIZE, SIZE);
}
if (!running) {
g.setColor(Color.WHITE);
g.setFont(new Font("Arial", Font.BOLD, 30));
g.drawString("Game Over", WIDTH / 2 - 80, HEIGHT / 2);
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (running) {
moveSnake();
checkCollision();
checkFood();
repaint();
}
}
private void moveSnake() {
Point head = snake.get(0);
Point newHead = new Point(head);
switch (direction) {
case "UP": newHead.y--; break;
case "DOWN": newHead.y++; break;
case "LEFT": newHead.x--; break;
case "RIGHT": newHead.x++; break;
}
snake.add(0, newHead);
snake.remove(snake.size() - 1);
}
private void checkCollision() {
Point head = snake.get(0);
if (head.x < 0 || head.x >= WIDTH / SIZE || head.y < 0 || head.y >= HEIGHT / SIZE || snake.subList(1, snake.size()).contains(head)) {
running = false;
}
}
private void checkFood() {
if (snake.get(0).equals(food)) {
snake.add(new Point(food));
spawnFood();
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Snake Game");
SnakeGame game = new SnakeGame();
frame.add(game);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}