当然,以下我会用几种不同的编程语言来生成一个简单的“猜数字”游戏(Guess the Number)的代码。
Python 版本
python
import random
def guess_number():
number_to_guess = random.randint(1, 100)
guess = None
attempts = 0
while guess != number_to_guess:
guess = int(input("猜一个1到100之间的数字: "))
attempts += 1
if guess < number_to_guess:
print("太低了!")
elif guess > number_to_guess:
print("太高了!")
print(f"恭喜你,你猜对了!用了{attempts}次尝试。")
if name == “main”:
guess_number()
JavaScript 版本(HTML 页面中的脚本)
html
猜数字游戏
猜 Java 版本 java import java.util.Random; import java.util.Scanner;public class GuessNumberGame {
public static void main(String[] args) {
Random rand = new Random();
int numberToGuess = rand.nextInt(100) + 1;
Scanner scanner = new Scanner(System.in);
int guess = 0;
int attempts = 0;
while (guess != numberToGuess) {
System.out.print("猜一个1到100之间的数字: ");
guess = scanner.nextInt();
attempts++;
if (guess < numberToGuess) {
System.out.println("太低了!");
} else if (guess > numberToGuess) {
System.out.println("太高了!");
}
}
System.out.println("恭喜你,你猜对了!用了" + attempts + "次尝试。");
scanner.close();
}
}
以上代码分别用 Python、JavaScript(HTML 中嵌入)和 Java 实现了“猜数字”游戏。每个版本都允许用户输入一个猜测的数字,并根据用户的猜测给出提示,直到用户猜中为止。