如何允许用户在 C# 中重试或退出控制台程序?

How to allow user to try again or quit console program in C#?

我创建了一个游戏,给玩家 5 次玩游戏的机会,之后我想问玩家是否愿意再次玩游戏或退出。我在 Python 看到过它,但我不知道 python。我的代码工作得很好,但我想添加这两个附加功能 如何在 C# 中实现这些功能? 作为参考,这是我的代码主要 class 代码的样子。

namespace NumBaseBall
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("\t\t\t*************************************");
            Console.WriteLine("\t\t\t*      Let's Have Some Fun          *");
            Console.WriteLine("\t\t\t*           Welcome To The          *");
            Console.WriteLine("\t\t\t*       Number Baseball Game        *");
            Console.WriteLine("\t\t\t*************************************\n");

            GameResults gameresults = new GameResults();

            for (int trysCounter = 1; trysCounter <= 5; trysCounter++)
            {
                gameresults.Strikes = 0; 

                Random r = new Random();
                var myRange = Enumerable.Range(1, 9);
                var computerNumbers = myRange.OrderBy(i => r.Next()).Take(3).ToList();
                Console.WriteLine("The Game's Three Random Integers Are: (Hidden from user)");
                 foreach (int integer in computerNumbers)
                 {
                     Console.WriteLine("{0}", integer);
                 }

                 List<int> playerNumbers = new List<int>();
                 Console.WriteLine("Please Enter Three Unique Single Digit Integers and Press ENTER after each:");
                 for (int i = 0; i < 3; i++)
                 {
                      Console.Write("");
                      int number = Convert.ToInt32(Console.ReadLine());
                                  playerNumbers.Add(number);
                 }

                 gameresults.StrikesOrBalls(computerNumbers,playerNumbers);
                 Console.WriteLine("---> Computer's Numbers = {0}{1}{2}", computerNumbers[0], computerNumbers[1], computerNumbers[2]);
                 Console.WriteLine("---> Player's Numbers = {0}{1}{2}", playerNumbers[0], playerNumbers[1], playerNumbers[2]);
                 Console.WriteLine("---> Game Results = {0} STRIKES & {1} BALLS\n", gameresults.Strikes, gameresults.Balls);
                 Console.WriteLine("You have played this games {0} times\n", trysCounter);

                  gameresults.TotalStrikes = gameresults.TotalStrikes + gameresults.Strikes;

                  Console.WriteLine("STRIKES = {0} ", gameresults.TotalStrikes);

                   if (gameresults.TotalStrikes >= 3)
                   {
                       gameresults.Wins++;
                       Console.WriteLine("YOU ARE A WINNER!!!");
                       break;
                   }
               }
                       if (gameresults.TotalStrikes <3)
                       Console.WriteLine("YOU LOSE :( PLEASE TRY AGAIN!");
           }
       }
   }

将您的代码插入一个循环中,该循环检查用户是否要继续:

while(true) // Continue the game untill the user does want to anymore...
{

    // Your original code or routine.

    while(true) // Continue asking until a correct answer is given.
    {
        Console.Write("Do you want to play again [Y/N]?");
        string answer = Console.ReadLine().ToUpper();
        if (answer == "Y")
             break; // Exit the inner while-loop and continue in the outer while loop.
        if (answer == "N")
             return; // Exit the Main-method.
    }
}

但也许将一个大例程拆分成单独的例程会更好。

让我们将您的主方法重命名为 PlayTheGame

将我的例程拆分为:

static public bool PlayAgain()
{
    while(true) // Continue asking until a correct answer is given.
    {
        Console.Write("Do you want to play again [Y/N]?");
        string answer = Console.ReadLine().ToUpper();
        if (answer == "Y")
             return true;
        if (answer == "N")
             return false;
    }
}

现在 Main 方法可以是:

static void Main(string[] args)
{
    do
    {
         PlayTheGame();
    }
    while(PlayAgain());
}

您必须将一些局部变量作为静态字段移动到 class。或者您可以创建一个游戏实例 class,但我认为这是目前的第一步。

您可以通过两种方式完成此操作:

https://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill%28v=vs.110%29.aspx

System.Diagnostics.Process.GetCurrentProcess().Kill();

或者

https://msdn.microsoft.com/en-us/library/system.environment.exit(v=vs.110).aspx

int exitCode =1;
System.Environment.Exit(exitCode);

Environment.Exit 是退出程序的首选方式,因为 Kill 命令“ 导致进程异常终止,应仅在必要时使用。”[msdn]

首先,采纳将实际玩游戏的代码移动到单独函数中的建议。它会清理很多东西。

类似

private static bool PlayGame()
{
    // Win branch returns true.
    // Loss branch returns false.
}

这样您就可以大大简化 Main 函数,使其仅处理菜单功能。

对于实际的菜单功能,我倾向于 do/while 循环。你有一个额外的规定,你只在5次播放后才询问,但这很容易处理。

static void Main(string[] args)
{
    int playCount = 0;
    string answer = "Y";
    bool winner;

    do
    {
        if(playCount < 5)
        {
            playCount++;
        }
        else
        {
            do
            {
                Console.Write("Play again? (Y/N): ");
                answer = Console.ReadLine().ToUpper();
            } while(answer != "Y" && answer != "N");
        }

        winner = PlayGame();
    } while(!winner && answer == "Y");

    Console.WriteLine("Thanks for playing!");
}

您可以通过使用递增运算符将 5 场比赛的测试移动到 if 条件中来稍微简化它。唯一的问题是,如果有人玩你的游戏十亿次左右,事情可能会变得很奇怪。

static void Main(string[] args)
{
    int playCount = 0;
    string answer = "Y";
    bool winner;

    do
    {


        if(playCount++ > 3)
        {
            do
            {
                Console.Write("Play again? (Y/N): ");
                answer = Console.ReadLine().ToUpper();
            } while(answer != "Y" && answer != "N");
        }

        winner = PlayGame();
    } while(!winner && answer == "Y");

    Console.WriteLine("Thanks for playing!");
}

编辑:在您的原始代码中做了一些改动,看起来游戏在玩家获胜后结束。


根据您在下方评论中提出的问题,您可以在 Program class 中创建 GameResults class 的静态实例。您的代码最终会如下所示

class Program
{
    private static GameResults results = new GameResults();

    public static void Main(string[] args)
    {
        // Code
    }

    private static bool PlayGame()
    {
        // Code
    }
}

PlayGame 中,您只需使用静态 results 对象,而不是在每次调用 PlayGame 时都创建一个新对象。