Search code examples
c#multithreadingpacman

Using thread two part of a program differently



I'm actually coding a pacman (C# Console) i would like to know how to move my ghost each seconds, but i would also like to be able to move my pacman whenever i want.

I would like my ghost keep mooving each second whatever pacman do, i should be able to move pacman when ever i want, and ghosts just have to move every second.

I guess i have to use Thread system, so i would like to know if you know how i have to proceed and how thread works, can't find any information about that :s.


Solution

  • You're probably confused because Console.ReadKey() is blocking...so your game loop would be stuck waiting for the user to press a key right? What you do is only grab the keystroke with ReadKey() if there is already one in the queue. This can be checked with Console.KeyAvailable which returns true if a key is already there. This way the game loop just keeps looping around if no key has been pressed...but you can still trap it and do something with it. Try this quick example out and see what happens:

    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                System.Threading.Thread.Sleep(250);
                Console.Write(".");
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo key = Console.ReadKey(true); // read key without displaying it
                    Console.WriteLine("");
                    Console.WriteLine("Key Pressed: " + key.KeyChar.ToString());
                }
            }
        }
    }