用Java设计一个拿火柴小游戏,要求:程序随机产生20~50根火柴,由人与计算机轮流拿,每次拿的数量为1~3根,以不拿到最后一根为胜。(要求使用图形界面)
时间: 2024-02-24 14:59:26 浏览: 18
好的,我可以为您提供一个Java Swing实现的拿火柴小游戏代码示例,您可以参考下面的代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MatchstickGame extends JFrame implements ActionListener {
private JLabel title, status;
private JTextField input;
private JButton submit;
private int matches, currentPlayer;
public MatchstickGame() {
super("拿火柴小游戏");
matches = (int) (Math.random() * 31) + 20; // 随机生成20~50根火柴
currentPlayer = 1; // 初始化为玩家1先手
setLayout(new GridLayout(3, 1));
title = new JLabel("剩余火柴数:" + matches, JLabel.CENTER);
add(title);
status = new JLabel("玩家" + currentPlayer + "请拿火柴", JLabel.CENTER);
add(status);
JPanel panel = new JPanel(new FlowLayout());
input = new JTextField(5);
panel.add(input);
submit = new JButton("确定");
submit.addActionListener(this);
panel.add(submit);
add(panel);
setSize(300, 150);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event) {
String inputText = input.getText();
int count = 0;
try {
count = Integer.parseInt(inputText);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "请输入数字");
return;
}
if (count < 1 || count > 3 || count > matches) {
JOptionPane.showMessageDialog(this, "请输入1~3之间的数字,且不能大于剩余火柴数");
return;
}
matches -= count;
title.setText("剩余火柴数:" + matches);
if (matches == 0) {
String winner = currentPlayer == 1 ? "计算机" : "玩家";
JOptionPane.showMessageDialog(this, winner + "获胜!");
int choice = JOptionPane.showConfirmDialog(this, "是否重新开始游戏?");
if (choice == JOptionPane.YES_OPTION) {
matches = (int) (Math.random() * 31) + 20;
currentPlayer = 1;
title.setText("剩余火柴数:" + matches);
status.setText("玩家" + currentPlayer + "请拿火柴");
input.setText("");
} else {
System.exit(0);
}
} else {
if (currentPlayer == 1) {
currentPlayer = 2;
status.setText("计算机正在思考...");
submit.setEnabled(false);
new Thread() {
public void run() {
try {
sleep(2000);
int count = (int) (Math.random() * 3) + 1;
while (count > matches) {
count = (int) (Math.random() * 3) + 1;
}
matches -= count;
title.setText("剩余火柴数:" + matches);
currentPlayer = 1;
status.setText("玩家" + currentPlayer + "请拿火柴");
submit.setEnabled(true);
input.setText("");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
} else {
currentPlayer = 1;
status.setText("玩家" + currentPlayer + "请拿火柴");
input.setText("");
}
}
}
public static void main(String[] args) {
new MatchstickGame();
}
}
```
这段代码实现了一个简单的拿火柴小游戏,可以随机生成20~50根火柴,由人与计算机轮流拿,每次拿的数量为1~3根,以不拿到最后一根为胜。
在界面中,有一个显示剩余火柴数的标签,一个显示当前玩家和操作提示的标签,以及一个用于输入拿火柴数量并提交的文本框和按钮。当玩家点击按钮后,程序会根据输入的数量更新剩余火柴数,并判断是否结束游戏或轮到计算机操作。若轮到计算机操作,则程序会在2秒后随机生成拿火柴数量并更新界面。
您可以参考这份代码进行学习和修改,以满足您的实际需求。