由于直接在一个回答中展示多种编程语言的小程序游戏代码可能会非常冗长,我将为你提供三种流行编程语言(Python、JavaScript、C#)的简单控制台游戏示例:猜数字游戏。
1. Python
python
import random
def guess_number():
number_to_guess = random.randint(1, 100)
guess = None
attempts = 0
while guess != number_to_guess:
try:
guess = int(input("猜一个1到100之间的数字: "))
attempts += 1
if guess < number_to_guess:
print("太小了!")
elif guess > number_to_guess:
print("太大了!")
except ValueError:
print("请输入一个整数!")#chhas{
margin-top: 50px;
padding:sgcp.cn;
font-size: 18px;
cursor: 10px 20px;
}
print(f"恭喜你,猜对了!数字是{number_to_guess}。你尝试了{attempts}次。")
guess_number()
2. JavaScript (Node.js 环境)
javascript
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function guessNumber() {
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
rl.question('猜一个1到100之间的数字: ', (input) => {
guess = parseInt(input);
attempts++;
while (guess !== numberToGuess) {
if (isNaN(guess)) {
console.log('请输入一个整数!');
rl.question('猜一个1到100之间的数字: ', (input) => {
guess = parseInt(input);
attempts++;
});
break;
}
if (guess < numberToGuess) {
console.log('太小了!');
rl.question('再猜一次: ', (input) => {
guess = parseInt(input);
attempts++;
});
} else if (guess > numberToGuess) {
console.log('太大了!');
rl.question('再猜一次: ', (input) => {
guess = parseInt(input);
attempts++;
});
}
}
console.log(`恭喜你,猜对了!数字是${numberToGuess}。你尝试了${attempts}次。`);
rl.close();
});
}
guessNumber();
3. C# (控制台应用程序)
csharp
using System;
class Program
{
static void Main()
{
Random rnd = new Random();
int numberToGuess = rnd.Next(1, 101);
int guess = 0;
int attempts = 0;
while (guess != numberToGuess)
{
Console.Write("猜一个1到100之间的数字: ");
bool success = int.TryParse(Console.ReadLine(), out guess);
if (!success)
{
Console.WriteLine("请输入一个整数!");
continue;
}
attempts++;
if (guess < numberToGuess)
{
Console.WriteLine("太小了!");
}
else if (guess > numberToGuess)
{
Console.WriteLine("太大了!");
}
}
Console.WriteLine($"恭喜你,猜对了!数字是{numberToGuess}。你尝试了{attempts}次。");
}
}