Question


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.

Was it helpful?

Solution 2

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());
            }
        }
    }
}

OTHER TIPS

You do not need to use different threads for each ghost. This can all be done on one thread using a Game Loop

The central component of any game, from a programming standpoint, is the game loop. The game loop allows the game to run smoothly regardless of a user's input or lack thereof.

Most traditional software programs respond to user input and do nothing without it. For example, a word processor formats words and text as a user types. If the user doesn't type anything, the word processor does nothing. Some functions may take a long time to complete, but all are initiated by a user telling the program to do something.

Games, on the other hand, must continue to operate regardless of a user's input. The game loop allows this. A highly simplified game loop, in pseudocode, might look something like this:

   while( user doesn't exit )
     check for user input
     run AI
     move enemies
     resolve collisions
     draw graphics
     play sounds
   end while

The game loop may be refined and modified as game development progresses, but most games are based on this basic idea.

Follow that pattern and your game will be much easier to write.

Finally found what i do need :
Threads and Thread Synchronization in C#

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top