Structuring Your Game
00:00 In the previous lesson, I showed you how to make very quick blue speckles in a dazzling display of randomness. In this lesson, I’ll show you how to structure your code files to get ready for larger programs.
The typical way of running a Python script is to use the
python command and pass it the script file, or if you’re on a Unix-based system, use the hash-bang (
#!) control at the top of the file, which is really just a shortcut for doing the same thing.
00:26 There is another way of doing things, though. You can run a directory instead of running a single file. This can be useful when you want to split your code up into multiple files and you don’t want your user to have to figure out which one is the one to run.
There will be other files in there as well, such as
game.py, where a lot of the game logic will live. With this structure in place, calling the Python interpreter with the
space_rocks directory as a parameter will result in your game running.
As I mentioned before, the first file you’ll need is
__main__.py. The contents of
__main__.py will be pretty simple. It imports and creates a
SpaceRocks object from the
game file and then runs its
All of this is done inside of a
__name__ check on line 4. If you haven’t seen this before, this
if statement is checking if the script is being run as code, as opposed to being loaded as a module. Inside of a
__main__.py file, this is likely redundant.
Line 12 defines the core game loop. Inside of here, you’ll find the
while loop. It checks for input, does any game logic, and draws a frame. No different than
blue.py, just reorganized to be a bit more clear.
In each iteration of the loop, you’re going to check for events that need handling. That’s the
._handle_input() method. Just like in
blue.py, I’m starting out here just checking for whether or not
QUIT was pushed.
03:14 The second part of the game loop, which is doing the game logic, is defined on line 23. This is just a placeholder for now. There isn’t any logic yet, but this will be where objects can be moved around.
03:26 Expect great spaceship and rock position logic here in the future. Let me just scroll down. The final part of the game loop is the drawing. This first version of Space Rocks does nothing but draw a blue background.
03:54 Isn’t this exciting? Not exactly the easiest game to win, but you’re ready to go! With this, a multi-million dollar budget, and several hundred developers, you could be writing Call of Duty in no time. Okay, enough with the Call of Duty references.
04:13 Don’t tell Bill Gates I said so, but blue screens are so passé. Next up, I’ll show you how to import graphics. Ultra-violence and drive-by shootings, here you come. Told you there’d be a GTA reference.
Become a Member to join the conversation.