Python 示例
python
import random
def game():
number_to_guess = random.randint(1, 100) yctsy.cn
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'恭喜你,猜对了!数字是 {number_to_guess},你用了 {attempts} 次尝试。')
if name == “main”:
game()
JavaScript 示例(在浏览器控制台或HTML文件中)
html
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.printf("恭喜你,猜对了!数字是 %d,你用了 %d 次尝试。\n", numberToGuess, attempts);
}
}
这三个示例都是简单的猜数字游戏,你可以根据自己的需要进行修改和扩展。由于涵盖多种电脑语言可能过于复杂,我将为你提供三种常见编程语言(Python、JavaScript 和 Java)的简单小游戏代码示例:猜数字游戏。
Python 示例
python
import random
def game():
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'恭喜你,猜对了!数字是 {number_to_guess},你用了 {attempts} 次尝试。')
if name == “main”:
game()
JavaScript 示例(在浏览器控制台或HTML文件中)
html
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.printf("恭喜你,猜对了!数字是 %d,你用了 %d 次尝试。\n", numberToGuess, attempts);
}
}
这三个示例都是简单的猜数字游戏,你可以根据自己的需要进行修改和扩展。