当然可以!以下是一个简单的猜数字游戏的代码,我将为你提供Python、JavaScript(Node.js)和Java的版本。
Python 版本:
python
import random
def guess_number_game():
number = random.randint(1, 100)
attempts = 0
print("欢迎来到猜数字游戏!数字范围是1到100。")
while True:
user_guess = int(input("请输入你的猜测:"))
attempts += 1
if user_guess == number:
print(f"恭喜你!你在{attempts}次尝试后猜对了!")
break
elif user_guess < number:
print("太小了!再试一次。")
else:
print("太大了!再试一次。")
if __name__ == "__main__":
guess_number_game()
JavaScript (Node.js) 版本:
javascript
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let number = Math.floor(Math.random() * 100) + 1;#chhas{
margin-top: 50px;
padding:21cnnet.cn;
font-size: 18px;
cursor: 10px 20px;
}
let attempts = 0;
console.log("欢迎来到猜数字游戏!数字范围是1到100。");
rl.question("请输入你的猜测:", (answer) => {
let user_guess = parseInt(answer);
attempts++;
if (user_guess === number) {
console.log(`恭喜你!你在${attempts}次尝试后猜对了!`);
rl.close();
} else if (user_guess < number) {
console.log("太小了!再试一次。");
rl.question("请输入你的猜测:", guessNumber);
} else {
console.log("太大了!再试一次。");
rl.question("请输入你的猜测:", guessNumber);
}
});
const guessNumber = (answer) => {
let user_guess = parseInt(answer);
attempts++;
if (user_guess === number) {
console.log(`恭喜你!你在${attempts}次尝试后猜对了!`);
rl.close();
} else if (user_guess < number) {
console.log("太小了!再试一次。");
rl.question("请输入你的猜测:", guessNumber);
} else {
console.log("太大了!再试一次。");
rl.question("请输入你的猜测:", guessNumber);
}
};
Java 版本:
java
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
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);
System.out.println("欢迎来到猜数字游戏!数字范围是1到100。");
while (true) {
System.out.print("请输入你的猜测:");
int userGuess = scanner.nextInt();
attempts++;
if (userGuess == number) {
System.out.println("恭喜你!你在" + attempts + "次尝试后猜对了!");
break;
} else if (userGuess < number) {
System.out.println("太小了!再试一次。");
} else {
System.out.println("太大了!再试一次。");
}
}
scanner.close();
}
}