Module 4 - Section 2 - Graphics
- identify the commands inside the Pygame basic template
- experiment with various graphics commands
- draw shapes using Python commands
- draw text using Python commands
4.2.5 - Frame processing and ending
The Main loop
The basic logic and order for each frame of the game:
- While not done:
- For each event (keypress, mouse click, etc.):
- Use a chain of if statements to run code to handle each event.
- Run calculations to determine where objects move, what happens when objects collide, etc.
- Clear the screen
- 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.
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.
Fortunately Thonny has a button in case that we forgot to terminate the script properly.
Clearing the Screen
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.