java打地鼠小游戏代码
时间: 2023-06-19 14:06:37 浏览: 143
以下是一个简单的 Java 打地鼠小游戏代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class WhackAMole extends JFrame implements ActionListener {
private JButton[] buttons;
private JLabel scoreLabel;
private int score;
private int molesRemaining;
private Timer timer;
public WhackAMole() {
super("Whack-a-Mole");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 4));
setSize(400, 400);
score = 0;
molesRemaining = 16;
buttons = new JButton[16];
for (int i = 0; i < 16; i++) {
buttons[i] = new JButton(" ");
buttons[i].addActionListener(this);
add(buttons[i]);
}
scoreLabel = new JLabel("Score: " + score + " Moles Remaining: " + molesRemaining);
add(scoreLabel);
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
int randomButton = (int) (Math.random() * 16);
buttons[randomButton].setText("M");
timer.setDelay((int) (Math.random() * 1000) + 500);
}
});
timer.start();
}
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button.getText().equals("M")) {
score++;
molesRemaining--;
} else {
score--;
}
button.setText(" ");
scoreLabel.setText("Score: " + score + " Moles Remaining: " + molesRemaining);
if (molesRemaining == 0) {
timer.stop();
JOptionPane.showMessageDialog(this, "Game Over! Final Score: " + score);
}
}
public static void main(String[] args) {
WhackAMole game = new WhackAMole();
game.setVisible(true);
}
}
```
这个代码创建了一个 4x4 的按钮网格,其中每个按钮都有可能在随机时间内显示“M”(代表地鼠),玩家需要在出现后尽快点击按钮来“打地鼠”,每次打中会增加得分并减少剩余地鼠数量,每次未打中则减少得分,游戏结束时会弹出得分提示窗口。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)