用JAVA写一个简单游戏
时间: 2023-12-20 19:06:45 浏览: 27
以下是一个简单的Java游戏示例,名称为“Whack-a-Mole”(打地鼠):
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class WhackAMole extends JFrame implements ActionListener {
private static final int NUM_BUTTONS = 9;
private static final int GAME_TIME = 30;
private JButton[] buttons;
private int score;
private JLabel scoreLabel;
private Timer gameTimer;
private int timeLeft;
public WhackAMole() {
setTitle("Whack-a-Mole");
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3, 3));
buttons = new JButton[NUM_BUTTONS];
for (int i = 0; i < NUM_BUTTONS; i++) {
buttons[i] = new JButton(" ");
buttons[i].setActionCommand(Integer.toString(i));
buttons[i].addActionListener(this);
add(buttons[i]);
}
score = 0;
scoreLabel = new JLabel("Score: " + score);
add(scoreLabel);
gameTimer = new Timer(1000, new TimerListener());
timeLeft = GAME_TIME;
gameTimer.start();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
int buttonIndex = Integer.parseInt(e.getActionCommand());
if (buttons[buttonIndex].getText().equals("M")) {
score++;
scoreLabel.setText("Score: " + score);
}
}
private class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
timeLeft--;
if (timeLeft == 0) {
gameTimer.stop();
JOptionPane.showMessageDialog(null, "Time's up! Final score: " + score);
System.exit(0);
} else {
int randomIndex = (int) (Math.random() * NUM_BUTTONS);
for (int i = 0; i < NUM_BUTTONS; i++) {
if (i == randomIndex) {
buttons[i].setText("M");
} else {
buttons[i].setText(" ");
}
}
}
}
}
public static void main(String[] args) {
new WhackAMole();
}
}
```
这个游戏有9个按钮,每秒钟随机一个按钮上会出现一个“M”(地鼠),玩家需要在游戏时间内尽可能多地点击出现的地鼠,最后显示分数。