当然可以!我会为你提供Python、JavaScript(基于Node.js)和Java三种语言的简单猜数字游戏代码。
Python 版本:
python
import random
def game():
number = random.randint(1, 100)
attempts = 0
while True:
user_guess = int(input("请猜一个1到100之间的数字: "))
attempts += 1
if user_guess < number:
print("太小了!")
elif user_guess > number:
print("太大了!")
else:
print(f"恭喜你,你猜对了!你用了{attempts}次尝试。")
break
game()
JavaScript(Node.js)版本:
javascript
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
}); #chhas{
margin-top: 50px;
padding:pzswcc.cn;
font-size: 18px;
cursor: 10px 20px;
}
let number = Math.floor(Math.random() * 100) + 1;
let attempts = 0;
function askForGuess() {
rl.question('请猜一个1到100之间的数字: ', (answer) => {
attempts++;
let guess = parseInt(answer);
if (guess < number) {
console.log('太小了!');
askForGuess();
} else if (guess > number) {
console.log('太大了!');
askForGuess();
} else {
console.log(`恭喜你,你猜对了!你用了${attempts}次尝试。`);
rl.close();
}
});
}
askForGuess();
Java 版本:
java
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Random rand = new Random();
int number = rand.nextInt(100) + 1;
int attempts = 0;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("请猜一个1到100之间的数字:");
int guess = scanner.nextInt();
attempts++;
if (guess < number) {
System.out.println("太小了!");
} else if (guess > number) {
System.out.println("太大了!");
} else {
System.out.println("恭喜你,你猜对了!你用了" + attempts + "次尝试。");
break;
}
}
scanner.close();
}
}
以上三个版本都是简单的猜数字游戏,程序会随机生成一个1到100之间的数字,然后让用户来猜。根据用户的猜测,程序会给出提示,直到用户猜对为止。
747



被折叠的 条评论
为什么被折叠?



