C# 使用控制台写了一个猜数字的小游戏
心血来潮想到一个以前玩的猜数字的小游戏, 就用控制台把这个游戏实现了一下, 游戏规则如下:
系统随机生成一个1-100(不包含100)的数字, 由你来猜, 如果猜错, 就提示你猜的结果是大了还是小了, 然后在剩下的范围内从新猜, 直到猜对数字为止, 大家可以试一下多少次可以猜对, 代码我直接放在下面了
创建一个控制台程序, 将下面代码复制到main函数里面, 编译之后可以直接运行
Console.WriteLine("**********让我们来玩一个猜数字的小游戏**********");
Console.WriteLine("游戏规则: 系统随机设定一个1-100以内(不包括100)的数字,由你来猜");
Console.WriteLine("如果猜错,会提示你猜测的结果是大了还是小了");
Console.WriteLine("范围外的数字不能再猜,直到你猜到正确结果为止.");
Console.WriteLine("好了,让我们开始游戏吧!\r\n");
Thread.Sleep(1000);
Lp1:
Console.WriteLine("由系统设置一个随机数字");
int value = new Random().Next(1, 100);
Console.WriteLine("系统设置随机数字成功, 请输入你猜的数字:");
int minValue = 0;
int maxValue = 99;
int count = 0;
Lp2:
string readValue = Console.ReadLine();
if (!int.TryParse(readValue, out int newValue))
{
Console.WriteLine("输入数字错误,请重新输入");
count++;
goto Lp2;
}
if (newValue < minValue || newValue > maxValue)
{
Console.WriteLine("范围外数字不能输入,请重新输入");
count++;
goto Lp2;
}
count++;
if (value == newValue)
{
Console.WriteLine("恭喜你猜对了, 正确的数字是: " + value);
Console.WriteLine("你一共猜了 {0} 次\r\n", count);
goto Lp1;
}
else if (value < newValue)
{
Console.WriteLine("对不起你猜错了, 设定值小于你猜的数字, 范围({0}, {1})", minValue, newValue);
maxValue = newValue;
goto Lp2;
}
else if (value > newValue)
{
Console.WriteLine("对不起你猜错了, 设定值大于你猜的数字, 范围({0}, {1})", newValue, maxValue);
minValue = newValue;
goto Lp2;
}
大家也可以添加一个值来记录自己最少用了多少次猜到正确数字的, 最后祝大家玩得开心!