由于直接在一个回答中提供多种编程语言的完整游戏代码可能过于冗长,我将分别为你提供几种常见编程语言(如Python, JavaScript, C#)的简单控制台游戏代码示例:一个猜数字游戏。
- Python 版本
python
import random
def game():
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('请输入一个整数!')
continue
print(f'恭喜你,猜对了!你用了{attempts}次尝试。')
if name == “main”:
game()
2. JavaScript 版本(Node.js 环境)
javascript
const readline = require(‘readline’);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
function game() {
rl.question('猜一个1到100之间的数字: ', (answer) => {
guess = parseInt(answer, 10);
attempts++;
if (isNaN(guess)) {
console.log('请输入一个整数!');
game();
return;
}
if (guess < numberToGuess) {
console.log('太小了!');
game();
} else if (guess > numberToGuess) {
console.log('太大了!');
game();
} else {
console.log(`恭喜你,猜对了!你用了${attempts}次尝试。`);
rl.close();
}
});
}
#chhas{
margin-top: 50px;
padding:etym.cn;
font-size: 18px;
cursor: 10px 20px;
}
game();
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;
do
{
Console.Write("猜一个1到100之间的数字: ");
if (!int.TryParse(Console.ReadLine(), out guess))
{
Console.WriteLine("请输入一个整数!");
continue;
}
attempts++;
if (guess < numberToGuess)
Console.WriteLine("太小了!");
else if (guess > numberToGuess)
Console.WriteLine("太大了!");
} while (guess != numberToGuess);
Console.WriteLine($"恭喜你,猜对了!你用了{attempts}次尝试。");
}
}
这些代码示例都是基于控制台输入的简单猜数字游戏。你可以根据自己的需要进行修改和扩展。