I'm making a reaction time game. This is the code:
Thread.Sleep(rnd.Next(1000, 5000));
Console.Write("NOW: ");
long start = DateTime.Now.Ticks;
Console.ReadKey(true);
long timePassed = DateTime.Now.Ticks - start;
if (timePassed < 5_000_000) Console.WriteLine("Fast");
else Console.WriteLine("Slow");
The problem is that you can press the key whilst the program is sleeping and then when it is checking for keypresses it will think that you pressed the key instantly which ruins the game.
CodePudding user response:
The Console
class has a KeyAvailable
property (https://learn.microsoft.com/en-us/dotnet/api/system.console.keyavailable).
Right before you output "NOW: "
, use a while
loop with a call to Console.KeyAvailable
(and possibly ReadKey
) to empty the input buffer.