Python 示例:猜数字游戏dgynx.cn
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'恭喜你,你猜对了!你尝试了{attempts}次。')
if name == “main”:
guess_number()
JavaScript 示例:简单的网页点击计数器
这个示例不是一个真正的游戏,但它是一个简单的网页应用。
html
你点击了 0 次
点击我<script>
let counter = 0;
function incrementCounter() {
counter++;
document.getElementById('counter').textContent = counter;
}
</script>
C# 示例:控制台版本的“石头、剪刀、布”游戏 csharp using System;
class Program
{
static string[] choices = { “石头”, “剪刀”, “布” };
static void Main()
{
Random rnd = new Random();
string computerChoice = choices[rnd.Next(choices.Length)];
Console.WriteLine("石头、剪刀、布!请选择:");
string userChoice = Console.ReadLine();
while (!choices.Contains(userChoice))
{
Console.WriteLine("无效的选择,请重新输入:");
userChoice = Console.ReadLine();
}
Console.WriteLine($"电脑选择了:{computerChoice}");
if (userChoice == computerChoice)
{
Console.WriteLine("平局!");
}
else if ((userChoice == "石头" && computerChoice == "剪刀") ||
(userChoice == "剪刀" && computerChoice == "布") ||
(userChoice == "布" && computerChoice == "石头"))
{
Console.WriteLine("你赢了!");
}
else
{
Console.WriteLine("你输了!");
}
}
}
这些示例分别展示了如何使用不同的编程语言编写简单的程序。你可以根据这些示例进一步扩展和改进你的代码。由于各种编程语言的语法和用途差异很大,我会为你提供几个简单的游戏示例,分别用Python(一种常用的脚本语言)、JavaScript(常用于网页开发)和C#(常用于.NET和Unity游戏开发)编写。
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'恭喜你,你猜对了!你尝试了{attempts}次。')
if name == “main”:
guess_number()
JavaScript 示例:简单的网页点击计数器
这个示例不是一个真正的游戏,但它是一个简单的网页应用。
html
你点击了 0 次
点击我<script>
let counter = 0;
function incrementCounter() {
counter++;
document.getElementById('counter').textContent = counter;
}
</script>
C# 示例:控制台版本的“石头、剪刀、布”游戏 csharp using System;
class Program
{
static string[] choices = { “石头”, “剪刀”, “布” };
static void Main()
{
Random rnd = new Random();
string computerChoice = choices[rnd.Next(choices.Length)];
Console.WriteLine("石头、剪刀、布!请选择:");
string userChoice = Console.ReadLine();
while (!choices.Contains(userChoice))
{
Console.WriteLine("无效的选择,请重新输入:");
userChoice = Console.ReadLine();
}
Console.WriteLine($"电脑选择了:{computerChoice}");
if (userChoice == computerChoice)
{
Console.WriteLine("平局!");
}
else if ((userChoice == "石头" && computerChoice == "剪刀") ||
(userChoice == "剪刀" && computerChoice == "布") ||
(userChoice == "布" && computerChoice == "石头"))
{
Console.WriteLine("你赢了!");
}
else
{
Console.WriteLine("你输了!");
}
}
}
这些示例分别展示了如何使用不同的编程语言编写简单的程序。你可以根据这些示例进一步扩展和改进你的代码。