打地鼠小游戏通过Swing实现图形界面,使用JButton模拟地鼠洞,Timer控制地鼠随机出现, ActionListener处理点击事件判断是否击中并更新分数,结合GridLayout布局和事件监听机制完成交互,适合掌握Java GUI编程基础。

开发一个打地鼠小游戏在Java中是很好的练手项目,能帮助你掌握图形界面、事件处理和定时任务等核心知识点。下面是一个基于Swing的简单实现思路和关键代码结构。
使用Java Swing创建图形界面,不需要额外依赖库。你需要准备以下类:
每个“地鼠洞”可以用一个JButton表示,点击时判断是否有地鼠出现。
使用JFrame作为窗口容器,JPanel放置多个按钮模拟地鼠洞。
立即学习“Java免费学习笔记(深入)”;
public class MoleGame extends JPanel {
private JButton[] holes = new JButton[9]; // 3x3 洞
private boolean[] hasMole = new boolean[9]; // 记录哪个洞有地鼠
private int score = 0;
private Random rand = new Random();
public MoleGame() {
setLayout(new GridLayout(3, 3));
for (int i = 0; i < 9; i++) {
holes[i] = new JButton("");
holes[i].setFont(new Font("Arial", Font.BOLD, 20));
final int index = i;
holes[i].addActionListener(e -> hit(index));
add(holes[i]);
}
// 每500毫秒随机出现一次地鼠
Timer timer = new Timer(500, e -> showMole());
timer.start();
}
}
用定时器控制地鼠随机出现在某个洞中,持续很短时间后消失。
private void showMole() {
// 先清除所有地鼠
for (int i = 0; i < 9; i++) {
hasMole[i] = false;
holes[i].setText("");
}
// 随机选一个洞出地鼠
int hole = rand.nextInt(9);
hasMole[hole] = true;
holes[hole].setText("?");
}
当玩家点击按钮时,检查该位置是否有地鼠,有则加分。
private void hit(int index) {
if (hasMole[index]) {
score++;
System.out.println("打中!当前分数:" + score);
hasMole[index] = false;
holes[index].setText("✅"); // 反馈击中
} else {
System.out.println("没打中!");
}
}
可以在界面上加一个JLabel显示实时分数,进一步提升体验。
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("打地鼠");
MoleGame game = new MoleGame();
frame.add(game);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
运行后你会看到一个3x3的按钮网格,地鼠会随机出现,点击它就能得分。
基本上就这些。你可以在此基础上增加难度(缩短出现时间)、计时器(倒计时60秒)、音效或图片替换文字图标,让游戏更有趣。关键是理解Swing事件机制和Timer的使用方式。
以上就是在Java中如何开发小游戏打地鼠的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号