由于篇幅限制,我将为您提供几种不同编程语言中非常简单的“猜数字”游戏的基本代码示例。
1. 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}次尝试。')
guess_number()
2. JavaScript (Node.js 或浏览器)
javascript
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
do {
guess = prompt('猜一个1到100之间的数字: ');
guess = parseInt(guess);
attempts++;
if (guess < numberToGuess) {
#chhas{
margin-top: 50px;
padding:fjspace.com.cn;
font-size: 18px;
cursor: 10px 20px;
}
alert('太小了!');
} else if (guess > numberToGuess) {
alert('太大了!');
}
} while (guess !== numberToGuess);
alert(`恭喜你,猜对了!你用了${attempts}次尝试。`);
3. 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);
do {
System.out.print("猜一个1到100之间的数字: ");
guess = scanner.nextInt();
attempts++;
if (guess < numberToGuess) {
System.out.println("太小了!");
} else if (guess > numberToGuess) {
System.out.println("太大了!");
}
} while (guess != numberToGuess);
System.out.println("恭喜你,猜对了!你用了" + attempts + "次尝试。");
}
}
这些代码示例都是非常简单的猜数字游戏,用户需要猜一个在1到100之间的随机数。每种语言都提供了获取用户输入、比较猜测值和随机数的功能,并在用户猜对时给出反馈。