游戏概述e-energy.cn
玩家需要猜测一个由程序随机生成的1到100之间的数字。每次猜测后,程序会告诉玩家他们的猜测是太高、太低还是正确。
Python 实现
python
import random
def guess_number_game():
number_to_guess = random.randint(1, 100)
guess = None
attempts = 0
print("欢迎来到猜数字游戏!")
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}。")
print(f"你总共尝试了{attempts}次。")
except ValueError:
print("请输入一个有效的数字。")
guess_number_game()
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;
int guess = 0;
int attempts = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎来到猜数字游戏!");
System.out.println("我已经想好了一个1到100之间的数字。");
while (guess != numberToGuess) {
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.println("恭喜你!猜对了!数字是" + numberToGuess);
System.out.println("你总共尝试了" + attempts + "次。");
}
} else {
System.out.println("请输入一个有效的数字。");
scanner.next(); // 清除无效输入
}
}
scanner.close();
}
}
C# 实现
csharp
using System;
class Program
{
static void Main()
{
Random rand = new Random();
int numberToGuess = rand.Next(1, 101);
int guess = 0;
int attempts = 0;
Console.WriteLine("欢迎来到猜数字游戏!");
Console.WriteLine("我已经想好了一个1到100之间的数字。");
while (guess != numberToGuess)
{
Console.Write("请输入你的猜测:");
if (int.TryParse(Console.ReadLine(), out guess))
{
attempts++;
if (guess < numberToGuess)
{
Console.WriteLine("太低了!");
}
else if (guess > numberToGuess)
{
Console.WriteLine("太高了!");
}
else
{
Console.WriteLine($"恭喜你!猜对了!数字是{numberToGuess}");
Console.WriteLine($"你总共尝试了{attempts}次。");
}
}
else
{
Console.WriteLine("请输入一个有效的数字。");
}
}
}
}
以上代码展示了如何在三种不同的编程语言中实现一个简单的猜数字游戏。每种语言都有其独特的语法和库,但逻辑是相似的。