在 chromebook 上使用 .Net fiddle,尝试制作猜谜游戏。提示(更高或更低)不起作用,目标数字似乎发生了变化

using .Net fiddle on a chromebook, tried to make a guessing game. the hints (higher or lower) arent working and the target number seems to change

我正在尝试 运行 .Net fiddle 上的以下代码,但遇到了以下问题。随机生成的目标数字似乎会改变,提示(更高或更低)似乎会随着您的猜测而改变。为什么会这样?

我也确信代码可以使用一些优化,我是初学者并且在学校使用 chromebook 来练习。

using System;

public class Program
{
    public static void Main()
    {
        var random = new Random();
        int i = random.Next(0, 101);
        int tries = 5;
        Console.WriteLine("I'm thinking of a number between 1 and 100. Guess it in 5 tries.");
    Start:
        string feedback = Console.ReadLine();
        int guess = Convert.ToInt32(feedback);
        
        if (guess == i)
        {
            Console.WriteLine("You won with " + tries + " tries left!");
        }
        else if (guess > i && tries > 1)
        {
            tries--;
            Console.WriteLine("Try lower. " + tries + " tries left.");
            goto Start;
        }
        else if (guess < i && tries > 1)
        {
            tries--;
            Console.WriteLine("Try higher. " + tries + " tries left.");
            goto Start;
        }
        else
        {
            Console.WriteLine("Sorry, you ran out of tries. The nubmer was " + i + ".");
        }       
    }
}

.Net fiddle 不适合这个,因为您没有与应用程序的单个实例的连续会话

考虑它的工作方式如下:

  • fiddle 运行应用程序,包括所有输出,直到它需要您的输入
  • fiddle 终止应用程序并收集您的输入
  • fiddle 再次运行应用程序,提供您提供的输入,显示新的输出并再次终止它,要求您提供新的输入
  • fiddle 再次运行该应用程序,提供它看到您提供的两个输入,然后再次终止该应用程序...

它适用于对一组输入具有确定性行为的程序,但不适用于程序所做的一些重要事情是选择一个随机数。

要测试此代码,请不要使用随机数,只需使用常量即可。如果逻辑适用于随机生成的数字(并且生成逻辑是合理的)它也适用于常数

如果你真的想要一些猜测的元素,试试这个:

Console.WriteLine("Enter a word");
var word = Console.ReadLine();
var i = Math.Abs(word.GetHashCode())%101;

它会提示您输入一个单词并从中生成一个数字,但很难预测哪个单词会变成什么数字,因此它保留了猜测的元素。因为这个数字是从你的输入中派生出来的,所以它与这个“回收提供所有以前的输入”行为兼容

现在,关于那个 goto..