【发布时间】:2021-10-16 23:58:14
【问题描述】:
我是 C# 编码新手,请帮我修复这个简单的骰子游戏,它在游戏结束时不断循环 ** 显然,我认为在这段代码的末尾,有些东西对循环和重新运行是不赞成的**
using System;
namespace first_game
{
class Program
{
static void Main(string[] args)
{
string userName;
userName = Console.ReadLine();
#region
{
int userPoint = 0;
int cpuPoint = 0;
int pDice;
bool closeApp;
while (true)
{
while (cpuPoint < 10 && userPoint < 10)
{
Random rd = new Random();
pDice = rd.Next(1, 6);
#endregion
int P2Dice;
Random scondRd = new Random();
P2Dice = scondRd.Next(1, 6);
Console.ReadLine();
Console.WriteLine("-------------------");
Console.Write("playe dice:");
Console.WriteLine(pDice);
Console.Write("CPU dice:");
Console.WriteLine(P2Dice);
Console.ReadLine();
if (pDice > P2Dice)
{
userPoint = userPoint + 1;
}
else if (pDice < P2Dice)
{
cpuPoint = cpuPoint + 1;
}
Console.Clear();
Console.WriteLine(userName);
Console.Write("player point:");
Console.WriteLine(userPoint);
Console.Write("CPU point:");
Console.Write(cpuPoint);
Console.ReadLine();
}
if (userPoint == 10)
{
Console.WriteLine("-----------------\nYOU WIN!!!");
Console.ReadLine();
}
else
{
Console.WriteLine("-----------------\nYOU lost!!! LOL");
Console.ReadLine();
}
Console.WriteLine("wanna continue?\n press Y for yes press N for NO");
ConsoleKeyInfo sw;
sw = Console.ReadKey();
Console.Clear();
if (sw.Key == ConsoleKey.Y)
{
userPoint = 0;
cpuPoint = 0;
continue;
}
else if (sw.Key == ConsoleKey.N)
{
}
else
Console.WriteLine("ERROR!");
}
}
}
}
}
【问题讨论】:
-
while (true) {...}是无限循环,它永远运行;要阻止它循环,您应该在某处break它:if (some_condition) break; -
Apple 的 以前的总部地址是“One Infinite Loop, Cupertino, CA”是有原因的。我们都至少写过一个(虽然通常不那么明显)。你有两个嵌套的
while循环,你需要确保你打破了他们两个 -
另一个(不相关的)评论。您在循环中创建
Random的实例。您只需要一个实例;在您输入程序时创建它并重复使用它。如果您快速连续创建两个实例,您最终可能会得到相同的数字序列。而且,为什么要在代码中声明#region,为什么它会以这种方式跨越作用域?