java猜数游戏图形界面_猜数游戏java实现代码
时间: 2023-11-13 16:12:11 浏览: 96
一个简单的依靠java驱动的带有gui界面的猜数小游戏.zip
以下是一个简单的Java猜数游戏的图形界面实现代码,您可以参考一下:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GuessNumberGame extends JFrame implements ActionListener {
private JTextField textField;
private JTextArea textArea;
private int randomNum;
private int guessCount;
public GuessNumberGame() {
super("Guess Number Game");
randomNum = (int) (Math.random() * 100) + 1; // 生成随机数
guessCount = 0;
// 设置布局
setLayout(new BorderLayout());
// 添加文本框
JPanel topPanel = new JPanel(new FlowLayout());
topPanel.add(new JLabel("Please guess a number between 1 and 100: "));
textField = new JTextField(10);
topPanel.add(textField);
add(topPanel, BorderLayout.NORTH);
// 添加文本区域
textArea = new JTextArea(10, 30);
textArea.setEditable(false);
add(new JScrollPane(textArea), BorderLayout.CENTER);
// 添加按钮
JPanel buttonPanel = new JPanel(new FlowLayout());
JButton guessButton = new JButton("Guess");
guessButton.addActionListener(this);
buttonPanel.add(guessButton);
JButton resetButton = new JButton("Reset");
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
add(buttonPanel, BorderLayout.SOUTH);
// 设置窗口属性
setSize(400, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("Guess")) { // 点击“Guess”按钮
int guessNum = Integer.parseInt(textField.getText());
if (guessNum < 1 || guessNum > 100) {
JOptionPane.showMessageDialog(this, "Please enter a number between 1 and 100!");
} else {
guessCount++;
if (guessNum == randomNum) { // 猜对了
textArea.append("Congratulations! You guessed the number " + randomNum + " in " + guessCount + " guesses!\n");
textField.setEnabled(false);
} else if (guessNum < randomNum) { // 猜小了
textArea.append("Your guess " + guessNum + " is too low. Please try again.\n");
} else { // 猜大了
textArea.append("Your guess " + guessNum + " is too high. Please try again.\n");
}
textField.setText("");
textField.requestFocus();
}
} else { // 点击“Reset”按钮
randomNum = (int) (Math.random() * 100) + 1; // 重新生成随机数
guessCount = 0;
textArea.setText("");
textField.setEnabled(true);
textField.setText("");
textField.requestFocus();
}
}
public static void main(String[] args) {
new GuessNumberGame();
}
}
```
阅读全文