c#控制台应用程序游戏问题

时间:2018-03-13 18:49:29

标签: c# console-application

我有一个简单的游戏。你在和PC比赛。当你开始游戏时,你将有随机数(例如10)。您只需说“是”即可获得随机数字(卡片),您需要拥有21或接近21号才能赢得比赛。您也可以输掉PC,因为当您键入“是”时,计算机也会得到他的随机数。你通过简单的发短信“no”来结束游戏,你将得到你的结果,那就是游戏的结束。但是如果你反复输入“是”,那么你的数字会超过21而且游戏无法对此做出回应。所以我希望我的游戏能够写出“你已经越过了数字限制。你输了!”如果> 21但我不知道该怎么做。有人能帮我吗 ?  附:对不起我的英语,我希望你能理解我的问题:D

static void Main(string[] args)
{
    Random randomNumbers = new Random();
    int cardPlayer = randomNumbers.Next(0, 11);
    int cardPC = randomNumbers.Next(0, 11);

    NextCard:
    Console.WriteLine("Do you want another card ? yes/no You have now " + cardPlayer);
    String choice = Console.ReadLine();

    if (choice == "yes") {
        cardPlayer += randomNumbers.Next(0, 11);
        if (cardPC < 15) {
            cardPC += randomNumbers.Next(0, 11);
        }
        goto NextCard;
    } else if (choice == "no") {
        if (cardPlayer <= 21 && (cardPC > 21 || cardPC < cardPlayer)) {
            Console.WriteLine("WIN ! Computer have " + cardPC + " cards!");
        } else if (cardPlayer <= 21 && (cardPC > 21 || cardPC > cardPlayer)) {
            Console.WriteLine("LOSE ! Computer have " + cardPC + " cards!");
        } else if (cardPC > 21 && cardPlayer > 21) {
            Console.WriteLine("Both players lose ! Computer have " + cardPC + " cards! ");
        } else if (cardPC == cardPlayer) {
            Console.WriteLine("DRAW!");
        }
        Console.ReadKey();
    } else {
        Console.WriteLine("Type only yes/no!");
        goto NextCard;
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用goto循环解决问题,而不是使用do-while

        Random randomNumbers = new Random();
        int cardPlayer = randomNumbers.Next(0, 11);
        int cardPC = randomNumbers.Next(0, 11);
        String choice;
        do
        {
            Console.WriteLine("Do you want another card ? yes/no You have now " + cardPlayer);
            choice = Console.ReadLine();

            cardPlayer += randomNumbers.Next(0, 11);

            if (cardPC < 15)
            {
                cardPC += randomNumbers.Next(0, 11);
            }
        } while (choice == "yes" && cardPlayer < 21);

我们通过在绘制新卡之前测试cardPlayer变量是否小于21来解决您的问题。