Game loop problem.

wyrd

Well-known member
Joined
Aug 23, 2002
Messages
1,408
Location
California
EDIT: Nevermind, I simply forgot Application.DoEvents *slaps self* .. works fine now.

I have my main game code inside a class (Game). The form simply creates a new instance of Game (passing in this.CreateGraphics() which the game class uses for displaying images), and then calls Game.Start() to start the game. The problem is the game loop goes nuts and never returns control of the form to the user (the form freezes and you cant do anything to it).

At first I thought maybe it was because the loop was inside a class, so I put the game loop inside the form and just called this.Refresh() for game updates. That didnt seem to work.

Its been a while since Ive made a game loop, so am I missing something? Did I do my game loop wrong?

Would passing in this.CreateGraphics() (from the form) cause this problem? I am correct in using this graphics object to display images right? Ill debug the rest of my code just to see if this problem could be from something else, but Im pretty convinced its my game loop (its been a while since Ive made one, so I just hacked this thing together).

C#:
/// <summary>
/// Starts the game.
/// </summary>
public void Start() {
   // Set initial mode.
   _mode = GameModes.FallingShape;

   // Time to next update.
   int nextTime = 0;

   // Go until game ends.
   while (_mode != GameModes.End) {
      // Check if game needs update.
      if (Environment.TickCount > nextTime) {
         _update();

         // Get next update time.
         nextTime = (1000 / GameSpeed) + Environment.TickCount;
      }
   }
}
 
Last edited by a moderator:
Instead of calling Application.DoEvents(), which is a very heavyweight API you might want to use [api]PeekMessage[/api] to get better performance. Just a thought.
 
Easier method that just as efficient:

----------------------------------------------------------------
System.Threading.Thread.CurrentThread.Sleep(0)
----------------------------------------------------------------

Sleeps the thread and allows waiting threads to execute.

Downside is you could lose a tiny bit of performance on the game loop when there is no user activity, but this shouldnt be a problem since your code is really just looping to wait on something anyway.
 
The CurrentThread didnt have a Sleep() method, but Thread did. I tried using Thread.Sleep() and it updated the graphics object, but wouldnt allow me to move the form, click on any menus, keys werent working, etc.
 
Back
Top