1668A, 14th Main Rd, Sector 7, HSR Layout, Bengaluru, Karnataka 560102
+91 99459 30733 (9am - 6pm IST, Tuesday - Sunday)
Pygame a cool Python module to build awesome games that's interesting to play and easy to build. Pygame limited by Python interpreters speed is suited for 2D games and works pretty well.
Every game developed in Pygame makes use of a game loop. This game loop is nothing but an endless while loop that redraws every bit of game elements every cycle. Number of cycles running every second is controlled by your hardware of your computer which translates into FPS (frames per second). Your computer will try to run the cycles at highest possible FPS. Many games do not required this high FPS for drawing. This is where you can optimise your game code.
Optimization 1. Control the FPS Use Pygame 's time module to control the clock speed. This is how you can code that:
clock = pygame.time.Clock()
fps = 30
while True:
clock.tick(fps)
This will restrict the while loop to run at FPS of 30 instead of its top speed.
Optimization 2. Control the loop execution with events Make games like Hangman, Chess or any card game wait for user to take any action. Until that happens nothing in the screen needs to the redrawn. This can be used to control the speed of execution of the while loop.
To trap the events generally in pygame one would something like this:
while True:
for event in pygame.event.all():
do something
Above will keep checking on the events every cycle. But in games where redrawing of screen needs user event then this can be controlled something like this:
while True:
event = pygame.event.wait()
if event.type == pygame.MOUSEBUTTONDOWN:
do something
Your game would be waiting at pygame.event.wait() and will proceed when user does some event. Depending on the event that was triggered you can perform different game logic.
By using above two optimizations I could bring down cpu time for my game to 1.3% down from 70%. Try these optimizations and you will be amazed how efficient your game has become.