由于篇幅限制,我无法为每种编程语言都提供一个完整的小游戏代码。但我可以为你提供几个简单的小游戏(如猜数字游戏)的示例代码,分别使用Python、JavaScript(通常在浏览器中运行)、Java(适用于桌面应用程序)和C#(用于.NET或Unity等)。
Python(猜数字游戏)
python
import random
def game():
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'恭喜你,你猜对了!你尝试了{attempts}次。')
game()#chhas{
margin-top: 50px;
padding:yanziliangpin.com;
font-size: 18px;
cursor: 10px 20px;
}
JavaScript(HTML中的猜数字游戏)
HTML部分:
html
<script src="game.js"></script>
JavaScript部分 (game.js):
javascript
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess;
let attempts = 0;
function checkGuess() {
guess = parseInt(document.getElementById(‘guess’).value);
attempts++;
if (guess === numberToGuess) {
document.getElementById('message').textContent = `恭喜你,你猜对了!你尝试了${attempts}次。`;
} else if (guess < numberToGuess) {
document.getElementById('message').textContent = '太小了!';
} else {
document.getElementById('message').textContent = '太大了!';
}
}
Java(Swing GUI中的猜数字游戏)
Java代码相对较长且复杂,但你可以使用Swing库来创建一个图形用户界面(GUI)。这里只提供一个大致的框架。
C#(控制台应用程序中的猜数字游戏)
C#代码与Python类似,但使用.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($"恭喜你,你猜对了!你尝试了{attempts}次。");
}
}