Java编写的贪吃蛇小游戏

仅供学习分享!

贪吃蛇是一款经典的游戏,早在20世纪80年代就已经出现。游戏规则非常简单,玩家控制一条蛇在屏幕上爬行,通过吃食物来增加蛇的长度,同时避免撞到墙壁或自身。

这个Java版的贪吃蛇小游戏采用了Java Swing图形界面库,通过继承JFrame类来创建窗口。游戏中,蛇和食物都是由一个个方格组成的,每个方格大小相同,蛇每吃到一个食物就会增加一个方格。

在Java中,我们可以通过继承JPanel类来创建游戏界面。在这个游戏中,我们需要创建三个面板:游戏面板、得分面板和游戏结束面板。游戏面板用于显示蛇和食物,得分面板用于显示玩家得分,游戏结束面板用于显示游戏结束的信息。

在游戏面板中,我们需要实现键盘监听器,通过监听玩家按键来控制蛇的移动方向。当蛇吃到食物时,我们需要重新生成一个食物,并且将蛇的长度加一。当蛇撞到墙壁或自身时,游戏结束,弹出游戏结束面板。

整个游戏的实现过程中,我们需要注意的是,需要使用线程来控制游戏的运行。游戏的运行过程中,需要不断地更新蛇的位置、检测是否吃到食物、检测是否撞到墙壁或自身等操作。如果在主线程中执行这些操作,会导致游戏界面卡顿,影响游戏体验。因此,我们需要使用一个游戏线程来处理这些操作。

实现的简要思路:

  1. 初始化游戏界面,包括窗口大小、标题、图片资源等。
  2. 初始化蛇的位置和长度,随机放置一个苹果。
  3. 启动一个定时器,定时移动蛇的每个部分,检查蛇是否吃到了苹果,是否碰到了边界或自己的身体,更新游戏状态和屏幕显示。
  4. 监听键盘事件,根据键盘事件更新蛇的移动方向。
  5. 如果游戏结束,停止定时器,显示游戏结束的提示信息。

简洁版详细代码如下(需要注释说明的的在下边,后期加的注释。。。。):

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SnakeGame 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 SnakeGame() {
        initGame();
        initUI();
    }

    private void initGame() {
        dots = 3;
        for (int i = 0; i < dots; i++) {
            x[i] = 50 - i * DOT_SIZE;
            y[i] = 50;
        }

        locateApple();

        timer = new Timer(DELAY, this);
        timer.start();
    }

    private void initUI() {
        setTitle("Snake");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(WIDTH, HEIGHT);
        setResizable(false);

        ImageIcon iid = new ImageIcon(getClass().getResource("dot.png"));
        ball = iid.getImage();

        ImageIcon iia = new ImageIcon(getClass().getResource("apple.png"));
        apple = iia.getImage();

        ImageIcon iih = new ImageIcon(getClass().getResource("head.png"));
        head = iih.getImage();

        addKeyListener(new TAdapter());
    }

    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 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 msg = "Game Over";
        Font small = new Font("Helvetica", Font.BOLD, 14);
        FontMetrics metr = getFontMetrics(small);

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

    @Override
    public void actionPerformed(ActionEvent e) {
        if (inGame) {
            checkApple();
            checkCollision();
            move();
        }

        repaint();
    }

    private class TAdapter extends KeyAdapter {
        @Override
        public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();

            if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) {
                leftDirection = true;
                upDirection = false;
                downDirection = false;
            }

            if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) {
                rightDirection = true;
                upDirection = false;
                downDirection = false;
            }

            if ((key == KeyEvent.VK_UP) && (!downDirection)) {
                upDirection = true;
                rightDirection = false;
                leftDirection = false;
            }

            if ((key == KeyEvent.VK_DOWN) && (!upDirection)) {
                downDirection = true;
                rightDirection = false;
                leftDirection = false;
            }
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            SnakeGame ex = new SnakeGame();
            ex.setVisible(true);
        });
    }
}

  在具体实现中,需要用到一些基本的Java语法和图形界面编程知识,例如数组、定时器、键盘事件监听器、图像绘制等。需要注意的是,由于贪吃蛇的移动是连续的,因此定时器的时间间隔需要适当调整,以保证游戏的流畅性和难度。同时,为了避免蛇的身体重叠,需要在每次移动前先移动蛇的尾部,再移动蛇的头部,这样就可以实现贪吃蛇的移动效果了。

有注释的版本:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SnakeGame 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 SnakeGame() {
        initGame();
        initUI();
    }

    private void initGame() {
        // 初始化蛇的位置和长度
        dots = 3;
        for (int i = 0; i < dots; i++) {
            x[i] = 50 - i * DOT_SIZE;
            y[i] = 50;
        }

        // 随机放置苹果
        locateApple();

        // 启动定时器
        timer = new Timer(DELAY, this);
        timer.start();
    }

    private void initUI() {
        // 初始化游戏窗口
        setTitle("Snake");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(WIDTH, HEIGHT);
        setResizable(false);

        // 加载图片资源
        ImageIcon iid = new ImageIcon(getClass().getResource("dot.png"));
        ball = iid.getImage();

        ImageIcon iia = new ImageIcon(getClass().getResource("apple.png"));
        apple = iia.getImage();

        ImageIcon iih = new ImageIcon(getClass().getResource("head.png"));
        head = iih.getImage();

        // 添加键盘事件监听器
        addKeyListener(new TAdapter());
    }

    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 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 msg = "Game Over";
        Font small = new Font("Helvetica", Font.BOLD, 14);
        FontMetrics metr = getFontMetrics(small);

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

    @Override
    public void actionPerformed(ActionEvent e) {
        if (inGame) {
            // 检查蛇是否吃到了苹果,是否碰到了边界或自己的身体,移动蛇的每个部分
            checkApple();
            checkCollision();
            move();
        }

        // 刷新屏幕
        repaint();
    }

    private class TAdapter extends KeyAdapter {
        @Override
        public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();

            // 根据键盘事件更新蛇的移动方向
            if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) {
                leftDirection = true;
                upDirection = false;
                downDirection = false;
            }

            if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) {
                rightDirection = true;
                upDirection = false;
                downDirection = false;
            }

            if ((key == KeyEvent.VK_UP) && (!downDirection)) {
                upDirection = true;
                rightDirection = false;
                leftDirection = false;
            }

            if ((key == KeyEvent.VK_DOWN) && (!upDirection)) {
                downDirection = true;
                rightDirection = false;
                leftDirection = false;
            }
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            SnakeGame ex = new SnakeGame();
            ex.setVisible(true);
        });
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ヾ草木萤火(≧▽≦*)o

希望大家多多支持,我会继续分享

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值