创建一个简单的小程序游戏需要考虑游戏的复杂性以及不同编程语言的特性。下面,我将为您提供几个使用不同编程语言创建简单猜数字游戏的示例。
1. Python
python
import random
def guess_number_game():
secret_number = random.randint(1, 100)
attempts = 0
print("Welcome to the Guess Number Game!")
print("I'm thinking of a number between 1 and 100.")
while True:
try:
guess = int(input("Guess the number: "))
except ValueError:
print("Please enter a valid integer.")
continue
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()
2. 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("Welcome to the Guess Number Game!");
console.log("I'm thinking of a number between 1 and 100.");
rl.question("Guess the number: ", (guess) => {
attempts++;
guess = parseInt(guess, 10);
if (guess < secretNumber) {
console.log("Too low! Try again.");
rl.question("Guess the number: ", askGuess);
} else if (guess > secretNumber) {
console.log("Too high! Try again.");
rl.question("Guess the number: ", askGuess);
} else {
console.log(`Congratulations! You guessed the number in ${attempts} attempts.`);
rl.close();
}
});
function askGuess(guess) {
// Recursive function to keep asking for guesses
if (parseInt(guess, 10) !== secretNumber) {
rl.question("Guess the number: ", askGuess);
}
}
3. Java (Console Application)
java
import java.util.Random;
import java.util.Scanner;
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);
#chhas{
margin-top: 50px;
padding:imsale.com.cn;
font-size: 18px;
cursor: 10px 20px;
}
System.out.println("Welcome to the Guess Number Game!");
System.out.println("I'm thinking of a number between 1 and 100.");
while (true) {
System.out.print("Guess the number: ");
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之间的随机数,并让玩家尝试猜测这个数字。游戏会在玩家猜对数字后结束,并告诉玩家他们尝试了多少次才猜对。