Beginning Game Programming for Teens with Python
- Getting Started: Installing Python
- Running Python Code from File
- Adding the Game Resources
- Step 1: Hello Bunny
- Step 2: Add Scenery
- Step 3: Make the Bunny Move
- Step 4: Turning the Bunny
- Step 5: Shoot, Bunny, Shoot!
- Step 6: Take Up Arms! Badgers!
- Step 7: Collisions with Badgers and Arrows
- Step 8: Add a HUD with Health Meter and Clock
- Step 9: Win or Lose
- Step 10: Gratuitous Music and Sound Effects!
- Where To Go From Here?
Have you ever wondered how video games are created? It’s not as complicated as you might think!
In this tutorial, you’ll create a simple game called Bunnies and Badgers, where the hero, the bunny, has to defend a castle against an attacking horde of badgers. :O
To write this game, you’ll use Python. No, I’m not talking about a big snake! :]
Python is a computer programming language. We chose Python for this tutorial because it’s a simple language to start out with, and is fun and easy to learn.
If you are new to Python, before you begin check out this book: Think Python: How to Think Like a Computer Scientist. That should get you up to speed.
Then dive back here and get ready – there’s a war coming on between the bunnies and the badgers. Keep reading to jump into the fray!
Getting Started: Installing Python
If you want to try this tutorial on a Windows PC, you need to install Python. Make sure you grab the 2.7.3 version and NOT the 3.3.0 version! After running the installer, you should have IDLE in your All Programs folder in your start menu. Launch IDLE to get started.
If you are on a Mac, you already have Python installed! Just open Terminal (/Applications/Utilities/Terminal.app), type in python and press Enter.
Note: If you install Python from python.org (and might have to if you want to get PyGame working), then you’ll also have access to IDLE on the Mac as well. It should be in the “/Applications/Python 2.7” folder.
If you did it correctly, you should see something like this:
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>
Note: If you want to exit the Python prompt (the triple angle brackets, >>>), you can either type exit() at the Python prompt and press Return or you can press Control+D.
Once you are at the Python prompt, to test if Python is correctly working, type in print 1+1 and hit Enter/Return. It should print 2. You have just written your first Python program!
Now that you know Python is working correctly, you need to install PyGame in order to write a game using Python.
PyGame is a Python library that makes writing games a lot easier! It provides functionality such as image handling and sound playback that you can easily incorporate into your game.
Go here and download the PyGame installer appropriate for your system. Make sure you download a Python 2.7 version.
Note: The PyGame installer from the link above will not work with the default Python from Apple that is installed on a Mac. You’ll need to download Python from python.org and install it in order to use PyGame. Or, you can install both Python and PyGame via MacPorts.
To verify that you have PyGame installed properly, open IDLE or run Python via the Terminal and type in import pygame at the Python prompt. If this doesn’t result in any output, then you’re good.
If, on the other hand, it outputs an error like what’s shown below, then PyGame is not installed.
Python 2.7.2 (default, Jun 20 2012, 16:23:33) [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import pygame Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named pygame >>>
If you get an error like this, post on the forums and I will help you get it working.
Running Python Code from File
While you can run short bits of Python code at the Python prompt, if you want to work on a bigger program (like a game), you probably want to save your code to a file so that you don’t have to type it in over and over again.
There are several ways to run a Python program as a file. One way is to use a plain text editor like Notepad (Windows), or TextEdit (Mac). Open a new text file, type in your Python code (like print 1+1). Then save it as XXX.py (The XXX can be any descriptive file name).
Then on Windows, double-click this file to run it. On Mac, open Terminal and type python, then drag the file that you saved onto the Terminal window and press Enter.
The other way is to type in your code using the IDLE editor, which is what you’re going to do in this tutorial. To run idle, simply type idle from Terminal. Then choose File\New Window from the IDLE menu and you should have a text editor window where you can type in Python code. You can save your code changes via File\Save and even run the code via Run\Run Module (F5).
Do note that the Run menu is only available if you have a file open in an editor window.
Adding the Game Resources
You are almost ready to create your game. But what’s a game without some great graphics and sound effects? I’ve put together all the graphics and sound effects you’ll need for your game into a ZIP archive. You can download it via the Download Materials button at the top and bottom of this page.
Once you’ve downloaded the file, create a folder for your game on your hard disk and extract the resources folder into that folder so that your game folder has a subfolder named resources, with the various resources grouped in additional folders inside it, like this:
You are now ready to begin creating Bunnies and Badgers. :]
Step 1: Hello Bunny
Run IDLE and open a new text editor window, as mentioned in the previous section. Type the following code into the editor window:
# 1 - Import library import pygame from pygame.locals import * # 2 - Initialize the game pygame.init() width, height = 640, 480 screen=pygame.display.set_mode((width, height)) # 3 - Load images player = pygame.image.load("resources/images/dude.png") # 4 - keep looping through while 1: # 5 - clear the screen before drawing it again screen.fill(0) # 6 - draw the screen elements screen.blit(player, (100,100)) # 7 - update the screen pygame.display.flip() # 8 - loop through the events for event in pygame.event.get(): # check if the event is the X button if event.type==pygame.QUIT: # if it is quit the game pygame.quit() exit(0)
Save the file into your game folder (the one where the resources subfolder is) and name it game.py.
Let’s go through the code section-by-section:
Note: Where other languages like Objective-C, Java or PHP use curly braces to show a block of code to be executed within a while loop or an if statement, Python uses indenting to identify code blocks. So proper indentation is very important in Python – keep that in mind. :]
Note: According to the PyGame documentation, you shouldn’t need to call pygame.quit() since the interpreter will automatically call it when the interpreter shuts down. However, at least on Mac OS, the game would hang on exit unless pygame.quit() was called.
- Import the PyGame library. This allows you to use functions from the library in your program.
- Initialize PyGame and set up the display window.
- Load the image that you will use for the bunny.
- Keep looping over the following indented code.
- Fill the screen with black before you draw anything.
- Add the bunny image that you loaded to the screen at x=100 and y=100.
- Update the screen.
- Check for any new events and if there is one, and it is a quit command, exit the program.
If you run the code now (via Run\Run Module in the Idle menu), you should see a screen similar to the one below:
w00t the bunny is in the scene, and ready for action!
But the game looks scary and lonely with the bunny just standing there on a black background. Time to prettify things a little bit. :]