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 Zero: 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-zero 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 pgzrun
    
    WIDTH = 800
    HEIGHT = 600
    
    pgzrun.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 pgzrun.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 Zero 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 pgzrun

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()

pgzrun.go()

New Images

This lab uses three new images. If you completed Getting Set Up for Pygame Zero, 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 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 to swap between the two bee images, over and over.

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

        if bee.image == "bee_a":
            bee.image = "bee_b"
        else:
            bee.image = "bee_a"
    

    If the bee's image is bee_a.png, we update it to bee_b.png. Otherwise, we update it to bee_a.png — because it must have already been set to bee_b.png.


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, 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.