当前位置: 首页 > article >正文

基于java的贪吃蛇小游戏

贪吃蛇游戏需要做两点:图形界面和游戏逻辑。在 Java 中,可以使用 Swing 或 JavaFX 来创建图形界面。下面代码创建了一个简单的 Swing 窗口,实现了一个基本的贪吃蛇游戏。在游戏中,使用方向键控制贪吃蛇的移动,吃到食物会增加蛇的长度,如果蛇撞到墙壁或者自己的身体,则游戏结束。

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Random;

public class SnakeGame extends JFrame implements ActionListener, KeyListener {
    private ArrayList<Point> snake;
    private Point fruit;
    private Timer timer;
    private int direction;
    private boolean gameOver;

    public SnakeGame() {
        setTitle("贪吃蛇游戏");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 400);
        setLocationRelativeTo(null);

        snake = new ArrayList<>();
        snake.add(new Point(10, 10));
        fruit = new Point(5, 5);

        direction = KeyEvent.VK_RIGHT;
        gameOver = false;

        timer = new Timer(100, this);
        timer.start();

        addKeyListener(this);
        setFocusable(true);
        setFocusTraversalKeysEnabled(false);

        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if (!gameOver) {
            move();
            checkCollision();
            checkFruit();
            repaint();
        }
    }

    public void paint(Graphics g) {
        super.paint(g);
        if (!gameOver) {
            g.setColor(Color.RED);
            g.fillRect(fruit.x * 20, fruit.y * 20, 20, 20);

            g.setColor(Color.GREEN);
            for (Point point : snake) {
                g.fillRect(point.x * 20, point.y * 20, 20, 20);
            }
        } else {
            g.setColor(Color.BLACK);
            g.setFont(new Font("Arial", Font.BOLD, 30));
            g.drawString("游戏结束", 130, 200);
        }
    }

    public void move() {
        for (int i = snake.size() - 1; i > 0; i--) {
            snake.get(i).x = snake.get(i - 1).x;
            snake.get(i).y = snake.get(i - 1).y;
        }

        switch (direction) {
            case KeyEvent.VK_UP:
                snake.get(0).y--;
                break;
            case KeyEvent.VK_DOWN:
                snake.get(0).y++;
                break;
            case KeyEvent.VK_LEFT:
                snake.get(0).x--;
                break;
            case KeyEvent.VK_RIGHT:
                snake.get(0).x++;
                break;
        }
    }

    public void checkCollision() {
        Point head = snake.get(0);
        if (head.x < 0 || head.x >= 20 || head.y < 0 || head.y >= 20) {
            gameOver = true;
            timer.stop();
        }

        for (int i = 1; i < snake.size(); i++) {
            if (head.x == snake.get(i).x && head.y == snake.get(i).y) {
                gameOver = true;
                timer.stop();
                break;
            }
        }
    }

    public void checkFruit() {
        Point head = snake.get(0);
        if (head.x == fruit.x && head.y == fruit.y) {
            snake.add(new Point(snake.get(snake.size() - 1)));
            generateFruit();
        }
    }

    public void generateFruit() {
        Random random = new Random();
        boolean validFruit = false;

        while (!validFruit) {
            int x = random.nextInt(20);
            int y = random.nextInt(20);
            fruit = new Point(x, y);

            boolean collision = false;
            for (Point point : snake) {
                if (fruit.x == point.x && fruit.y == point.y) {
                    collision = true;
                    break;
                }
            }

            if (!collision) {
                validFruit = true;
            }
        }
    }

    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        if ((key == KeyEvent.VK_LEFT || key == KeyEvent.VK_RIGHT || key == KeyEvent.VK_UP || key == KeyEvent.VK_DOWN) &&
                (key + direction) % 2 != 0) {
            direction = key;
        }
    }

    public void keyReleased(KeyEvent e) {
    }

    public void keyTyped(KeyEvent e) {
    }

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

http://www.kler.cn/a/162710.html

相关文章:

  • 矩阵的各种计算:乘法、逆矩阵、转置、行列式等——基于Excel实现
  • 欧国联的规则,你都了解吗?
  • Prompt 工程
  • 【C++】详解RAII思想与智能指针
  • 「QT」几何数据类 之 QLine 整型直线类
  • 把握鸿蒙生态崛起的机遇:开发者视角的探讨
  • Zabbix 执行自定义key脚本超时timeout while executing a shell script
  • Linux C语言 39-进程间通信IPC之管道
  • 【科学炼丹指南】机器学习最科学、最有效的参数优化全流程实现方法
  • VUE学习一、环境的安装
  • 【力扣100】8.找到字符串中所有字母异位词
  • HarmonyOS通过OpenGL渲染显示yuv数据
  • modbus转profinet网关解决plc插槽号不够用的情况
  • Numpy数组的运算(第7讲)
  • BUUCTF-WEB-刷题记录(2)
  • Netty03-核心组件NioEventLoopGroup解读
  • 使用Rust Rayon库提升程序运行速度
  • Pytest+Allure生成自动化测试报告!
  • WebGL笔记:矩阵旋转运算的原理和实现
  • stm32串口编程实例-实现数据的收发功能
  • 【CVE 复现】CVE-2022-0185 fsconfig之整数溢出
  • LinuxBasicsForHackers笔记 -- 使用和滥用服务
  • 自动化测试框架需要具备哪些功能?
  • 2、Redis变慢原因排查(下)
  • 使用Echarts.js绘制环形图(指定触发高亮事件)
  • Python中读写(解析)JSON文件的深入探究