Game loop problem.

wyrd

Senior Contributor
Joined
Aug 23, 2002
Messages
1,405
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 can't 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 didn't seem to work.

It's been a while since I've 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? I'll debug the rest of my code just to see if this problem could be from something else, but I'm pretty convinced it's my game loop (it's been a while since I've 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:
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 shouldn't be a problem since your code is really just looping to wait on something anyway.
 
The CurrentThread didn't have a Sleep() method, but Thread did. I tried using Thread.Sleep() and it updated the graphics object, but wouldn't allow me to move the form, click on any menus, keys weren't working, etc.
 
Back
Top