当然,我会继续为你提供“猜数字”游戏的代码,这次会涵盖更多编程语言。
Python (控制台应用程序)
python
import random
def guess_number_game():
number_to_guess = random.randint(1, 100)
guess = None
attempts = 0
while guess != number_to_guess:
try:
guess = int(input("猜一个1到100之间的数字:"))
attempts += 1
if guess < number_to_guess:
print("太低了!")
elif guess > number_to_guess:
print("太高了!")
except ValueError:
print("请输入一个整数!")
print(f"恭喜你,猜对了!数字是{number_to_guess},你一共猜了{attempts}次。")
if __name__ == "__main__":
guess_number_game()
JavaScript (Node.js 环境)
javascript
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});#chhas{
margin-top: 50px;
padding:xiergd.cn;
font-size: 18px;
cursor: 10px 20px;
}
const numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess;
let attempts = 0;
readline.question('猜一个1到100之间的数字:', (input) => {
guess = parseInt(input, 10);
attempts++;
while (isNaN(guess) || guess < 1 || guess > 100 || guess !== numberToGuess) {
readline.question('输入无效或未猜中,请重新输入一个1到100之间的数字:', (input) => {
guess = parseInt(input, 10);
if (isNaN(guess) || guess < 1 || guess > 100) {
console.log('请输入一个1到100之间的整数!');
} else if (guess < numberToGuess) {
console.log('太低了!');
} else if (guess > numberToGuess) {
console.log('太高了!');
}
if (guess === numberToGuess) {
console.log(`恭喜你,猜对了!数字是${numberToGuess},你一共猜了${attempts}次。`);
readline.close();
}
});
}
if (guess === numberToGuess) {
console.log(`恭喜你,猜对了!数字是${numberToGuess},你一共猜了${attempts}次。`);
readline.close();
}
});
Java (Swing GUI)
这个Java版本将使用Swing库来创建一个图形用户界面(GUI)。
java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GuessNumberGUI extends JFrame implements ActionListener {
private JTextField guessField;
private JButton checkButton;
private JLabel resultLabel;
private int numberToGuess;
private int attempts = 0;
public GuessNumberGUI() {
super("猜数字游戏");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setLayout(new FlowLayout());
numberToGuess = (int) (Math.random() * 100) + 1;
guessField = new JTextField(10);
checkButton = new JButton("提交");
resultLabel = new JLabel("猜一个1到100之间的数字:");
add(resultLabel);
add(guessField);
add(checkButton);
checkButton.addActionListener(this);
setLocationRelativeTo(null); // Center the window
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String input = guessField.getText();
int guess = 0;
try {
guess = Integer.parseInt(input);
} catch (NumberFormatException ex) {
resultLabel.setText("请输入一个整数!");
return;
}
attempts++;
if (guess < numberToGuess) {
resultLabel.setText("太低了!");
} else if (guess > numberToGuess) {
resultLabel.setText("太高了!");
} else {
resultLabel.setText("恭喜你,猜对了!数字是

被折叠的 条评论
为什么被折叠?



