Now it's time to begin coding the internals of our game. Create a file called pydodge.py (after all, our game is about dodging objects) to store our game module, and let's jump into some code. First, we'll need to import the required modules:
First, we import the imp module. The imp module will allow us to import modules in a more dynamic fashion. Since we store our levels as Python classes and will access them by importing them as modules, this functionality is needed. We then import the gamesprites module, which we constructed earlier to store the game's Sprite classes, as well as pygame itself. Finally, sys is imported since we need to make use of sys.exit.
Next, we'll need to take care of some global variables:
Don't worry about what each one of these means right now. We'll cover the purpose of each one as it is used.
Loading Levels
The first thing that needs to be done is the loading of levels. We'll need to import the specified level file and then extract some basic information from it, such as the object images and the layout of the level as a whole:
def loadLevel(levelFile):
# Import the level and extract the data global level, player, objects, background, rows, columns, layout level = imp.find_module(levelFile) level = imp.load_module('level', level[0], level[1], level[2]) level = level.Level() player = level.getPlayer() objects = level.getObjects() background, rows = level.getBackground() layout = level.getLayout() columns = len(layout[0])
In the above function, we use the imp module to search for the level by its name. Then, we import it as level. However, since we only need the single Level class that it contains, we re-assign level to an instance of the contained Level class. We then extract the player image and assign it to the player variable, and we get the list of object images and assign it to the objects variable. Next, we get the background image and the number of rows that will be visible at once. Finally, we get the layout list and retrieve the number of columns it calls for.