答案:使用Java Swing创建打地鼠游戏,通过JFrame构建窗口,JButton模拟地洞,随机显示地鼠图标,玩家点击得分,配合Timer实现计时与刷新, JLabel显示分数和倒计时,完成基础逻辑后可扩展音效、图片资源及难度升级功能。

开发一个简单的“打地鼠”小游戏,用Java完全可以实现。你可以使用Swing或JavaFX来构建图形界面。下面以Swing为例,带你一步步完成一个基础版本的打地鼠游戏。
打地鼠的核心机制是:多个地洞中随机出现地鼠,玩家点击地鼠得分,没打中或超时则不加分。可以设定时间限制和计分系统。
关键要素包括:
使用JFrame作为主窗口,JButton作为地洞,JLabel显示分数和倒计时。
立即学习“Java免费学习笔记(深入)”;
示例代码框架:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class WhackAMole extends JFrame {
private int score = 0;
private int timeLeft = 30; // 游戏总时间(秒)
private Random random = new Random();
private JButton[] holes = new JButton[9]; // 9个地洞
private Timer gameTimer, moleTimer;
private JLabel scoreLabel, timeLabel;
public WhackAMole() {
setTitle("打地鼠");
setSize(400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// 分数和时间显示
JPanel topPanel = new JPanel();
scoreLabel = new JLabel("得分: 0");
timeLabel = new JLabel("剩余时间: 30");
topPanel.add(scoreLabel);
topPanel.add(timeLabel);
add(topPanel, BorderLayout.NORTH);
// 地洞区域
JPanel holePanel = new JPanel(new GridLayout(3, 3));
for (int i = 0; i < 9; i++) {
holes[i] = new JButton();
holes[i].setPreferredSize(new Dimension(80, 80));
final int index = i;
holes[i].addActionListener(e -> whack(index));
holePanel.add(holes[i]);
}
add(holePanel, BorderLayout.CENTER);
// 启动游戏
startGame();
}
private void startGame() {
// 每秒更新时间
gameTimer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
timeLeft--;
timeLabel.setText("剩余时间: " + timeLeft);
if (timeLeft <= 0) {
((Timer)e.getSource()).stop();
moleTimer.stop();
JOptionPane.showMessageDialog(null, "游戏结束!你的得分: " + score);
}
}
});
gameTimer.start();
// 控制地鼠出现频率(比如每800毫秒换一次位置)
moleTimer = new Timer(800, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 清除所有地鼠
for (JButton hole : holes) {
hole.setIcon(null);
}
// 随机选一个地洞出现地鼠
int r = random.nextInt(9);
holes[r].setIcon(new ImageIcon("mole.png")); // 准备一张mole.png图片
}
});
moleTimer.start();
}
private void whack(int index) {
if (holes[index].getIcon() != null) {
score++;
scoreLabel.setText("得分: " + score);
holes[index].setIcon(null); // 打中后消失
} else {
// 可以加个“打空”提示音或反馈
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeel());
} catch (Exception e) { }
new WhackAMole().setVisible(true);
});
}
}
为了让游戏更完整,你可以做这些改进:
javax.sound.sampled播放打中或失败音效运行前确保项目目录下有名为“mole.png”的图片资源,或者改用系统图标代替,例如:
// 替代方案:用文字表示地鼠holes[r].setText("?");如果打包成jar,记得把图片资源放在src/main/resources并用getClass().getResource()加载。
以上就是如何用Java开发小游戏打地鼠的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号