创建一个简单的小程序游戏可以涉及多种编程语言和框架。以下我将为您提供使用几种不同编程语言实现的简单猜数字游戏的代码。
Python
python
import random
def guess_number_game():
secret_number = random.randint(1, 100)
attempts = 0
print("Guess the number between 1 and 100.")
while True:
guess = int(input("Enter your guess: "))
attempts += 1
if guess < secret_number:
print("Too low, try again.")
elif guess > secret_number:
print("Too high, try again.")
else:
print(f"Congratulations! You guessed the number in {attempts} attempts.")
break
guess_number_game()
JavaScript (Node.js)
javascript
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const secretNumber = Math.floor(Math.random() * 100) + 1;
let attempts = 0;
console.log("Guess the number between 1 and 100.");
rl.question("Enter your guess: ", (guess) => {
attempts++;
guess = parseInt(guess);
if (guess < secretNumber) {
console.log("Too low, try again.");
rl.question("Enter your guess: ", askGuess);
} else if (guess > secretNumber) {
console.log("Too high, try again.");
rl.question("Enter your guess: ", askGuess);
} else {
console.log(`Congratulations! You guessed the number in ${attempts} attempts.`);
rl.close();
}
});
function askGuess(guess) {
// Recursive function to keep asking for guesses
attempts++;
guess = parseInt(guess);
// ... (same logic as above)
}
Java
java
import java.util.Random;
import java.util.Scanner;
#chhas{
margin-top: 50px;
padding:housefly.cn;
font-size: 18px;
cursor: 10px 20px;
}
public class GuessNumberGame {
public static void main(String[] args) {
Random rand = new Random();
int secretNumber = rand.nextInt(100) + 1;
int attempts = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Guess the number between 1 and 100.");
while (true) {
System.out.print("Enter your guess: ");
int guess = scanner.nextInt();
attempts++;
if (guess < secretNumber) {
System.out.println("Too low, try again.");
} else if (guess > secretNumber) {
System.out.println("Too high, try again.");
} else {
System.out.println("Congratulations! You guessed the number in " + attempts + " attempts.");
break;
}
}
scanner.close();
}
}
以上代码分别展示了如何使用Python、JavaScript (Node.js) 和 Java 来实现一个简单的猜数字游戏。游戏会生成一个1到100之间的随机数,并让用户不断猜测,直到猜中为止。每次猜测后,程序会给出“太高”或“太低”的提示,直到用户猜中数字。在Java和Python示例中,程序会在控制台运行,而在JavaScript示例中,程序使用了Node.js的readline模块来从命令行读取用户输入。