用Java语言写一个打地鼠游戏
时间: 2023-07-20 20:08:52 浏览: 44
好的,下面是一个简单的打地鼠游戏的Java代码,希望能对你有所帮助。
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class WhackAMole extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel scoreLabel;
private int score = 0;
private JButton[] buttons;
public WhackAMole() {
super("打地鼠");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 4));
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("得分: 0", SwingConstants.CENTER);
add(scoreLabel);
setSize(500, 500);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button.getText().equals("地鼠")) {
score++;
scoreLabel.setText("得分: " + score);
button.setText("");
}
}
public void run() {
while (true) {
try {
Thread.sleep((int) (Math.random() * 3000));
int index = (int) (Math.random() * 16);
buttons[index].setText("地鼠");
Thread.sleep((int) (Math.random() * 2000));
buttons[index].setText("");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
WhackAMole game = new WhackAMole();
new Thread() {
public void run() {
game.run();
}
}.start();
}
}
```
这个程序创建了一个 `JFrame` 窗口,其中包含 16 个按钮和一个标签。每次单击按钮时,如果该按钮上显示了“地鼠”,则得分加 1。程序还启动了一个线程,随机在 16 个按钮中的某一个上显示“地鼠”,并在一段时间后将其清除。