4.2.5 - Frame processing and ending

The Main loop

The basic logic and order for each frame of the game:

  • While not done:
  1. For each event (keypress, mouse click, etc.):
  2. Use a chain of if statements to run code to handle each event.
  3. Run calculations to determine where objects move, what happens when objects collide, etc.
  4. Clear the screen
  5. Draw everything

It makes the program easier to read and understand if these steps aren't mixed togther.

Frames Per Second (FPS)

The code for drawing the image to the screen happens inside the while loop

With the clock tick set at 10, the contents of the window will be drawn 10 times per second. If we need animation this is very slow.

If the clock tick is more than the computer can handle then computer will not be able to process everything in time because all of its time is spent updating the screen. 

Ending

Right now, clicking the “close” button of a window while running this Pygame program in IDLE will still cause the program to crash. This is a hassle because it requires a lot of clicking to close a crashed program.

The problem is, even though the loop has exited, the program hasn't told the computer to close the window. By calling the command below, the program will close any open windows and exit as desired.

pygame.quit()

Fortunately Thonny has a  button in case that we forgot to terminate the script properly.

Clearing the Screen

The following code clears whatever might be in the window with a white background. Remember that the variable WHITE was defined earlier as a list of 3 RGB values.

screen.fill(WHITE)

Flipping the Screen

Very important! You must flip the display after you draw. The computer will not display the graphics as you draw them because it would cause the screen to flicker. This waits to display the screen until the program has finished drawing. The command below “flips” the graphics to the screen.

Failure to include this command will mean the program just shows a blank screen. Any drawing code after this flip will not display.

pygame.display.flip()