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 final int WIDTH = 640;
    private final int HEIGHT = 640;

    // 定义贪吃蛇的初始位置和大小
    private final int DOT_SIZE = 10;
    private final int ALL_DOTS = 900;
    private final int RAND_POS = 40;
    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();
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                int key = e.getKeyCode();
                if (key == KeyEvent.VK_LEFT && !rightDirection) {
                    leftDirection = true;
                    upDirection = false;
                    downDirection = false;
                } else if (key == KeyEvent.VK_RIGHT && !leftDirection) {
                    rightDirection = true;
                    upDirection = false;
                    downDirection = false;
                } else if (key == KeyEvent.VK_UP && !downDirection) {
                    upDirection = true;
                    leftDirection = false;
                    rightDirection = false;
                } else if (key == KeyEvent.VK_DOWN && !upDirection) {
                    downDirection = true;
                    leftDirection = false;
                    rightDirection = false;
                }
            }
        });
        setFocusable(true);
    }

    public void initGame() {
        // 初始化游戏区域
        setTitle("SnakeGame");
        setSize(WIDTH, HEIGHT);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
        getContentPane().setBackground(Color.black);
        // 初始化贪吃蛇的位置和大小
        dots = 3;
        for (int i = 0; i < dots; i++) {
            x[i] = 50 - i * DOT_SIZE;
            y[i] = 50;
        }

        // 初始化苹果的位置
        locateApple();

        // 初始化计时器
        timer = new Timer(140, this);
        timer.start();
    }

    public 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;
    }

    public void checkApple() {
        // 检查贪吃蛇是否吃到了苹果
        if ((x[0] == apple_x) && (y[0] == apple_y)) {
            dots++;
            locateApple();
        }
    }

    public 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();
        }
    }

    public 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;
        }
    }

    public void actionPerformed(ActionEvent e) {
        // 计时器触发事件
        if (inGame) {
            checkApple();
            checkCollision();
            move();
            repaint(); // 重绘游戏区域
        }
    }

    public void paint(Graphics g) {

        // 绘制游戏区域
        super.paint(g);
        g.setColor(Color.black);

        if (inGame) {
            g.setColor(Color.red);
            g.fillOval(apple_x, apple_y, DOT_SIZE, DOT_SIZE);

            for (int i = 0; i < dots; i++) {
                g.setColor(Color.green);
                g.fillRect(x[i], y[i], DOT_SIZE, DOT_SIZE);
            }

            Toolkit.getDefaultToolkit().sync();
        } else {
            gameOver(g);
        }
    }

    public void gameOver(Graphics g) {
        // 游戏结束
        String msg = "GAME OVER";
        Font small = new Font("Helvetica", Font.BOLD, 40);
        FontMetrics metr = getFontMetrics(small);

        g.setColor(Color.white);
        g.setFont(small);
        g.drawString(msg, (WIDTH - metr.stringWidth(msg)) / 2, HEIGHT / 2);
    }


    public static void main(String[] args) {
        new SnakeGame();
    }
}

实机演示

JAVA练习小游戏——贪吃蛇小游戏

猜你喜欢

转载自blog.csdn.net/timberman666/article/details/131046742