0

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;
}
Nino
  • 6,931
  • 2
  • 27
  • 42
SuperMinefudge
  • 301
  • 3
  • 11

1 Answers1

1

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.

rs232
  • 1,248
  • 8
  • 16
  • This is what i first though but Is there a way to clear this input queue? – SuperMinefudge Mar 28 '17 at 12:15
  • http://stackoverflow.com/questions/3769770/clear-console-buffer i think i found the solution pelase confirm if this is the right thing :) – SuperMinefudge Mar 28 '17 at 12:16
  • It really depends on what you are trying to achieve. If just loosing all the user input you did not process in time is ok for you, then definitely it is the solution. However, if I was making a snake game, I would rather consider moving away from a regular console input completely as it is too slow and does not really fit such a fast reaction-based game. – rs232 Mar 28 '17 at 12:31
  • i'm using Keybaord.IsKeyDown() to determine weather the key is pressed and then move/continue moving accordingly – SuperMinefudge Mar 28 '17 at 12:47
  • Oh, in that case just clearing the console buffer should be perfectly fine! – rs232 Mar 28 '17 at 12:54