142-253 Computer Programming: Pygame Exercises: Clock Pygame - Time.clock
142-253 Computer Programming: Pygame Exercises: Clock Pygame - Time.clock
Basics
1. What is the game loop?
a. It processes user input, updates objects, and draws the screen in each frame of the
game.
b. It runs once for the entire game.
c. It loops once for each life that the player has.
d. It loops once for each level of the game.
2. Where does this code go?
clock = pygame.time.Clock()
a. The code is placed after the game loop.
b. The code is placed inside the game loop.
c. This code is placed before the game loop.
3. Where does this code go, and what does it do?
clock.tick(20)
a. The code is place after the game loop and pauses 20 milliseconds.
b. The code is place after the game loop and limits the game to 20 frames per second.
c. The code is placed inside the game loop and limits the game to 20 frames per second.
d. This code is placed before the game loop and limits the game to 20 frames per second.
e. The code is placed inside the game loop and pauses 20 milliseconds.
4. Changing the tick value from 20 to 30 will cause what to happen?
clock.tick(20)
a. Nothing.
b. The game will run faster.
c. The game will run slower.
5. What does this code do?
pygame.display.update()
a. Nothing.
b. Clears the screen.
c. Displays everything that has been drawn so far.
d. Flips the screen from left to right.
e. Flips the screen from top to bottom.
6. What code will open up a window 400 pixels high and 800 pixels wide?
Pygame Exercises
c. size = 800,400
screen = pygame.display.set_mode(size)
d. size = 400,800
screen = pygame.display.set_mode(size)
7. Before a Pygame program can use any functions like pygame.display.set_mode(), what
must be done first?
8. What does the pygame.display.set_mode() function do?
9. What is pygame.time.Clock used for?
10. What does pygame.display.update() do?
11. What does pygame.quit() do?
Drawing
1. Explain how the Pygame coordinate system differs from the coordinate system used in
maths (called the Cartesian system).
2. What does pixel mean?
3. If a Pygame window is 600 pixels wide by 400 pixels high, what letter in the diagram
below is at [50, 200]?
4. What letter in the diagram is at location [300, 50]?
5. If a box is drawn starting at (x,y) coordinate (0,0), where will it be on the screen?
a. Upper left
b. Lower left
c. Upper right
2
Pygame Exercises
d. Lower right
e. Center
f. It won't display
6. If the screen width and height are both 400 pixels, and a rectangle is drawn starting at
(0,400), where will it display?
a. Upper left
b. Lower left
c. Upper right
d. Lower right
e. Center
f. It won't display
7. In Pygame, as x and y coordinates increase, a point will move:
a. Down and to the right
b. Up and to the right
c. Down and to the left
d. Up and to the left
e. Nowhere
8. What color is defined by (0, 0, 0)?
a. Black
b. Red
c. Green
d. Blue
e. White
9 What color is defined by (0, 255, 0)?
a. Black
b. Red
c. Green
d. Blue
e. White
10. What color is defined by (255, 255, 255)?
a. Black
b. Red
c. Green
d. Blue
e. White
11. Explain how WHITE = (255, 255, 255) represents a color.
12. Which of the following will draw a line from (0, 0) to (100, 100)?
a. pygame.draw.line(screen, GREEN, [0,0,100,100], 5)
b. pygame.draw.line(screen, GREEN, 0, 0, 100, 100, 5)
c. pygame.draw.line(screen, GREEN, [0, 0], [100, 100], 5)
d. pygame.draw.line(GREEN, screen, 0, 0, 100, 100, 5)
e. pygame.draw.line(5, GREEN, [0, 0], [100, 100], screen)
13. What will this code draw?
3
Pygame Exercises
offset = 0
while offset < 100:
pygame.draw.line(screen, RED, [50+offset,20], [50+offset,60], 5)
offset = offset + 10
a. Ten vertical lines, 10 pixels apart, with a starting x coordinate of 50 and an ending
coordinate of 140.
b. Ten horizontal lines, 10 pixels part, with a starting y coordinate of 50 and an ending
coordinate of 150.
c. Ten vertical lines, 5 pixels apart, with a starting x coordinate of 50 and an ending
coordinate of 100.
d. Ten vertical lines, 10 pixels apart, with a starting x coordinate of 10 and an ending
coordinate of 110.
e. Ten vertical lines, 5 pixels apart, with a starting x coordinate of 10 and an ending
coordinate of 150.
f. Ten lines, all drawn on top of each other.
14. For this line of code:
pygame.draw.line(screen, GREEN, [0, 0], [100, 100], 5)
pygame.init()
size = [700, 500]
screen = pygame.display.set_mode(size)
done = False
clock = pygame.time.Clock()
screen.fill(BLACK)
pygame.draw.rect(screen, WHITE, [50, 50, 50, 50])
pygame.quit()
4
Pygame Exercises
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
pygame.init()
size = [700, 500]
screen = pygame.display.set_mode(size)
done = False
clock = pygame.time.Clock()
screen.fill(BLACK)
pygame.draw.rect(screen, WHITE, [50, 50, 50, 50])
pygame.display.update()
pygame.quit()
a. The rectangle dimensions are offscreen.
b. The update is unindented and doesn’t show until after the program ends.
c. The rectangle is the same color as the background.
d. The rectangle is drawn outside the game loop.
e. The rectangle is too small to see.
f. The update should be done before the rectangle is drawn.
20. How wide will this ellipse be?
pygame.draw.ellipse(screen, BLACK, [0, 0, 100, 100], 2)
a. 100 pixels
b. 99 pixels
c. 101 pixels
d. 50 pixels
e. 49 pixels
21. Where will the center of this ellipse be?
pygame.draw.ellipse(screen, BLACK, [1, 1, 3, 3], 1)
a. (1, 1)
b. (3, 3)
c. (2, 2)
5
Pygame Exercises
6
Pygame Exercises
Create-a-Picture
Draw a single picture using Pygame functions, similar to the one of the pictures below.
User Input
1. What is the name of the event type that Pygame uses to detect keys being pressed?
2. In the keyboard example, if xStep and yStep were both set to 3, then:
7
Pygame Exercises
b. pos = pygame.mouse.get_pos()
x = pos[x]
y = pos[y]
c. pos = pygame.mouse.get_pos()
x = pos(x)
y = pos(y)
d. x = pygame.mouse.get_pos(x)
y = pygame.mouse.get_pos(y)
e. x = pygame.mouse.get_pos(0)
y = pygame.mouse.get_pos(1)
6. Given this line of code, what code will get the x value of the current mouse position?
player_position = pygame.mouse.get_pos()
a. x = player_position[x]
b. x = player_position[0]
c. x = player_position.x
d. x[0] = player_position
7. The call axes = joystick.get_numaxes() will return how many axes for a gamepad?
a. 2
b. 4
c. One for each analog joystick on the gamepad.
d. Two for each analog joystick on the gamepad.
e. One for each button on the gamepad.
8. Depending on the button state, what value will the variable button be assigned using this
code?
button = joystick.get_button( 0 )
a. 0 or 1
b. On or Off
c. Up or Down
d. True or False
9. What is the difference between a gamepad hat and an analog stick?
a. Nothing, they are just different names for the same thing.
b. A hat can be moved in small amounts; an analog joystick is all or nothing.
8
Pygame Exercises
c. xCoord = my_joystick.get_axis(0)
yCoord = my_joystick.get_axis(1)
d. xCoord = my_joystick.get_axis(0)*10
yCoord = my_joystick.get_axis(1)*10
13. Why does movement with the keyboard or gamepad need to have a starting x, y location,
but the mouse doesn’t?
14. What is wrong with this code that draws a stick figure? Assume the colors are already
defined and the rest of the program is OK. What is wrong with the code in the function?
# Legs
pygame.draw.line(screen, BLACK, [100,100], [105,110], 2)
pygame.draw.line(screen, BLACK, [100,100], [95,110], 2)
# Body
pygame.draw.line(screen, RED, [100,100], [100,90], 2)
# Arms
pygame.draw.line(screen, RED, [100,90], [104,100], 2)
pygame.draw.line(screen, RED, [100,90], [96,100], 2)
Create-a-Picture Control
Write at least two functions that draw objects onto your create-a-picture scene. For example,
drawBird() and drawTree(). Do not draw a stick figure; we've done that already.
9
Pygame Exercises
Control the movement of the objects in two different ways, using the keyboard, mouse, or
gamepad
Make sure to add checks so that your objects cannot move offscreen.
Animation
10. What are the two main steps when you’re “moving” or animating an image?
2. Change one of the sample programs that uses the beach ball image to use a different image.
3. Change the xStep and yStep values in the sample program to make the ball move faster or
slower and in different directions.
4. Change the sample program to make the ball “bounce” off an invisible wall or floor that
isn’t the edge of the window.
5. In the modern art, sine wave, and picture programs, move the pygame.display.update() line
inside the while loop. To do that, just indent it four spaces. After that line, and also inside the
while loop, add a delay with this line and see what happens: pygame.time.delay(30)
1. In the bouncing rectangle program, if xStep is positive and yStep is negative, which way
will the rectangle travel?
a. Up
b. Up and right
c. Right
d. Down and right
e. Down
f. Down and left
g. Left
h. Up and left
2. In the bouncing rectangle program, if xStep is zero and yStep is positive, which way will
the rectangle travel?
a. Up
b. Up and right
c. Right
d. Down and right
e. Down
f. Down and left
g. Left
h. Up and left
5. This version of “The Bouncing Rectangle” doesn’t work. The rectangle won’t move.
Why?
import pygame
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
pygame.init()
size = [700, 500]
screen = pygame.display.set_mode(size)
10
Pygame Exercises
done = False
clock = pygame.time.Clock()
xStep = 5
yStep = 5
screen.fill(BLACK)
pygame.draw.rect(screen, WHITE, [xRect, yRect, 50, 50])
pygame.display.update()
pygame.quit ()
a. pygame.draw.rect doesn’t change where the rectangle is drawn based on the variables.
b. xRect and yRect are reset to 50 each time through the loop.
c. The 50,50 in the draw command also needs to be changed to xRect,yRect
d. The lines to adjust xRect and yRect need to be outside the while loop.
6. What is the correct code to make the rectangle bounce of the left and right sides of the
screen?
a. if xRect > 450 or xRect < 0:
xRect = xRect * -1
b. if xRect > 450 or xRect < 0:
xStep = xStep * -1
c. if yRect > 450 or yRect < 0:
yRect = yRect * -1
d. if yRect > 450 or yRect < 0:
yStep = yStep * -1
7. Why does this code not work for drawing stars?
for i in range(50):
x = random.randrange(0,400)
y = random.randrange(0,400)
pygame.draw.circle(screen, WHITE, [x, y], 2)
a. The stars are drawn offscreen.
b. The variable i should be used when drawing stars.
11
Pygame Exercises
12
Pygame Exercises
b. def draw_circle(screen,x,y):
pygame.draw.ellipse(screen, WHITE, [x, y, 25 + x, 25 + y])
Create-a-Picture Animation
Modify the prior Create-a-Picture exercise, or start a new one. Animate the image. Try one or
more of the following:
Move an item across the screen.
Move an item back and forth.
13
Pygame Exercises
Move up/down/diagonally.
Move in circles.
Have a person wave their arms.
Create a stoplight that changes colors.
Remember, the more flair the better! Have fun with this exercise, and take time to see what
you can do.
b. class alien():
def __init__(self):
self.name = ""
self.height = 7.2
self.weight = 156
d. class alien(
def __init__(self):
self.name = ""
self.height = 7.2
self.weight = 156
)
14
Pygame Exercises
def __init__(self):
self.pages = 347
account = Account()
money = 100
account.deposit(50)
print(money, account.money)
a. 150 150
b. 100 50
c. 100 100
d. 50 100
e. 50 50
f. 100 150
10. What is wrong with the following:
class Dog():
def __init__(self, new_name):
""" Constructor.
Called when creating an object of this type """
name = new_name
print("A new dog is born!")
15
Pygame Exercises
nancy = Person()
name = "Nancy"
money = 100
8. Take a look at the code. It does not run. What is the error that prevents it from running?
class Person():
def __init__(self):
self.name = ""
self.money = 0
bob = Person()
print(bob.name, "has", money, "dollars.")
9. Even with that error fixed, the program will not print out:
Bob has 0 dollars.
Instead it just prints out:
has 0 dollars.
Why is this the case?
Animals Classes
16
Pygame Exercises
To answer the next four questions, create one program. In that program will be the answers
for all four questions. Make sure the program runs, and then copy/paste from the program to
answer each of the questions below.
You should have a program that starts with three class definitions, one each for the first three
questions.
Then you should have code that will create instances of each class, and that will be the
answer to the last problem.
1. Write code that defines a class named Animal:
Add an attribute for the animal name.
Add an eat() method for Animal that prints “Munch munch.”
A make_noise() method for Animal that prints “Grrr says [animal name].”
Add a constructor for the Animal class that prints “An animal has been born.”
2. A class named Cat:
Make Animal the parent.
A make_noise() method for Cat that prints “Meow says [animal name].”
A constructor for Cat that prints “A cat has been born.”
Modify the constructor so it calls the parent constructor as well.
3. A class named Dog:
Make Animal the parent.
A make_noise() method for Dog that prints “Bark says [animal name].”
A constructor for Dog that prints “A dog has been born.”
Modify the constructor so it calls the parent constructor as well.
4. A main program with:
Code that creates a cat, two dogs, and an animal.
Sets the name for each animal.
Code that calls eat() and make_noise() for each animal. (Don’t forget this!)
Sprites
1. What is a Sprite?
a. A graphic image that he computer can easily track, draw on the screen, and detect
collisions with.
b. A very bright color that seems to glow.
c. A function that draws images to the screen.
d. A sprite is to Tinkerbell as a human is to Bob.
2. Which option best describes how a programmer use sprites in his or her program?
a. Derive a new class from pygame.sprite.Sprite, and then create instances of those
sprites and add them to sprite groups.
b. Create instances of pygame.sprite.Sprite and add them to sprite groups.
c. Use functions to draw images directly to the screen
d. Use bitmaps and blit images to the screen.
17
Pygame Exercises
b.
c.
d.
1. What is rect collision detection?
2. What is pixel-perfect collision detection, and how is it different from rect collision
detection?
3. What are two ways to keep track of a number of sprite objects together?
4. What are two ways to control the speed of animation in your code?
6. How can you tell what frame rate your program is running at?
Pong
5. What is wrong with the following code:
class Ball():
def __init__(self):
self.x = 0
self.y = 0
self.change_x = 0
self.change_y = 0
x += change_x
y += change_y
Ball.x = 50
Ball.y = 100
19
Pygame Exercises
self.x = 0
self.y = 0
b = Ball()
b.x = 50
b.y = 100
b1 = Ball()
b2 = b1
b1.x = 40
b2.x = 50
b1.x += 5
b2.x += 5
print(b1.x, b2.x)
a. 40 40
b. 60 60
c. 45 55
d. 55 55
e. 40 50
1. Did you notice anything strange that happens when the ball hits the side of the paddle
instead of the top? It kind of bounces along through the middle of the paddle for a while. Can
you figure out why? Can you fix it? Give it a try before looking at my solution in the answer
section.
2. Try rewriting the program (either listing 18.4 or 18.5) so that there’s some randomness to
the ball’s bounces. You might change the way the ball bounces off the paddle or the walls,
make the speed random, or something else you can think of. (You saw random.randint() and
random.random() in chapter 15, so you know how to generate random numbers, both integers
and floats.)
Media
7. What is wrong with section of code?
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
if event.type == pygame.MOUSEBUTTONDOWN:
click_sound = pygame.mixer.Sound("click.wav")
click_sound.play()
20
Pygame Exercises
Skier
21
Pygame Exercises
1. Try modifying Skier so that it gets harder as the game goes on. Here are some suggestions
for things to try:
Make the speed increase as the game goes on.
Add more trees farther down the hill.
Add “ice,” which makes turning more difficult.
2. The SkiFree program that was the inspiration for Skier had an Abominable Snowman that
randomly appeared and chased the skier. If you’re up for a real challenge, try adding
something like that to the Skier program. You’ll have to find or create a new sprite image and
figure out how to modify the code to get the behavior you want.
Video Game
This final exercise is divided into three parts. Each part raises the bar on what your game
needs to be able to do.
Part 1:
Open up a screen.
Set up the items to be drawn on the screen.
Provide some sort of rudimentary player movement via mouse, keyboard, or gamepad.
Tips:
If your program will involve things running into each other, start by using sprites. Do not
start by using drawing commands and expect to add in sprites later. It won’t work and
you’ll need to start over from scratch. This will be sad.
If you are coding a program like minesweeper or connect four, do not use sprites. Since
collision detection is not needed, there is no need to mess with sprites.
Under “longer game examples” I have two programs that show how to create pong or
breakout style games. Don’t just turn these in as Part 1 though; you’ll need to add a lot
before it really qualifies.
http://OpenGameArt.org has a lot of images and sounds you can use royalty-free.
http://Kenney.nl has many images and sounds as well.
Part 2:
For Final Exercise Part 2, your game should be mostly functional. A person should be able to
sit down and play the game for a few minutes and have it feel like a real game. Here are some
things you might want to add:
Be able to collide with objects.
Players can lose the game if something bad happens.
Onscreen score.
Some initial sound effects.
Movement of other characters in the screen.
The ability to click on mines or empty spots.
22
Pygame Exercises
Part 3:
For the final part, add in the last polish for your game. Here are some things you might want
to add:
Multiple levels
Sounds
Multiple “lives”
Title and instruction screens
Background music
Heat-seeking missiles
Hidden doors
A “sweep” action in a minesweeper game or the ability to place “flags”
23