Sign InCoursewareNuggetsTutorials AboutClassesCodePad

Multiple Files

As your game gets more complex, your Python file might become hard to manage when it is too large. It is a good idea to break one big file into multiple files, grouped by functionality. Go ahead and do the following:

  • Create a file named constants.py. Move the constant definitions at the beginning of game.py to it.
  • Create a file named player.py. Move the Player class definition to it. Add a line at the beginning to import pygame.
  • Create a file named platforms.py. Move the Platform class definition to it. Add a line at the beginning to import pygame. Do NOT call your file platform.py because it conflicts with another name in the Python library.

After the files are created, you can try to run your python game from command line (type python3 game.py on Mac or python game.py on PC). You will get an error message:

NameError: name 'SCREEN_WIDTH' is not defined

Because the constant definitions are in a separate module, you need to import them into game.py in order to use them. Similarly, player.py and platforms.py use some constants as well. Add the following line of code at the beginning of game.py, player.py and platforms.py:

from constants import *

Also, import Player and Platform from player and platforms module in game.py because both classes are used there.

from player import Player from platforms import Platform
© CS Wonders·About·Classes·Cheatsheet