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

贪吃蛇游戏(代码+超详细注释)

哈喽哈喽大家好,下面呢我编了一个Java的小游戏,大家可以玩一下,代码随便复制,不过要标清楚原创哦

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.Random; /** * Java贪吃蛇游戏主类 * 包含游戏逻辑、渲染和输入处理 */ public class SnakeGame extends JPanel implements ActionListener { // 游戏面板尺寸 private final int BOARD_WIDTH = 600; private final int BOARD_HEIGHT = 600; // 每个网格单元的大小 private final int UNIT_SIZE = 25; // 游戏刷新延迟(毫秒),控制速度 private final int DELAY = 100; // 蛇身体坐标数组 private final int[] x = new int[(BOARD_WIDTH * BOARD_HEIGHT) / (UNIT_SIZE * UNIT_SIZE)]; private final int[] y = new int[(BOARD_WIDTH * BOARD_HEIGHT) / (UNIT_SIZE * UNIT_SIZE)]; // 蛇的身体部分数量 private int bodyParts = 6; // 苹果吃的数量(分数) private int applesEaten = 0; // 苹果的坐标 private int appleX; private int appleY; // 当前移动方向: 'R'右, 'L'左, 'U'上, 'D'下 private char direction = 'R'; // 游戏是否正在运行 private boolean running = false; // 定时器,用于驱动游戏循环 private Timer timer; // 随机数生成器,用于生成苹果位置 private Random random; /** * 构造函数,初始化游戏组件 */ public SnakeGame() { random = new Random(); this.setPreferredSize(new Dimension(BOARD_WIDTH, BOARD_HEIGHT)); this.setBackground(Color.BLACK); this.setFocusable(true); // 添加键盘监听器以控制蛇的移动 this.addKeyListener(new MyKeyAdapter()); startGame(); } /** * 启动游戏,初始化状态并启动定时器 */ public void startGame() { newApple(); running = true; timer = new Timer(DELAY, this); timer.start(); } /** * 绘制游戏画面 * @param g 图形上下文 */ public void paintComponent(Graphics g) { super.paintComponent(g); draw(g); } /** * 具体的绘制逻辑 * @param g 图形上下文 */ public void draw(Graphics g) { if (running) { // 绘制网格线(可选,这里为了简洁省略,直接画背景) // 绘制苹果 g.setColor(Color.RED); g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE); // 绘制蛇 for (int i = 0; i < bodyParts; i++) { if (i == 0) { // 蛇头颜色 g.setColor(Color.GREEN); } else { // 蛇身颜色 g.setColor(new Color(45, 180, 0)); } g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE); } // 绘制分数 g.setColor(Color.WHITE); g.setFont(new Font("Arial", Font.BOLD, 40)); FontMetrics metrics = getFontMetrics(g.getFont()); g.drawString("Score: " + applesEaten, (BOARD_WIDTH - metrics.stringWidth("Score: " + applesEaten)) / 2, g.getFont().getSize()); } else { // 游戏结束画面 gameOver(g); } } /** * 生成新的苹果位置,确保不生成在蛇身上 */ public void newApple() { // 计算网格列数和行数 int cols = BOARD_WIDTH / UNIT_SIZE; int rows = BOARD_HEIGHT / UNIT_SIZE; // 随机生成苹果坐标,对齐网格 appleX = random.nextInt(cols) * UNIT_SIZE; appleY = random.nextInt(rows) * UNIT_SIZE; } /** * 移动蛇的逻辑 */ public void move() { // 身体跟随头部移动:从尾部开始,每一节移动到前一节的位置 for (int i = bodyParts; i > 0; i--) { x[i] = x[i - 1]; y[i] = y[i - 1]; } // 根据方向移动头部 switch (direction) { case 'U': y -= UNIT_SIZE; break; case 'D': y += UNIT_SIZE; break; case 'L': x -= UNIT_SIZE; break; case 'R': x += UNIT_SIZE; break; } } /** * 检查是否吃到苹果 */ public void checkApple() { if ((x == appleX) && (y == appleY)) { bodyParts++; applesEaten++; newApple(); } } /** * 检查碰撞(撞墙或撞自己) */ public void checkCollisions() { // 检查头部是否撞到身体 for (int i = bodyParts; i > 0; i--) { if ((x == x[i]) && (y == y[i])) { running = false; break; } } // 检查头部是否撞墙 // 左边界 if (x < 0) { running = false; } // 右边界 if (x >= BOARD_WIDTH) { running = false; } // 上边界 if (y < 0) { running = false; } // 下边界 if (y >= BOARD_HEIGHT) { running = false; } if (!running) { timer.stop(); } } /** * 显示游戏结束画面 * @param g 图形上下文 */ public void gameOver(Graphics g) { // 显示分数 g.setColor(Color.RED); g.setFont(new Font("Arial", Font.BOLD, 75)); FontMetrics metrics1 = getFontMetrics(g.getFont()); g.drawString("Score: " + applesEaten, (BOARD_WIDTH - metrics1.stringWidth("Score: " + applesEaten)) / 2, g.getFont().getSize()); // 显示Game Over文本 g.setColor(Color.RED); g.setFont(new Font("Arial", Font.BOLD, 75)); FontMetrics metrics2 = getFontMetrics(g.getFont()); g.drawString("Game Over", (BOARD_WIDTH - metrics2.stringWidth("Game Over")) / 2, BOARD_HEIGHT / 2); } /** * 定时器动作事件,每帧调用 * @param e 动作事件 */ @Override public void actionPerformed(ActionEvent e) { if (running) { move(); checkApple(); checkCollisions(); } repaint(); } /** * 内部类,处理键盘输入 */ public class MyKeyAdapter extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_LEFT: if (direction != 'R') { direction = 'L'; } break; case KeyEvent.VK_RIGHT: if (direction != 'L') { direction = 'R'; } break; case KeyEvent.VK_UP: if (direction != 'D') { direction = 'U'; } break; case KeyEvent.VK_DOWN: if (direction != 'U') { direction = 'D'; } break; } } } /** * 主方法,启动游戏窗口 * @param args 命令行参数 */ public static void main(String[] args) { JFrame frame = new JFrame("Snake Game"); SnakeGame game = new SnakeGame(); frame.add(game); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.pack(); frame.setVisible(true); frame.setLocationRelativeTo(null); // 窗口居中 } }
http://www.gsyq.cn/news/1339161.html

相关文章:

  • 基于STM32+RTOS智能家居控制系统实现(已实现全部功能)
  • 【Redis -01】Redis 零基础运维实战!全网最常用 Linux 命令大全(工作直接抄)
  • 苹果手机快速开启开发者模式教程(iOS 16+)
  • AMD Ryzen终极调试工具:硬件级性能调优完全指南
  • 终极指南:119,376个英语单词发音MP3音频一键下载完整教程 [特殊字符]
  • 2026年新品:资深高压锅炉管研发厂家 - 品牌推广大师
  • 给OpenWrt路由器写个简易“设备管家”:用Shell脚本自动记录并通知新设备上线
  • 听完了AMD的AI开发者大会,我算清了两笔账!
  • 深度学习视频压缩技术解析与应用实践
  • 贵阳西服定制标杆:老合兴洋服,凭四大核心优势圈粉无数 - 贵州服装测评君
  • 如何快速掌握uesave:Unreal引擎存档编辑的完整指南
  • RT-DETRv2训练自定义数据集的排坑全记录
  • AI设计泳装,能颠覆今夏潮流?
  • 冲压送料机远程监控运维管理系统方案
  • Python利用openpyxl库写入或修改xlsx文件
  • 学生心理测评系统哪家好?2026谁能守护青少年心理健康? - 健成星云
  • 使用 curl 命令直接测试 Taotoken 聊天接口的连通性与返回格式
  • 2026年4月市面上有名的活性炭公司口碑推荐,杏壳活性炭/净水活性炭/煤质柱状活性炭/食品级活性炭,活性炭品牌找哪家 - 品牌推荐师
  • 如何快速掌握SPT-AKI存档编辑器:离线版塔科夫玩家的终极修改指南
  • 影刀RPA跨境店群运营架构:TikTok Shop与TEMU高并发Python调度引擎实战
  • 越南语TTS合规生死线:GDPR+越南《个人数据保护法令》双框架下ElevenLabs语音日志清理SOP
  • 使用Taotoken后API调用稳定性与延迟的实际体验观察
  • 【仅限前500名设计师获取】Midjourney双色调调色板生成器(含17组经Adobe Color验证的高转化配色矩阵)
  • AI 不锈钢电热保温杯智能功率 MOSFET 完整选型方案
  • 零基础考医师资格证,怎么选辅导机构? - 医考机构品牌测评专家
  • 2026年太原漏水检测维修靠谱公司推荐榜:精准测漏、查漏水、测漏水、地埋管漏水、漏水维修、防水维修服务商甄选指南 - 海棠依旧大
  • Windhawk终极指南:5分钟掌握Windows系统个性化定制
  • 3分钟彻底清理Windows系统:Win11Debloat让你的电脑重获新生
  • 从零训练潮州话语音克隆模型:ElevenLabs Fine-tuning实战(附1782条标注语料清洗脚本)
  • 如何三步免费下载百度文库文档:智能清理与打印保存完整指南