设计一个贪吃蛇游戏利用java并且具有暂停功能

时间: 2024-02-21 20:02:25 浏览: 16
好的,下面是一个简单的贪吃蛇游戏的Java代码,同时也包含了暂停功能的实现: ```java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SnakeGame extends JFrame implements ActionListener { private final int WIDTH = 500; // 游戏窗口宽度 private final int HEIGHT = 500; // 游戏窗口高度 private final int UNIT_SIZE = 10; // 蛇身体单位大小 private final int MAX_UNITS = (WIDTH * HEIGHT) / UNIT_SIZE; // 蛇身体最大长度 private final int DELAY = 100; // 游戏速度 private int x[] = new int[MAX_UNITS]; // 蛇身体X坐标 private int y[] = new int[MAX_UNITS]; // 蛇身体Y坐标 private int bodyParts = 6; // 蛇身体长度 private int appleX; // 苹果X坐标 private int appleY; // 苹果Y坐标 private char direction = 'R'; // 蛇移动方向 private boolean running = false; // 游戏是否正在运行 private Timer timer; // 游戏计时器 private JButton pauseButton; // 暂停按钮 public SnakeGame() { initGame(); initUI(); } private void initGame() { // 初始化游戏 addKeyListener(new MyKeyAdapter()); setPreferredSize(new Dimension(WIDTH, HEIGHT)); setBackground(Color.BLACK); setFocusable(true); initSnake(); newApple(); running = true; timer = new Timer(DELAY, this); timer.start(); } private void initUI() { // 初始化UI界面 pauseButton = new JButton("暂停"); pauseButton.addActionListener(this); JPanel buttonPanel = new JPanel(); buttonPanel.add(pauseButton); add(buttonPanel, BorderLayout.SOUTH); pack(); setLocationRelativeTo(null); setVisible(true); } private void initSnake() { // 初始化蛇 bodyParts = 6; for (int i = 0; i < bodyParts; i++) { x[i] = (WIDTH / 2) - (i * UNIT_SIZE); y[i] = (HEIGHT / 2); } } private void newApple() { // 新增苹果 appleX = (int) (Math.random() * (WIDTH / UNIT_SIZE)) * UNIT_SIZE; appleY = (int) (Math.random() * (HEIGHT / UNIT_SIZE)) * UNIT_SIZE; } private void move() { // 蛇的移动 for (int i = bodyParts; i > 0; i--) { x[i] = x[(i - 1)]; y[i] = y[(i - 1)]; } switch (direction) { case 'U': y[0] = y[0] - UNIT_SIZE; break; case 'D': y[0] = y[0] + UNIT_SIZE; break; case 'L': x[0] = x[0] - UNIT_SIZE; break; case 'R': x[0] = x[0] + UNIT_SIZE; break; } } private void checkApple() { // 检查是否吃到苹果 if ((x[0] == appleX) && (y[0] == appleY)) { bodyParts++; newApple(); } } private void checkCollision() { // 检查碰撞 for (int i = bodyParts; i > 0; i--) { if ((x[0] == x[i]) && (y[0] == y[i])) { running = false; } } if (x[0] < 0) { running = false; } if (x[0] > WIDTH) { running = false; } if (y[0] < 0) { running = false; } if (y[0] > HEIGHT) { running = false; } if (!running) { timer.stop(); } } private void gameOver(Graphics g) { // 游戏结束 String message = "游戏结束!"; Font font = new Font("Times New Roman", Font.BOLD, 30); FontMetrics metrics = getFontMetrics(font); g.setColor(Color.WHITE); g.setFont(font); g.drawString(message, (WIDTH - metrics.stringWidth(message)) / 2, (HEIGHT / 2)); } @Override public void actionPerformed(ActionEvent e) { if (running) { move(); checkApple(); checkCollision(); } repaint(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); draw(g); } private 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); g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE); } else { g.setColor(Color.YELLOW); g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE); } } } else { gameOver(g); } } private 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; } } } public static void main(String[] args) { new SnakeGame(); } } ``` 上述代码中,实现了一个简单的贪吃蛇游戏,并且包含了暂停功能。具体实现方式为在界面下方添加一个“暂停”按钮,点击后暂停游戏计时器,游戏界面停止更新。

