Skip to content

More Characters and Collisions

In Nice Bike! you placed shapes that sat still. This time, things move. You'll drive an alien around the screen with the arrow keys, hand a friend the W A S D keys to fly a bee, and teach the game to notice when the two touch. The alien, for the record, is allergic to bee stings.


Overview

In this lab you'll build a basic game where an Actor — the alien — moves with the keyboard and wraps around the screen edges. Then you'll add a second character, detect collisions between the two, and animate the bee's wings.

Builds on: Pygame Turbo: Nice Bike! — the window variables and the draw() function.

Follow along

We build the first part of this game together in class. If you were out (or you'd like to rebuild it yourself), the numbered steps below get you to the same place.

Before you start

Open Thonny and start a new program named alien_game.py. Save it in your pygame-turbo folder, next to your images folder.

You've got it when…

  • The alien moves with the arrow keys and wraps around all four edges of the screen.
  • The bee moves with W A S D and wraps around too.
  • The alien changes its look while the bee is touching it, and changes back when it isn't.
  • The bee flaps its wings.

Collaboration & AI

Work: On your own, though you'll need to borrow a neighbor to playtest the two-player result.

AI — AIAS Level 1, No AI: This lab is about learning Actors and collisions by writing them yourself, so set AI aside for the code. What the levels mean.


The Basic Game

First we'll get the alien on screen and moving.

  1. Start alien_game.py with the bookends and the window size.

    alien_game.py
    import pgtrun
    
    WIDTH = 800
    HEIGHT = 600
    
    pgtrun.go()
    
  2. An Actor is a character or object in your game, drawn from an image in your images folder. Create the alien just below the window variables. Add the highlighted lines.

    WIDTH = 800
    HEIGHT = 600
    
    # create the alien
    alien = Actor("alien")
    alien.x = 0
    alien.y = 300
    

    Info

    Actor("alien") loads images/alien.png. Notice that we use only the name of the image, without the ".png" part at the end.

  3. Add the draw() function above pgtrun.go() to paint the sky, a sun, and the alien on every frame.

    def draw():
        screen.fill("skyblue")
        screen.draw.filled_circle((700, 100), 50, "yellow")
        alien.draw()
    

    Run your program. The alien should sit near the left edge, with a yellow sun in the corner.

  4. Now for movement. Pygame Turbo calls a special function named update() many times per second, and keyboard tells us which keys are down right now. Add this function between the alien and draw().

    def update():
        # keyboard keys for moving the alien
        if keyboard.right:
            alien.x = alien.x + 10
        if keyboard.left:
            alien.x = alien.x - 10
        if keyboard.up:
            alien.y = alien.y - 10
        if keyboard.down:
            alien.y = alien.y + 10
    

    Try it. The alien moves with the arrow keys — and drives right off the edge of the screen if you let it.

  5. Keep the alien on the screen by wrapping it around to the opposite edge. Add the highlighted lines to the bottom of update().

    def update():
        # keyboard keys for moving the alien
        if keyboard.right:
            alien.x = alien.x + 10
        if keyboard.left:
            alien.x = alien.x - 10
        if keyboard.up:
            alien.y = alien.y - 10
        if keyboard.down:
            alien.y = alien.y + 10
    
        # keep the alien on the screen...wrap around if it goes beyond the screen
        if alien.x > WIDTH:
            alien.x = 0
        if alien.x < 0:
            alien.x = WIDTH
        if alien.y < 0:
            alien.y = HEIGHT
        if alien.y > HEIGHT:
            alien.y = 0
    

Checkpoint

Drive off any edge of the screen. The alien should reappear on the opposite side. That's the basic game — everything from here builds on it.

The whole program so far
alien_game.py
import pgtrun

WIDTH = 800
HEIGHT = 600

# create the alien
alien = Actor("alien")
alien.x = 0
alien.y = 300

def update():
    # keyboard keys for moving the alien
    if keyboard.right:
        alien.x = alien.x + 10
    if keyboard.left:
        alien.x = alien.x - 10
    if keyboard.up:
        alien.y = alien.y - 10
    if keyboard.down:
        alien.y = alien.y + 10

    # keep the alien on the screen...wrap around if it goes beyond the screen
    if alien.x > WIDTH:
        alien.x = 0
    if alien.x < 0:
        alien.x = WIDTH
    if alien.y < 0:
        alien.y = HEIGHT
    if alien.y > HEIGHT:
        alien.y = 0

def draw():
    screen.fill("skyblue")
    screen.draw.filled_circle((700, 100), 50, "yellow")
    alien.draw()

pgtrun.go()

New Images

This lab uses three new images. If you completed Getting Set Up for Pygame Turbo, they are already in your images folder. If one is missing, download it here and save it there.

The bee, wings up. bee_a.png

The bee, wings down. bee_b.png

The bee is in two places

The same two bee pictures also live in your animations folder, as animations/bee/bee_0.png and animations/bee/bee_1.png. That's where the Animation section at the end of this lab will look for them. If that folder is missing, make it and copy the two downloads into it with those names.

The alien reacting to the bee. alien_hit.png


Add a Character

Let's add a bee character to the game — a second player.

  1. Near the top of your program where we created the alien Actor, create a new Actor for your bee. Create a variable named bee and set it to be a new Actor that uses your bee_a.png file.

    bee = Actor("bee_a")
    
  2. Immediately below that line, set an x position and a y position for the bee, just like we did for the alien. Start it anywhere you like on the screen — away from the alien.

  3. Your bee won't show up on the screen yet. For that, we need to call the bee's draw() function inside our draw() function. Notice how we did this for the alien, and do the same for the bee.

    You should now see the alien and your bee on the screen when you run your program. If not, check the steps above.

  4. Add a section of code to the update() function to move the bee using the W (up), A (left), S (down), and D (right) keyboard keys. Notice how we did this for the alien using the arrow keys.

    Stuck? Open for a hint.

    keyboard.w, keyboard.a, keyboard.s, and keyboard.d work exactly like keyboard.up and its neighbors — they just watch different keys.

  5. Add a section of code to the update() function to keep the bee on the screen, wrapping it around if it goes off an edge. Notice how we did this for the alien.

Checkpoint

You should now be able to move the bee and the alien separately with the keyboard at the same time.


Detecting Collisions

The alien is allergic to bee stings and gets nervous if the bee is too close.

Both the alien and the bee have an invisible rectangle around them. We can check whether two rectangles are touching, or colliding.

  1. Add this code to the bottom of your update() function.

        if bee.colliderect(alien):
            alien.image = "alien_hit"
        else:
            alien.image = "alien"
    

    When the bee and alien are colliding, we update the alien's image to the alien_hit.png file. When they are not colliding, we restore the original. Notice again that we use the image name without the ".png".

    Info

    We checked whether the bee is colliding with the alien, but you could just as well check whether the alien is colliding with the bee. These two are the same:

    if bee.colliderect(alien):
    
    if alien.colliderect(bee):
    

    Try playing the game with a friend.


Animation

Let's animate the bee to make it appear to flap its wings. The trick is the one every cartoon uses: show two slightly different pictures one after the other, fast enough that your eye sees motion. Pygame Turbo has a built-in animation system that does the swapping for us. We tell it which pictures to use and how fast to play them, and it loops on its own.

The pictures for an animation live in your animations folder, in a subfolder named after the animation. The setup lab put animations/bee/bee_0.png and animations/bee/bee_1.png in place for you — the two bee pictures, numbered in the order they should play.

  1. Add the highlighted lines just below where you created the bee Actor.

    bee = Actor("bee_a")
    bee.x = 600  # or wherever you started your bee
    bee.y = 300
    
    bee.anim.add("bee", durations=0.2)
    bee.anim.set_base("bee")
    

    bee.anim.add("bee", durations=0.2) loads every picture in animations/bee and says that one full run through them — both wing positions — should take 0.2 seconds. bee.anim.set_base("bee") makes it the bee's base animation: the one that plays whenever nothing else is going on, over and over, with no extra code in update().

    Try your program. The bee should flap.

  2. Change 0.2 to 1.0 and run the program again, then try 0.05. Keep whichever flap speed you like.

Why not swap the images ourselves?

You could. An if statement in update() that flips bee.image between "bee_a" and "bee_b" works — and flaps sixty times a second, because update() runs sixty times a second. Slowing that down takes a counter and more if statements. The animation system handles the timing, which is the tedious part.


Turn It In

  • Submit your alien_game.py file in Google Classroom.

How It's Graded

This lab is worth up to 4 points. One score covers everything you turn in.

Score What it looks like
4 — Excellent Both characters fly on their own keys — arrows and WASD — and wrap around all four edges. The alien flinches exactly while the bee touches it and recovers the moment it doesn't, the bee flaps its wings with a base animation, and it all held up in a two-player playtest.
3 — Above Average Everything works with a small slip — one edge that doesn't wrap, or an alien that stays stuck on its hit image.
2 — Average The alien flies and wraps, but the bee is half-added or the collision check is missing.
1 — Below Average Little beyond the base game we built together in class.
0 — Failing Nothing submitted, or the program doesn't run.