想要一个循环来检查是否按下了键

时间:2015-08-11 16:11:01

标签: c#

我做了这个游戏,我想制作一个循环,不断检查是否按下了一个键,但是当我进行循环时,它会自动输入角色,而不是按下你按下按钮的数量。没有循环,你只能输入一次,所以如何创建一个循环,只检查按钮是否被按下然后释放。

{

        Console.WriteLine("Enter your name, please: ");

        string name = Console.ReadLine();

        Console.WriteLine("Nice to met you, " + name);

        Console.WriteLine("Press F to feed yourself(+10) and D to drink some water(+10)");

        int hunger = 60;
        int thirst = 60;

        ConsoleKeyInfo info = Console.ReadKey();
        //here is where I want it too loop but I dont want it too automatically feed every half seconds, how do I do this?
        {
            if (info.Key == ConsoleKey.F)
            {
                System.Threading.Thread.Sleep(500);
                {
                    hunger = hunger + 10;
                    Console.WriteLine("Food: {0:0.0}".PadRight(15), hunger);

                    Console.WriteLine("Water: {0:0.0}".PadRight(70), thirst);
                }
            }
            if (info.Key == ConsoleKey.D)
            {
                System.Threading.Thread.Sleep(500);
                {
                    thirst = thirst + 10;
                    Console.WriteLine("Food: {0:0.0}".PadRight(15), hunger);

                    Console.WriteLine("Water: {0:0.0}".PadRight(70), thirst);
                }
            }

        }
        while (hunger > 1 && hunger < 101 && thirst > 1 && thirst < 101)
        {
            System.Threading.Thread.Sleep(5000);
            Console.Write(" ");
            {
                hunger = hunger - 2;
                thirst = thirst - 4;
                Console.Write("Food: {0:0.0}".PadRight(15), hunger);

                Console.Write("Water: {0:0.0}".PadRight(70), thirst);

            }

1 个答案:

答案 0 :(得分:1)

您只获得Console.ReadKey()一次的值,因此一旦按下f或d,循环将继续为它们提供。尝试这样的事情:

do
{
    ConsoleKeyInfo info = Console.ReadKey();

        if (info.Key == ConsoleKey.F)
        {
            System.Threading.Thread.Sleep(500);
            {
                hunger = hunger + 10;
                Console.WriteLine("Food: {0:0.0}".PadRight(15), hunger);

                Console.WriteLine("Water: {0:0.0}".PadRight(70), thirst);
            }
        }
        if (info.Key == ConsoleKey.D)
        {
            System.Threading.Thread.Sleep(500);
            {
                thirst = thirst + 10;
                Console.WriteLine("Food: {0:0.0}".PadRight(15), hunger);

                Console.WriteLine("Water: {0:0.0}".PadRight(70), thirst);
            }
        }
}
while(info.Key != ConsoleKey.Escape);

这将循环,不断检查按键直到用户逃脱(你可以取消任何你喜欢的取消条件,例如,满足一些阈值的饥饿或口渴)