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, andRock: given complete, the Lecture 20 activities (Part 1: read them)Snowflake: you write it (Part 2)Player.catchesandPlayer.collect: you write them (Part 3)show_balls()andplay(): 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.
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
Ballobject.Read the classes. Read
Ball,Player, andRockinlab6.py. If yourday20_game.pyfrom 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.updatemoves first, then checks the walls, and reverses a velocity withself.vx = -self.vx.Player.movekeeps the player on the screen withmaxandmin: the smallestxallowed is0and the largest isSCREEN_WIDTH - PLAYER_SIZE.Rock.__init__setsself.radiusand then callsself.reset(), so the random choices are written only once, inreset.updatecallsself.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
resetalso picks a newradius, betweenFLAKE_MIN_RADIUSandFLAKE_MAX_RADIUS. Pick the radius first: the range forxdepends 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:
- Before the loop, make a list
flakesofNUM_FLAKESsnowflakes, the wayrocksis made. - In the loop, update each snowflake (next to the rocks).
- 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.
- Complete
Player.catches(flake), which returnsTrueif the player overlapsflake. It takes one line. - Complete
Player.collect(flakes). For each flake in the list that the player catches, it calls that flake’sresetmethod (so the flake starts falling again from above) and counts it. It returns the count. Callself.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:
- Before the loop, set
scoreto 0. - In the loop, after the
forloop that updates the snowflakes (not inside it), add the number caught:score = score + player.collect(flakes). - 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.
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.