游戏描述:猜数字fengbaoshun.com
玩家需要猜测一个由程序随机生成的1到100之间的数字。每次猜测后,程序会告诉玩家猜测的数字是太高、太低还是正确。
示例代码
Python 示例
python
import random
def guess_the_number():
number_to_guess = random.randint(1, 100)
guess = None
attempts = 0
print(“我想了一个1到100之间的数字,你能猜到是哪个吗?”)
while guess != number_to_guess:
try:
guess = int(input("请输入你的猜测:"))
attempts += 1
if guess < number_to_guess:
print("太低了!")
elif guess > number_to_guess:
print("太高了!")
else:
print(f"恭喜你猜对了!数字就是{number_to_guess}。你尝试了{attempts}次。")
except ValueError:
print("请输入一个有效的数字。")
guess_the_number()
Java 示例
java
import java.util.Random;
import java.util.Scanner;
public class GuessTheNumber {
public static void main(String[] args) {
Random rand = new Random();
int numberToGuess = rand.nextInt(100) + 1;
Scanner scanner = new Scanner(System.in);
int guess;
int attempts = 0;
System.out.println("我想了一个1到100之间的数字,你能猜到是哪个吗?");
while (true) {
System.out.print("请输入你的猜测:");
if (scanner.hasNextInt()) {
guess = scanner.nextInt();
attempts++;
if (guess < numberToGuess) {
System.out.println("太低了!");
} else if (guess > numberToGuess) {
System.out.println("太高了!");
} else {
System.out.printf("恭喜你猜对了!数字就是%d。你尝试了%d次。\n", numberToGuess, attempts);
break;
}
} else {
System.out.println("请输入一个有效的数字。");
scanner.next(); // 清除无效输入
}
}
}
}
JavaScript 示例(Node.js 环境下)
javascript
const readline = require(‘readline’).createInterface({
input: process.stdin,
output: process.stdout
});
const numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess;
let attempts = 0;
console.log(“我想了一个1到100之间的数字,你能猜到是哪个吗?”);
readline.question(“请输入你的猜测:”, function(answer) {
while (true) {
guess = parseInt(answer, 10);
if (isNaN(guess)) {
console.log(“请输入一个有效的数字。”);
readline.question(“请输入你的猜测:”, function(newAnswer) {
answer = newAnswer;
continue;
});
return;
}
attempts++;
if (guess < numberToGuess) {
console.log("太低了!");
} else if (guess > numberToGuess) {
console.log("太高了!");
} else {
console.log(`恭喜你猜对了!数字就是${numberToGuess}。你尝试了${attempts}次。`);
readline.close();
break;
}
readline.question("请输入你的猜测:", function(newAnswer) {
answer = newAnswer;
});
}
});
请注意,JavaScript 示例在 Node.js 环境下运行,并使用了 readline 模块来处理命令行输入。每种语言都有其独特的语法和库,但基本的逻辑是相似的。