练习,猜拳游戏强化
public class GuessNumberGUI extends JFrame implements ActionListener {
// GUI 组件
private JTextField inputField; // 输入数字的文本框
private JTextArea outputField; // 显示结果的文本区域
private JButton guessButton; // 猜按钮
// 游戏参数
private int target, count; // 目标数字和猜测次数
// 构造函数
public GuessNumberGUI() {
super("猜数字游戏");
// 初始化 GUI 组件
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400, 300);
this.setLocationRelativeTo(null);
this.setLayout(new BorderLayout());
// 创建输入组件,并添加到顶部
JPanel inputPanel = new JPanel(new GridLayout(2, 1));
inputField = new JTextField();
guessButton = new JButton("猜");
guessButton.addActionListener(this);
inputPanel.add(inputField);
inputPanel.add(guessButton);
this.add(inputPanel, BorderLayout.NORTH);
// 创建文本区域,并添加到中间
outputField = new JTextArea();
outputField.setEditable(false);
outputField.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 16));
JScrollPane scrollPane = new JScrollPane(outputField);
this.add(scrollPane, BorderLayout.CENTER);
// 初始化游戏参数
target = new Random().nextInt(100) + 1; // 生成 1-100 之间的随机整数
count = 0;
output("系统已经想好了一个 1-100 之间的整数,你需要尽可能快地猜中它。");
// 显示 GUI 窗口
this.setVisible(true);
}
// 处理用户点击猜按钮的事件
@Override
public void actionPerformed(ActionEvent e) {
try {
int guess = Integer.parseInt(inputField.getText().trim()); // 获取用户猜测的数字
count++; // 猜测次数加一
if (guess > target) {
output("你猜的数字比目标数字大,请继续尝试。"); // 提示用户继续猜测
} else if (guess < target) {
output("你猜的数字比目标数字小,请继续尝试。"); // 提示用户继续猜测
} else {
output(String.format("恭喜你猜对了!目标数字就是 %d。\n你一共猜了 %d 次。", target, count)); // 提示用户猜对,并显示猜测次数
guessButton.setEnabled(false); // 禁用猜按钮
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "请输入一个整数。", "错误", JOptionPane.ERROR_MESSAGE); // 用户输入不是数字,弹出错误提示框
}
inputField.setText(""); // 清空输入框
inputField.requestFocus(); // 让输入框获得焦点
}
// 在文本区域中显示消息
private void output(String message) {
outputField.append(message + "\n");
}
// 主函数,启动程序
public static void main(String[] args) {
// 使用 SwingUtilities.invokeLater 创建 GUI 界面
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GuessNumberGUI();
}
});
}
}