我怎样才能告诉我的程序在完成之后“重新执行”不同的操作(由用户输入选择),直到设置了执行要求为止?

时间:2015-06-04 14:44:12

标签: c# input console readline

我只是C#的初学者,我正在研究控制台应用程序,我希望程序能够读取用户的输入并执行订单,直到他有0 HP。它基本上就是“战斗游戏”。

我的问题现在,我只能要求用户输入一次(它只会执行程序曾经获得的输入)。我想添加额外的战斗选项,但是现在我已经被困在这里了。

static void Main(string[] args)
    {
        int playerHealth = 100;
        int playerDamageSword = 10;
        int playerDamageFire = 10;
        int playerHeal = 20;

        int enemyHealth = 100;


        Console.WriteLine("Hey! Enter your Character Name!");
        string name = Console.ReadLine();
        Console.Clear();

        Console.WriteLine("Okay! " + name + " You have encountered an Enemy! Which Action do you choose?\n1.Sword-Attack\n2.Fire-Attack\n3.Heal\n8.Flee\n9.Quit\n" );
        string Input = Console.ReadLine();

        do
        {
            if (Input == "1")
            {
                Console.WriteLine("You hit your Opponment for 10 Damage!");
                enemyHealth = enemyHealth - 10;
                Console.WriteLine("Your Opponment hit you back for 10 Damage!");
                playerHealth = playerHealth - 10;
                Console.WriteLine("Your Current Hp: " + playerHealth);
                Console.WriteLine("Opponment Current HP: " + enemyHealth);

            }

            else if (Input == "2")
            {
                Console.WriteLine("You healed yourself for 20 HP");
                playerHealth = playerHealth + 20;
                Console.WriteLine("Your Current Hp: " + playerHealth);
                Console.WriteLine("Opponment Current HP: " + enemyHealth);


            }
        } while (playerHealth > 0);

1 个答案:

答案 0 :(得分:1)

你非常接近,你需要将输入读取移动到你的循环中,如下所示:

    string Input;

    do
    {
        Input = Console.ReadLine();

        if (Input == "1")
        {
            Console.WriteLine("You hit your Opponment for 10 Damage!");
            enemyHealth = enemyHealth - 10;
            Console.WriteLine("Your Opponment hit you back for 10 Damage!");
            playerHealth = playerHealth - 10;
            Console.WriteLine("Your Current Hp: " + playerHealth);
            Console.WriteLine("Opponment Current HP: " + enemyHealth);

        }

        else if (Input == "2")
        {
            Console.WriteLine("You healed yourself for 20 HP");
            playerHealth = playerHealth + 20;
            Console.WriteLine("Your Current Hp: " + playerHealth);
            Console.WriteLine("Opponment Current HP: " + enemyHealth);


        }
    } while (playerHealth > 0);

这将做什么:

  1. 开始循环
  2. 获取用户输入并将其存储到Input字符串
  3. 检查if (Input == "1")else if (Input == "2")条件
  4. 检查(playerHealth > 0),然后返回循环顶部 或退出循环