相关推荐

最新推荐

recommend-type

基于Java的贪吃蛇设计

基于java的贪吃蛇设计,简单实现,文档, ecplise编程 附录源码
recommend-type

使用Python第三方库pygame写个贪吃蛇小游戏

主要介绍了使用Python第三方库pygame写个贪吃蛇小游戏,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
recommend-type

基于VHDL语言的贪吃蛇设计

基于VHDL语言的贪吃蛇设计,点阵实现蛇的移动,数码管记录显示分数,游戏有时间设定
recommend-type

scrapy练习 获取喜欢的书籍

主要是根据网上大神做的 项目一 https://zhuanlan.zhihu.com/p/687522335
recommend-type

基于PyTorch的Embedding和LSTM的自动写诗实验.zip

基于PyTorch的Embedding和LSTM的自动写诗实验LSTM (Long Short-Term Memory) 是一种特殊的循环神经网络(RNN)架构,用于处理具有长期依赖关系的序列数据。传统的RNN在处理长序列时往往会遇到梯度消失或梯度爆炸的问题,导致无法有效地捕捉长期依赖。LSTM通过引入门控机制(Gating Mechanism)和记忆单元(Memory Cell)来克服这些问题。 以下是LSTM的基本结构和主要组件: 记忆单元(Memory Cell):记忆单元是LSTM的核心,用于存储长期信息。它像一个传送带一样,在整个链上运行,只有一些小的线性交互。信息很容易地在其上保持不变。 输入门(Input Gate):输入门决定了哪些新的信息会被加入到记忆单元中。它由当前时刻的输入和上一时刻的隐藏状态共同决定。 遗忘门(Forget Gate):遗忘门决定了哪些信息会从记忆单元中被丢弃或遗忘。它也由当前时刻的输入和上一时刻的隐藏状态共同决定。 输出门(Output Gate):输出门决定了哪些信息会从记忆单元中输出到当前时刻的隐藏状态中。同样地,它也由当前时刻的输入和上一时刻的隐藏状态共同决定。 LSTM的计算过程可以大致描述为: 通过遗忘门决定从记忆单元中丢弃哪些信息。 通过输入门决定哪些新的信息会被加入到记忆单元中。 更新记忆单元的状态。 通过输出门决定哪些信息会从记忆单元中输出到当前时刻的隐藏状态中。 由于LSTM能够有效地处理长期依赖关系,它在许多序列建模任务中都取得了很好的效果,如语音识别、文本生成、机器翻译、时序预测等。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

【实战演练】MATLAB用遗传算法改进粒子群GA-PSO算法

![MATLAB智能算法合集](https://static.fuxi.netease.com/fuxi-official/web/20221101/83f465753fd49c41536a5640367d4340.jpg) # 2.1 遗传算法的原理和实现 遗传算法(GA)是一种受生物进化过程启发的优化算法。它通过模拟自然选择和遗传机制来搜索最优解。 **2.1.1 遗传算法的编码和解码** 编码是将问题空间中的解表示为二进制字符串或其他数据结构的过程。解码是将编码的解转换为问题空间中的实际解的过程。常见的编码方法包括二进制编码、实数编码和树形编码。 **2.1.2 遗传算法的交叉和
recommend-type

openstack的20种接口有哪些

以下是OpenStack的20种API接口: 1. Identity (Keystone) API 2. Compute (Nova) API 3. Networking (Neutron) API 4. Block Storage (Cinder) API 5. Object Storage (Swift) API 6. Image (Glance) API 7. Telemetry (Ceilometer) API 8. Orchestration (Heat) API 9. Database (Trove) API 10. Bare Metal (Ironic) API 11. DNS
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。