All that's left now is creating a Python script that will make use of our level and game module. To run our level, simply create a file named playAsteroid.py:
Of course, we can always customize our game a bit more. Let's say that we want to use a title screen rather than forcing the user to jump right into the level. Also, let's display either “Level Complete” or “Game Over”:
# Wait for enter to be pressed # The user can also quit waiting = True while waiting: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: waiting = False break
pydodge.loadBackground() pydodge.loadSprites()
# The user has won the game if pydodge.run(100, 300): text3 = font1.render('Level Complete', True, (255, 255, 255)) textRect3 = text3.get_rect() textRect3.centerx = pydodge.screen.get_rect().centerx textRect3.y = 150 pydodge.screen.blit(text3, textRect3)
# The user has lost the game else: text3 = font1.render('Game Over', True, (255, 255, 255)) textRect3 = text3.get_rect() textRect3.centerx = pydodge.screen.get_rect().centerx textRect3.y = 150 pydodge.screen.blit(text3, textRect3)
pygame.display.update()
# Wait for the user to quit while True: for event in pygame.event.get(): if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN): sys.exit()
Conclusion
As you can see, creating a functioning game with PyGame is rather easy. Our game module weighs in at around five kilobytes. Using the module, you can also customize games, loading whatever levels you would like and displaying extra messages and what-not.
From here, try customizing your game even further. You can try adding a menu where the user can select a difficulty level. You can also link multiple levels together and randomize the layout lists in levels. It's up to your imagination.
Of course, there's a lot more to PyGame than a simple space game like this, so feel free to explore the library and examine one of the many example games available on the PyGame website. Good luck!