代码之家  ›  专栏  ›  技术社区  ›  Mustafa Arslan

使用While循环返回程序的起点

c#
  •  0
  • Mustafa Arslan  · 技术社区  · 7 年前

    首先,我为这个简单的问题感到抱歉,但我自己无法处理它,因为我刚刚开始编码。
    我编写了这个小游戏。我需要重新启动它,如果用户点击 y

    我的问题是,我知道如何恢复生命、米和点数,但我无法修复随机数(我们需要找到它才能获胜):它不会改变。


    static void Main(string[] args)
    {
        int QuestionNumber = (new Random()).Next(1, 10);
        int life = 5;
        int meter = 0;
        int number;
        int points = 100;
        char selection = 'y';
    
        while (selection == 'y')
        {
            life = 5;
            meter = 0;
            points = 100;
    
            while (life > 0)
            {
                meter++;
                Console.Write("Enter a number: ");
                number = Convert.ToInt32(Console.ReadLine());
    
                if (number == QuestionNumber)
                {
                    Console.WriteLine($"Congrats! You found the number at {meter}th and got {points} points!");
                    break;
                }
                life--;
                points = points - 20;
    
                if (life == 0)
                {
                    Console.WriteLine("Game over!");
                }
                else
                {
                    if (number > QuestionNumber)
                    {
                        Console.WriteLine("Down");
                    }
                    else
                    {
                        Console.WriteLine("Up");
                    }
                }
            }
            Console.Write("Do you want to countinue?(y/n)");
            selection = Convert.ToChar(Console.ReadLine());
        }
        Console.ReadKey();
    }
    
    2 回复  |  直到 7 年前
        1
  •  4
  •   gravity tata    7 年前

    while (selection == 'y')
    {
      life = 5;
      meter = 0;
    

    对此,请改为:

    while (selection == 'y')
    {
      QuestionNumber = (new Random()).Next(1, 10);
      life = 5;
      meter = 0;
    

    QuestionNumber 重新设置,就像从顶部开始实例化一样。

        2
  •  2
  •   Dave    7 年前

    这是因为在您的程序中,问题编号只分配了一次值。为了更改问题编号,您需要在while循环中为其分配一个新的随机值。