如何解决如何为自己制作的游戏添加计数系统
我是一个初学者,我在C#控制台中编码。我做了这个猜谜游戏,您必须猜一个1到10的随机数。我做了这个,所以您可以玩无限次。该游戏可以按计划完美运行,但我想在此游戏中提供更多功能,这是一个计数系统。我希望我的代码能计算出玩家为获得正确猜测所进行的尝试。我已经尝试了几种方法,但是没有用。
using System;
namespace The_Test_Program
{
class Program
{
static void Main(string[] args)
{
// Appearance
Console.Title = "Test";
// Working Code
Console.WriteLine("I will generate a random number and you have to guess it.");
Random random = new Random();
int randomNum = random.Next(1,11);
Console.WriteLine("I have generated a random number from 1 to 10.");
Console.Write("What do you think write the answer : ");
int GenNum = int.Parse(Console.ReadLine());
Char yN;
while (GenNum!=randomNum)
{
Console.Clear();
Console.WriteLine("\nWrong");
Console.Write("Wanna try again [Y/N]: ");
yN = Char.Parse(Console.ReadLine());
if (yN =='Y')
{
randomNum = random.Next(1,11);
Console.WriteLine("I have generated a new random number.");
Console.Write("Try again : ");
GenNum = int.Parse(Console.ReadLine());
}
else
{
Console.WriteLine("No problem");
Console.WriteLine("\nPress any key to exit .....");
Console.ReadKey();
Environment.Exit(0);
}
}
Console.WriteLine("Correct");
}
}
}
解决方法
首先欢迎堆栈溢出,希望您喜欢它:)
我建议您进行一些更改,您可以在检查时更改以下内容:
while (GenNum!=randomNum && yN != 'N')
这将允许您稍后提取if逻辑,并在这两个语句正确时循环。
如果要计算循环播放的次数(计算播放器播放的次数),可以在开头添加int counter
,然后在while循环中添加counter++
。 ++与counter = counter + 1
相同,但是花哨的方式更多。
下面的代码具有这些要点,您可能还需要更改一些其他内容,但这是您要理解的地方!
using System;
namespace The_Test_Program
{
class Program
{
static void Main()
{
// Appearance
Console.Title = "Test";
// Working Code
Console.WriteLine("I will generate a random number and you have to guess it.");
Random random = new Random();
int randomNum = random.Next(1,11);
Console.WriteLine("I have generated a random number from 1 to 10.");
Console.Write("What do you think write the answer : ");
int GenNum = int.Parse(Console.ReadLine());
Char yN = 'Y';
int counter = 0;
while (GenNum!=randomNum && yN != 'N')
{
Console.Clear();
Console.WriteLine("\nWrong");
Console.Write("Wanna try again [Y/N]: ");
yN = Char.Parse(Console.ReadLine());
counter++;
if (GenNum == randomNum)
{
Console.WriteLine($"Correct,you tried {counter} times.");
}
}
Console.WriteLine("No problem");
Console.WriteLine("\nPress any key to exit .....");
Console.ReadKey();
Environment.Exit(0);
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。