java编写程序,用 GUI 和线程实现一个打字的小游戏,程序每隔一定时间(自行设置时间,比如5秒)随机给出一个汉字,玩家输入正确即可得分。
时间: 2024-03-10 21:43:56 浏览: 20
以下是一个简单的Java程序,实现了基于GUI和线程的打字小游戏:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class TypingGame extends JFrame implements ActionListener {
private JLabel characterLabel;
private JTextField inputField;
private JButton startButton;
private JLabel scoreLabel;
private Random random;
private Thread thread;
private boolean isRunning;
private int score;
public TypingGame() {
super("打字游戏");
// 初始化界面
characterLabel = new JLabel("");
characterLabel.setFont(new Font("宋体", Font.PLAIN, 72));
inputField = new JTextField(10);
startButton = new JButton("开始游戏");
startButton.addActionListener(this);
scoreLabel = new JLabel("得分:0");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(characterLabel);
panel.add(inputField);
panel.add(startButton);
panel.add(scoreLabel);
getContentPane().add(panel);
// 初始化游戏
random = new Random();
isRunning = false;
score = 0;
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == startButton) {
if (isRunning) {
stopGame();
} else {
startGame();
}
}
}
private void startGame() {
isRunning = true;
startButton.setText("结束游戏");
inputField.setText("");
score = 0;
scoreLabel.setText("得分:" + score);
thread = new Thread(new Runnable() {
public void run() {
while (isRunning) {
// 随机生成一个汉字
int codePoint = random.nextInt(20902) + 19968;
final String character = new String(Character.toChars(codePoint));
// 在界面上显示汉字
SwingUtilities.invokeLater(new Runnable() {
public void run() {
characterLabel.setText(character);
}
});
// 等待一段时间
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
// 检查输入是否正确
String input = inputField.getText();
if (input.equals(character)) {
score++;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
scoreLabel.setText("得分:" + score);
}
});
}
}
}
});
thread.start();
}
private void stopGame() {
isRunning = false;
startButton.setText("开始游戏");
thread.interrupt();
}
public static void main(String[] args) {
new TypingGame();
}
}
```
程序中使用了Swing库来构建GUI界面,使用了线程来实现定时任务和UI更新。具体来说,程序启动后,用户点击“开始游戏”按钮,程序会启动一个线程,每隔5秒钟随机生成一个汉字,并在界面上显示出来。用户需要在输入框中输入相应的汉字,如果输入正确,程序会自动更新得分。点击“结束游戏”按钮可以结束游戏并计算最终得分。