带时间的java小游戏,不要省略代码
时间: 2024-03-16 12:47:10 浏览: 29
好的,以下是一个简单的Java小游戏,可以让用户在规定时间内点击屏幕上随机出现的按钮,尽可能多地得分。
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ClickGame extends JFrame implements ActionListener {
private JButton button;
private JLabel scoreLabel;
private Timer timer;
private int score = 0;
public ClickGame() {
super("Click Game");
// 创建按钮
button = new JButton("Click me!");
button.addActionListener(this);
// 创建得分标签
scoreLabel = new JLabel("Score: " + score);
// 将按钮和得分标签添加到窗口
getContentPane().add(button, BorderLayout.CENTER);
getContentPane().add(scoreLabel, BorderLayout.SOUTH);
// 创建计时器
timer = new Timer(1000, this);
timer.setInitialDelay(0);
timer.start();
// 设置窗口属性
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
// 点击了按钮,加分并更新得分标签
score++;
scoreLabel.setText("Score: " + score);
// 移动按钮到随机位置
int x = (int) (Math.random() * (getWidth() - button.getWidth()));
int y = (int) (Math.random() * (getHeight() - button.getHeight()));
button.setLocation(x, y);
} else if (e.getSource() == timer) {
// 时间到了,计算最终得分并提示用户
timer.stop();
int finalScore = score * 10 / (timer.getDelay() / 1000);
JOptionPane.showMessageDialog(this, "Time's up! Your score is: " + finalScore);
dispose();
}
}
public static void main(String[] args) {
new ClickGame();
}
}
```
该程序使用Java Swing库创建了一个简单的窗口,其中包含一个按钮和一个得分标签。在计时器的作用下,每秒钟按钮会随机移动到窗口中的一个新位置。用户需要在规定时间内尽可能多地点击按钮,以获得更高的得分。时间到了后,程序会计算最终得分并提示用户。