Python 示例
python
import random
def game(): anjijc.cn
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}次。')
game()
JavaScript 示例(在浏览器控制台或Node.js环境中运行)
javascript
function game() {
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
while (guess !== numberToGuess) {
guess = parseInt(prompt('猜一个1到100之间的数字: '));
attempts++;
if (guess < numberToGuess) {
console.log('太低了!');
} else if (guess > numberToGuess) {
console.log('太高了!');
}
}
console.log(`恭喜你,你猜对了!你尝试了${attempts}次。`);
}
game();
Java 示例
java
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
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 + "次。");
}
}
这些示例都是基于一个简单的“猜数字”游戏,其中程序会随机选择一个数字,然后让用户尝试猜测这个数字。程序会给出提示(太高或太低),直到用户猜对为止。由于各种电脑语言(编程语言)的特性和语法差异很大,我将在下面分别为你提供三种流行的编程语言(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'恭喜你,你猜对了!你尝试了{attempts}次。')
game()
JavaScript 示例(在浏览器控制台或Node.js环境中运行)
javascript
function game() {
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
while (guess !== numberToGuess) {
guess = parseInt(prompt('猜一个1到100之间的数字: '));
attempts++;
if (guess < numberToGuess) {
console.log('太低了!');
} else if (guess > numberToGuess) {
console.log('太高了!');
}
}
console.log(`恭喜你,你猜对了!你尝试了${attempts}次。`);
}
game();
Java 示例
java
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
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 + "次。");
}
}
这些示例都是基于一个简单的“猜数字”游戏,其中程序会随机选择一个数字,然后让用户尝试猜测这个数字。程序会给出提示(太高或太低),直到用户猜对为止。