Question

I want to create a simple 2D game. I don't want to use threads. The programming language will be Java (but could be any language, does not really matter...).

Is it possible to avoid high CPU usage if I use a main loop like while(true)... (infinite loop)?

Was it helpful?

Solution

In a game you typically have a main loop that runs everything. However, in order to avoid doing unnecessary things, it is typical to only update the game at a certain frame-rate (such as 60 Frames Per Second (FPS)).

Most games accomplish this by causing the CPU to sleep until a new frame needs to be calculated/drawn. In the python game library, pygame, this is done using pygame.time.wait:

Will pause for a given number of milliseconds. This function sleeps the process to share the processor with other programs. A program that waits for even a few milliseconds will consume very little processor time.

OTHER TIPS

To illustrate Darthfett's answer, the main loop for a console game would typically look something like:

#define FRAMELENGTH (1.0 / 60.0) // 60hz = 16.6ms per NTSC frame. Different for PAL. 
while ( !QuitSignalled() ) 
{
   double frameStartTime = GetTime(); // imagine microsecond precision
   HandleUserInput( PollController() );
   SimulateEntities(); 
   Physics();
   Render();
   Sound();
   etc();

   double timeUntilNextFrameShouldStart = GetTime() - frameStartTime + FRAMELENGTH;
   sleep( timeUntilNextFrameShouldStart  );   
}
// if down here, we got the 'quit' signal 
ExitToDesktop();

Of course the loop above will break if a frame ever takes more than 16.6ms to execute, so we have special code to detect that and catch up or drop frames, but that's the basic idea. Also, until recently we didn't actually use floating-point numbers for time, but fixed-point microsecond counters.

All you have to do is "block on input" ... and you get zero CPU usage. Until something happens, anyway.

Just about any sockets program will have a loop something like this:

  while (true) {
    select ()
    ...

You could just as easily wait on a "getchar()", or "WaitOnSingleEvent()"

One could argue that "block on I/O" is actually an optimal design strategy. It beats the heck out of the alternative - "polling" (Polling is Evil).

IMHO..

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