写一个Java猜字小游戏,有窗口
时间: 2024-04-10 08:27:53 浏览: 94
当然可以!下面是一个简单的Java猜字小游戏,使用了窗口来进行交互:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class GuessNumberGame extends JFrame {
private int randomNumber;
private int guessCount;
private JTextField inputField;
private JTextArea outputArea;
public GuessNumberGame() {
setTitle("猜字游戏");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
inputField = new JTextField();
outputArea = new JTextArea();
outputArea.setEditable(false);
JButton guessButton = new JButton("猜");
guessButton.addActionListener(new GuessButtonListener());
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(inputField, BorderLayout.CENTER);
panel.add(guessButton, BorderLayout.EAST);
Container container = getContentPane();
container.add(panel, BorderLayout.NORTH);
container.add(new JScrollPane(outputArea), BorderLayout.CENTER);
randomNumber = generateRandomNumber();
guessCount = 0;
outputArea.append("猜一个1到100之间的数字\n");
setVisible(true);
}
private int generateRandomNumber() {
Random random = new Random();
return random.nextInt(100) + 1;
}
private class GuessButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
try {
int guess = Integer.parseInt(inputField.getText());
guessCount++;
if (guess < randomNumber) {
outputArea.append(guess + " 太小了\n");
} else if (guess > randomNumber) {
outputArea.append(guess + " 太大了\n");
} else {
outputArea.append("恭喜你,猜对了!你一共猜了 " + guessCount + " 次\n");
inputField.setEnabled(false);
((JButton) e.getSource()).setEnabled(false);
}
inputField.setText("");
inputField.requestFocus();
} catch (NumberFormatException ex) {
outputArea.append("请输入一个有效的数字\n");
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(GuessNumberGame::new);
}
}
```
这个游戏会生成一个1到100之间的随机数,你需要通过输入猜测的数字来猜出正确的答案。游戏会根据你的猜测给出提示,直到猜对为止。祝你好运!
阅读全文