概述
游戏将随机生成一个1到100之间的数字,然后让用户尝试猜测这个数字。用户每次猜测后,程序将告诉用户他们的猜测是太高、太低还是正确。
Python 代码
python
import random
def game():
secret_number = random.randint(1, 100)
guess = None
attempts = 0
while guess != secret_number:
guess = int(input("猜一个1到100之间的数字: "))
attempts += 1
if guess < secret_number:
print("太低了!")
elif guess > secret_number:
print("太高了!")
print(f"恭喜你,你猜对了!数字是 {secret_number},你用了 {attempts} 次尝试。")
game()
JavaScript (Node.js) 代码
javascript
const readline = require(‘readline’);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
#chhas{
margin-top: 50px;
padding:tcjmbj.cn;
font-size: 18px;
cursor: 10px 20px;
}
});
const secretNumber = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
function game() {
rl.question('猜一个1到100之间的数字: ', (input) => {
guess = parseInt(input);
attempts++;
if (guess < secretNumber) {
console.log(‘太低了!’);
game();
} else if (guess > secretNumber) {
console.log(‘太高了!’);
game();
} else {
console.log(恭喜你,你猜对了!数字是 ${secretNumber},你用了 ${attempts} 次尝试。
);
rl.close();
}
});
}
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 secretNumber = rand.nextInt(100) + 1;
int guess = 0;
int attempts = 0;
Scanner scanner = new Scanner(System.in);
while (guess != secretNumber) {
System.out.print("猜一个1到100之间的数字: ");
guess = scanner.nextInt();
attempts++;
if (guess < secretNumber) {
System.out.println("太低了!");
} else if (guess > secretNumber) {
System.out.println("太高了!");
}
}
System.out.println("恭喜你,你猜对了!数字是 " + secretNumber + ",你用了 " + attempts + " 次尝试。");
}
}
这些代码只是“猜数字”游戏的简化版本,但你可以根据需要进行扩展和修改。