简体   繁体   中英

Console.ReadKey() looping by itself in while loop

I have a loop and inside it a switch case which is basicly an user interface which lets people choose yes and now to continue a game with the left and right arrows.

i also added a Console.Beep() to give some feedback to the user. for some reason once the game ends(the game uses the arrows(its snake)) the option yes and no keep switching and i hear beeping about 10 to 20 times and then it stops. Does anyone know the reason? this is the code :

while (true)
{
    Console.Clear();
    Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~\n\n~~~~~~~~You Lost!~~~~~~~~\n\n~~~~~~~~~~~~~~~~~~~~~~~~~\nYour score was: " + SnakeBody.Count);
    Console.WriteLine("\nDo you want to continue?\n\n      " + (Continue ? ">YES  /  No" : " Yes  / >NO"));
    switch (Console.ReadKey().Key)
    {
        case ConsoleKey.LeftArrow:
            if (!Continue)
            {
                Console.Beep(SoundFrequency, SoundLength);
                Continue = true;
            }
            continue;
        case ConsoleKey.RightArrow:
            if (Continue)
            {
                Console.Beep(SoundFrequency, SoundLength);
                Continue = false;
            }
            continue;
        case ConsoleKey.Enter:
            Console.Beep(SoundFrequency + 200, SoundLength);
            if (Continue)
                SnakeGame();
            break;
        default: continue;
    }
    break;
}

When you press and hold a key, it generates repeating keystrokes with a certain frequency and puts them into an input queue. It looks that when you play your game, you generate a lot of keystrokes this way, your application is unable to process them in time so even when you think you've completed playing, your application still has a lot (about 10 to 20 times as you write) of keys yet to process, that's the reason.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM