参考下面程序实现猜大小的游戏,有两个按钮,分别表示用户猜大还是猜小,代码内部随机产生一个0-9的数,如果产生的数0-4为小,5-9为大。显示用户是否猜对,并告诉用户正确的数字大小。。import java.awt.Color;
时间: 2024-02-15 09:05:04 浏览: 68
抱歉,我是一个自然语言处理AI,不具备编写代码的能力。但是,我可以为你提供一份Java代码,实现你所描述的猜大小游戏:
```
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class GuessNumberGame extends JFrame implements ActionListener {
private JLabel labelTitle;
private JLabel labelNumber;
private JButton buttonGuessSmall;
private JButton buttonGuessBig;
private Random random;
private int targetNumber;
public GuessNumberGame() {
super("Guess Number Game");
setLayout(new FlowLayout());
labelTitle = new JLabel("Guess Number Game");
labelTitle.setFont(new Font("Arial", Font.BOLD, 24));
labelTitle.setForeground(Color.BLUE);
add(labelTitle);
labelNumber = new JLabel("");
labelNumber.setFont(new Font("Arial", Font.PLAIN, 20));
add(labelNumber);
buttonGuessSmall = new JButton("Guess Small");
buttonGuessSmall.addActionListener(this);
add(buttonGuessSmall);
buttonGuessBig = new JButton("Guess Big");
buttonGuessBig.addActionListener(this);
add(buttonGuessBig);
setSize(400, 150);
setVisible(true);
random = new Random();
targetNumber = random.nextInt(10);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonGuessSmall) {
if (targetNumber >= 0 && targetNumber <= 4) {
JOptionPane.showMessageDialog(this, "Congratulations! You guessed right!");
} else {
JOptionPane.showMessageDialog(this, "Sorry, the answer is " + targetNumber + ". You guessed wrong.");
}
} else if (e.getSource() == buttonGuessBig) {
if (targetNumber >= 5 && targetNumber <= 9) {
JOptionPane.showMessageDialog(this, "Congratulations! You guessed right!");
} else {
JOptionPane.showMessageDialog(this, "Sorry, the answer is " + targetNumber + ". You guessed wrong.");
}
}
}
public static void main(String[] args) {
new GuessNumberGame();
}
}
```
这个程序使用Java Swing库实现了一个简单的GUI界面,包含了标题、显示结果的标签、两个按钮。当用户点击按钮时,程序会根据随机生成的数字判断用户的猜测是否正确,并给出相应的提示。
阅读全文