Beginning Game Programming for Teens with Python

This is a post by Tutorial Team Member Julian Meyer, a 13-year-old python developer. You can find him on Google+ and Twitter. 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 […] By .

4 (17) · 2 Reviews

Download materials
Save for later
Share
You are currently viewing page 2 of 5 of this article. Click here to view the first page.

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.

  1. Import the PyGame library. This allows you to use functions from the library in your program.
  2. Initialize PyGame and set up the display window.
  3. Load the image that you will use for the bunny.
  4. Keep looping over the following indented code.

    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. :]

  5. Fill the screen with black before you draw anything.
  6. Add the bunny image that you loaded to the screen at x=100 and y=100.
  7. Update the screen.
  8. Check for any new events and if there is one, and it is a quit command, exit the program.

    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.

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.

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. :]

Step 2: Add Scenery

Let’s start by adding a background to the game scene. This can be done with a couple more screen.blit() calls.

At the end of section #3, after loading the player image, add the following code:

grass = pygame.image.load("resources/images/grass.png")
castle = pygame.image.load("resources/images/castle.png")

This loads the images and puts them into specific variables. Now they have to be drawn on screen. But if you check the grass image, you will notice that it won’t cover the entire screen area, which is 640 x 480. This means you have to tile the grass over the screen area to cover it completely.

Add the following code to game.py at the beginning of section #6 (before the player is drawn on screen):

    for x in range(width/grass.get_width()+1):
        for y in range(height/grass.get_height()+1):
            screen.blit(grass,(x*100,y*100))
    screen.blit(castle,(0,30))
    screen.blit(castle,(0,135))
    screen.blit(castle,(0,240))
    screen.blit(castle,(0,345 ))

As you can see, the for statement loops through x first. Then, within that for loop, it loops through y and draws the grass at the x and y values generated by the for loops. The next couple of lines just draw the castles on the screen.

If you run the program now, you should get something like this:

Much better – this is starting to look good! :]

Step 3: Make the Bunny Move

Next you need to add some actual gameplay elements, like making the bunny respond to key presses.

To do that, first you’ll implement a good method of keeping track of which keys are being pressed at a given moment. You can do this simply by making an array of key states that holds the state of each key you want to use for the game.

Add the following code to game.py at the end of section #2 (after you set the screen height and width):

keys = [False, False, False, False]
playerpos=[100,100]

This code is pretty self-explanatory. The keys array keeps track of the keys being pressed in the following order: WASD. Each item in the array corresponds to one key – the first to W, the second to A and so on.

The playerpos variable is where the program draws the player. Since the game will move the player to different positions, it’s easier to have a variable that contains the player position and then simply draw the player at that position.

Now you need to modify the existing code for drawing the player to use the new playerpos variable. Change the following line in section #6:

    screen.blit(player, (100,100))

To:

    screen.blit(player, playerpos)

Next, update the keys array based on which keys are being pressed. PyGame makes detecting key presses easy by adding event.key functions.

At the end of section #8, right after the block checking for event.type==pygame.QUIT, put this code (at the same indentation level as the pygame.QUIT if block):

        if event.type == pygame.KEYDOWN:
            if event.key==K_w:
                keys[0]=True
            elif event.key==K_a:
                keys[1]=True
            elif event.key==K_s:
                keys[2]=True
            elif event.key==K_d:
                keys[3]=True
        if event.type == pygame.KEYUP:
            if event.key==pygame.K_w:
                keys[0]=False
            elif event.key==pygame.K_a:
                keys[1]=False
            elif event.key==pygame.K_s:
                keys[2]=False
            elif event.key==pygame.K_d:
                keys[3]=False

Wow! Those are a lot of lines of code. If you break it down into the if statements though, it’s not that complicated.

First you check to see if a key is being pressed down or released. Then you check which key is being pressed or released, and if the key being pressed or released is one of the keys you’re using, you update the keys variable accordingly.

Finally, you need to update the playerpos variable in response to the key presses. This is actually very simple.

Add the following code to the end of game.py (with one indentation level, putting it at the same level as the for loop):

    # 9 - Move player
    if keys[0]:
        playerpos[1]-=5
    elif keys[2]:
        playerpos[1]+=5
    if keys[1]:
        playerpos[0]-=5
    elif keys[3]:
        playerpos[0]+=5

This code simply checks which of the keys are being pressed and adds or subtracts from the player’s x or y position (depending on the key pressed) to move the player.

Run the game and you should get a player just like before. Try pressing WASD. Yay! It works.