Skip to main content

Lab 6

Objectives

  • Read a complete pygame game built from classes, and compare it with your own Lecture 20 code
  • Write a new class by following the pattern of one you already have
  • Write methods that make objects interact, keeping the game’s logic in methods where it can be tested without opening a window

In this lab you’ll turn the Lecture 20 dodge game into a snowfall game. Move the orange square with the arrow keys, dodge the gray rocks, and catch the snowflakes to score.

Part 0: Setup

Download the file lab6.zip by clicking the blue “Download Starter Code” button above; move the zip file to your cs145/labs directory, then extract it (Mac: double-click it; Windows: right-click it and choose “Extract All…”) to create a subfolder called lab6 inside your labs directory. Then delete lab6.zip.

The folder contains one file, lab6.py.

Does pygame run? Open lab6.py in Thonny and run it. A window should open with gray rocks falling; close it to stop. If you get ModuleNotFoundError: No module named 'pygame', install midd-media as in Lecture 17 (see Working with Images), or ask for help now. pygame comes with midd-media: don’t install pygame separately, since it conflicts with the version midd-media uses.

Getting started

At the top of lab6.py are constants for the sizes, speeds, and colors; use them rather than typing numbers like 600 or 20. Then come:

  • Ball, Player, and Rock: given complete, the Lecture 20 activities (Part 1: read them)
  • Snowflake: you write it (Part 2)
  • Player.catches and Player.collect: you write them (Part 3)
  • show_balls() and play(): given, the loops that open a window

play() is the game loop from Lecture 20. Its # Part 2 and # Part 3 comments mark where you’ll add lines. Running the file runs play().

You’ll write methods only, and each one has a docstring that says exactly what it should do. As in Lecture 20, the logic lives in the methods, not in the loop, so you can test each method in the Shell without a window. Each time you run the file, the game opens: close its window, then type your tests in the Shell.

Part 1: Read the dodge game

Ball, Player, and Rock are complete: they are the classes you completed in the Lecture 20 activities, where you wrote Ball.update, Player.move, Rock.update, and Rock.get_rect. There is nothing to write in this part, but Parts 2 and 3 build on these classes, so read them with your partner. Spend 5 to 10 minutes on this part: the real work is in Parts 2 and 3.

  1. Watch them run. Run the file and play the dodge game until a rock hits you. Then close the window and type in the Shell:

    >>> show_balls()

    You should see 20 bouncing balls, each one a Ball object.

  2. Read the classes. Read Ball, Player, and Rock in lab6.py. If your day20_game.py from the Lecture 20 activities behaved differently, compare the four methods you wrote and find out why. If you haven’t done the Lecture 20 activities yet, read the classes alongside the Lecture 20 slides instead.

As you read, look for these:

  • Ball.update moves first, then checks the walls, and reverses a velocity with self.vx = -self.vx.
  • Player.move keeps the player on the screen with max and min: the smallest x allowed is 0 and the largest is SCREEN_WIDTH - PLAYER_SIZE.
  • Rock.__init__ sets self.radius and then calls self.reset(), so the random choices are written only once, in reset. update calls self.reset() again when the rock falls off the bottom.
  • A rock’s get_rect() is the square around its circle: its upper-left corner is (x - radius, y - radius).
  • In play(), the rocks are made before the loop, then updated, checked for a collision, and drawn in the loop. In Parts 2 and 3 you’ll add snowflakes in the same places.

Notice that a Player has a rect attribute, which move changes directly, while a Rock (and, in Part 2, a Snowflake) stores its center and radius and has a get_rect() method that builds a new pygame.Rect each time you call it.

Part 2: Snowflakes

A Snowflake is a lot like a Rock: it falls, and once it is below the bottom it starts again above the top. Start from Rock’s methods and change what’s different:

  • Each snowflake has a random size, so reset also picks a new radius, between FLAKE_MIN_RADIUS and FLAKE_MAX_RADIUS. Pick the radius first: the range for x depends on it.
  • Its speeds and color come from the FLAKE_ constants.
  • Later (Part 3), catching a snowflake also calls reset.

Write __init__, reset, and get_rect first, and test them in the Shell with the examples below. Then write update and draw, and add snowflakes to play(), at the three # Part 2 comments:

  1. Before the loop, make a list flakes of NUM_FLAKES snowflakes, the way rocks is made.
  2. In the loop, update each snowflake (next to the rocks).
  3. Draw each snowflake. Draw them before the rocks, so a rock passes in front of a flake.
>>> flake = Snowflake()
>>> flake.radius, flake.speed
(7, 2)
>>> flake.y < 0
True
>>> flake.y = 200
>>> flake.reset()
>>> flake.y < 0
True
>>> flake.x = 200
>>> flake.y = 150
>>> flake.radius = 7
>>> flake.get_rect()
Rect(193, 143, 14, 14)

Your first numbers will differ: they are random. The last test sets the position and radius first, so its answer is exact. Run the game: snow should fall, at different sizes and speeds, behind the rocks.

Part 3: Catching snowflakes

In play(), the loop checks whether a rock hits the player with player.rect.colliderect(rock.get_rect()). Catching a snowflake is the same check, but this time you’ll write it as a method, so it can be tested.

  1. Complete Player.catches(flake), which returns True if the player overlaps flake. It takes one line.
  2. Complete Player.collect(flakes). For each flake in the list that the player catches, it calls that flake’s reset method (so the flake starts falling again from above) and counts it. It returns the count. Call self.catches(flake) rather than repeating its code.
>>> p = Player(100, 100)
>>> flake = Snowflake()
>>> flake.x = 110
>>> flake.y = 110
>>> p.catches(flake)
True
>>> far = Snowflake()
>>> far.x = 400
>>> far.y = 300
>>> p.catches(far)
False
>>> p.collect([flake, far])
1
>>> flake.y < 0
True
>>> far.x, far.y
(400, 300)

Now keep score in play(), at the three # Part 3 comments:

  1. Before the loop, set score to 0.
  2. In the loop, after the for loop that updates the snowflakes (not inside it), add the number caught: score = score + player.collect(flakes).
  3. Draw the score in the upper-left corner with the two lines below.
text = font.render("Score: " + str(score), True, TEXT_COLOR)
screen.blit(text, (10, 10))

The first line makes an image of the text, and the second draws it at (10, 10).

Run the game and catch some snow.

  • Restart: press r to start over after “Game over”. Check for event.type == pygame.KEYDOWN and event.key == pygame.K_r in the event loop.
  • Lives: start with 3 lives and lose one per rock hit (reset that rock), with the lives drawn under the score.
  • Speed-up: every 10 snowflakes, make new rocks fall faster.
  • A real snowflake: in Snowflake.draw, draw three lines through the center with pygame.draw.line instead of a circle.

Submitting your work

When you are done, submit lab6.py to Gradescope.

Leave the last two lines of lab6.py as they are (if __name__ == "__main__": and play()), and keep your test calls in the Shell rather than in the file: Gradescope has no screen to open a window on.

Ensure that the upload succeeds and your submission passes all visible tests. The tests check your methods, not draw or play(): run the game to check those.