由于不同的编程语言有其特定的语法和用途,我将为你提供三种不同编程语言(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:
guess = int(input('猜一个1到100之间的数字: '))
attempts += 1
if guess < number_to_guess:
print('太小了!')
elif guess > number_to_guess:
print('太大了!')
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
});#chhas{
margin-top: 50px;
padding:rjcq.cn;
font-size: 18px;
cursor: 10px 20px;
}
function guessNumber() {
const numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
function askForGuess() {
rl.question('猜一个1到100之间的数字: ', (answer) => {
guess = parseInt(answer, 10);
attempts++;
if (guess < numberToGuess) {
console.log('太小了!');
} else if (guess > numberToGuess) {
console.log('太大了!');
} else {
console.log(`恭喜你,猜对了!数字是 ${numberToGuess},你用了 ${attempts} 次尝试。`);
rl.close();
}
if (guess !== numberToGuess) {
askForGuess();
}
});
}
askForGuess();
}
guessNumber();
3. C# (在.NET环境中运行,如控制台应用)
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之间的数字: ");
guess = Convert.ToInt32(Console.ReadLine());
attempts++;
if (guess < numberToGuess)
{
Console.WriteLine("太小了!");
}
else if (guess > numberToGuess)
{
Console.WriteLine("太大了!");
}
}
Console.WriteLine($"恭喜你,猜对了!数字是 {numberToGuess},你用了 {attempts} 次尝试。");
}
}
这些代码示例都创建了一个简单的猜数字游戏,用户需要猜测一个在1到100之间的随机整数。每个程序都会提示用户输入猜测,然后根据用户的猜测给出反馈,直到用户猜对为止。