带时间的java小游戏
时间: 2023-08-29 10:06:18 浏览: 41
好的,以下是一个带时间限制的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 JLabel timeLabel;
private Timer timer;
private int score = 0;
private int timeLeft = 60;
public ClickGame() {
super("Click Game");
// 创建按钮
button = new JButton("Click me!");
button.addActionListener(this);
// 创建得分标签
scoreLabel = new JLabel("Score: " + score);
// 创建时间标签
timeLabel = new JLabel("Time left: " + timeLeft);
// 将按钮、得分标签和时间标签添加到窗口
getContentPane().add(button, BorderLayout.CENTER);
getContentPane().add(scoreLabel, BorderLayout.NORTH);
getContentPane().add(timeLabel, 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) {
// 时间到了,计算最终得分并提示用户
timeLeft--;
timeLabel.setText("Time left: " + timeLeft);
if (timeLeft == 0) {
timer.stop();
int finalScore = score * 10;
JOptionPane.showMessageDialog(this, "Time's up! Your score is: " + finalScore);
dispose();
}
}
}
public static void main(String[] args) {
new ClickGame();
}
}
```
该程序与上一个示例程序相似,但添加了一个时间标签和一个60秒的时间限制。在计时器的作用下,每秒钟按钮会随机移动到窗口中的一个新位置。用户需要在60秒的时间内尽可能多地点击按钮,以获得更高的得分。时间到了后,程序会计算最终得分并提示用户。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.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)