如何在c#中允许用户再次尝试或退出控制台程序

本文关键字:程序 控制台 退出 用户 许用户 | 更新日期: 2023-09-27 18:18:05

我创造了一款游戏,让玩家有5次机会玩游戏,之后我想问玩家他们是想再玩一次还是退出。我在Python中见过这样做,但我不懂Python。我的代码工作得很好,但是我想添加这两个额外的函数如何在c#中实现这些功能?作为参考,这是我的代码主类代码的样子。

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!");
           }
       }
   }

如何在c#中允许用户再次尝试或退出控制台程序

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

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.
    }
}

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

让我们把你的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-method可以是:

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

必须将一些局部变量作为静态字段移到类中。或者你也可以创建一个Game类的实例,但我认为现在已经走得太远了

有两种方法可以做到这一点:

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);

环境。退出是退出程序的首选方式,因为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类中创建GameResults类的静态实例。您的代码最终看起来像下面这样

class Program
{
    private static GameResults results = new GameResults();
    public static void Main(string[] args)
    {
        // Code
    }
    private static bool PlayGame()
    {
        // Code
    }
}

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