Let's Learn Pygame: Exercises Saengthong School, June July 2016 Teacher: Aj. Andrew Davison CoE, PSU Hat Yai Campus E-mail: ad@fivedots.coe.psu.ac.th 1. Basics 1. What is a 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 in the program, and what does it do? clock.tick(20) a. The code is placed after the game loop and pauses 20 milliseconds. b. The code is placed 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. Which of these bits of code will open up a window 400 pixels high and 800 pixels wide? a. size = [800, 400] screen = pygame.display.set_mode(size) 1
b. size = [400, 800] screen = pygame.display.set_mode(size) c. size = 800,400 screen = pygame.display.set_mode(size) d. size = 400,800 screen = pygame.display.set_mode(size) e. screen = pygame.display.open_window(800, 400) f. screen = pygame.display.open_window(400, 800) 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? 2. Drawing 1. Explain how the Pygame coordinate system differs from the coordinate system used in maths (called the Cartesian coordinates system, https://en.wikipedia.org/wiki/cartesian_coordinate_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 [300, 50]? 5. If a box is drawn at (0,0), where will it be on the screen? a. Upper left b. Lower left c. Upper right d. Lower right e. Center 2
f. It won't display 6. If the screen width and height are both 400 pixels, and a rectangle is drawn 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 coordinate values 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 FOO = (255, 255, 255) represents a color. 12. Which of the following bits of code 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? offset = 0 while offset < 100: pygame.draw.line(screen, RED, [50+offset,20], [50+offset,60], 5) 3
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) What does screen do? What does [0, 0] do? What does [100, 100] do? What does 5 do? 15. What Pygame function can you use to draw lines joining many points together? 16. When drawing a rectangle, what happens if the line width is zero? 17. What Pygame function can you use to draw rectangles? 18. This code is supposed to draw a white rectangle. But when the program is run, no rectangle shows up. Why? import pygame # Define some colors 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() while not done: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.quit: done = True screen.fill(black) pygame.draw.rect(screen, WHITE, [50, 50, 50, 50]) pygame.quit() a. The rectangle dimensions are off-screen. b. There is no update function. 4
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 rectangle should be drawn earlier in the code. 19. This code is supposed to draw a white rectangle, but when the program is run, no rectangle shows up. However, when the user hits the close button, a rectangle briefly appears before the program closes. Why? import pygame 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() while not done: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.quit: done = True screen.fill(black) pygame.draw.rect(screen, WHITE, [50, 50, 50, 50]) pygame.display.update() pygame.quit() a. The rectangle dimensions are off-screen. 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 is the center of this ellipse? pygame.draw.ellipse(screen, BLACK, [1, 1, 3, 3], 1) a. (1, 1) b. (3, 3) c. (2, 2) 22. Describe the ellipse drawn in the code below. 5
pygame.draw.ellipse(screen, BLACK, [20, 20, 250, 100], 2) 23. When drawing an arc, what extra information is needed over drawing an ellipse? 24. What are the coordinates of the following polygon? pygame.draw.polygon(screen, BLACK, [[50,100],[0,200],[200,200],[100,50]], 5) 25. What are the three steps needed when printing text to the screen using graphics? 26. When drawing text, the first line of the three lines needed to draw text should be outside the game loop. It should only run once at the start of the program. Why? 27. What Pygame function is used to copy images to a surface (like the screen)? 28. Should the following line go inside, or outside, of the game loop? backgroundim = pygame.image.load("saturn_family1.jpg").convert() a. Outside the loop, because it isn t a good idea to load the image from the disk 20 times per second. b. Inside the loop, because the background image needs to be redrawn every frame. 29. In the following code, what does the [0, 0] do? screen.blit(backgroundim, [0, 0]) a. Sets the size of the image. b. Specifies the x and y of the top left coordinate of where to start drawing the bitmap on the screen. c. Draw the bitmap in the center of the screen. 30. Should the following line go inside or outside of the game loop? screen.blit(backgroundim, [0, 0]) a. Outside the loop, because it isn t a good idea to load the image from the disk 20 times per second. b. Inside the loop, because the background image needs to be redrawn every frame. 31. What types of image file formats are lossless (i.e., they do not change the image)? Choose the best answer. a. png, jpg, gif b. png, gif c. png d. jpg e. gif f. jpg, gif 32. This is about the time that many people learning to program run into problems with Windows hiding file extensions. Briefly explain how to make Windows show file extensions. 33. What does this code do? player_image.set_colorkey(white) a. Makes the bitmap background white. b. Sets all the white pixels to be transparent instead. c. Sets the next color to be drawn to white. d. Clears the screen to a white color. e. Draws the player image in white. 6
34. Should an image be loaded inside the game loop or before it? Should the program draw/blit the image in the game loop or before it? 35. How can a person change an image from one format to another? For example, how do you change a.jpg to a.gif? 3. Create-a-Picture Draw a single picture using Pygame functions, similar to one of the pictures below. To select new colors, either use http://www.colorpicker.com/ or open up the Windows Paint program and click on Edit Colors. Copy the values for Red, Green, and Blue. Please use comments and blank lines to make it easy to follow your program. 7
4. User Input 1. What is the event type that Pygame uses to detect keys being pressed? 2. In the move_keyboard.py example, if xstep and ystep were both set to 3, then: a. The object would be set to location (3, 3). b. The object would move down and to the right at 3 pixels per frame. c. The object would move down and to the right at 3 pixels per second. d. The object would move up and to the right at 3 pixels per second. e. The object would move up and to the left 3 pixels per frame. 3. What part of a MOUSEMOVE event tells you where the mouse is located? 4. What is the code to get only the x coordinate of the mouse. 5. Which of the following bits of code gets the x and y position of the mouse? a. pos = pygame.mouse.get_pos() x = pos[0] y = pos[1] 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() returns how many axes for a gamepad? a. 2 b. 4 c. One for each analog stick on the gamepad. d. Two for each analog stick on the gamepad. e. One for each button on the gamepad. 8. Depending on the button state, what value will button be assigned with this code? button = joystick.get_button( 0 ) a. 0 or 1 b. On or Off c. Up or Down 8
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 stick is all or nothing. c. An analog stick can be moved in small amounts; a hat is all or nothing. 10. What axis values will be returned when an analog stick is moved up and to the left? a. (-1, -1) b. (1, 1) c. (0, 0) 11. What axis values will be returned when an analog stick is centered? a. (-1, -1) b. (1, 1) c. (0, 0) 12. Why does movement with the keyboard or gamepad need to have a starting x, y location, but the mouse doesn t? 13. 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? def draw_stick_figure(screen, x, y): # Head pygame.draw.ellipse(screen, BLACK, [96,83,10,10], 0) # 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) 5.Create-a-Picture Control Write functions that draw two objects into your create-a-picture scene. For example, drawbird() and drawtree(). Do not draw a stick figure; we've done that already in Part 4. Control the movement of the each object in a different way, using either the keyboard, mouse, or gamepad Add checks so the objects cannot move off-screen. Explain your code in comments at the start of the program. 9
6. Animation 1. Which of these functions will draw a circle at the specified x and y locations? a. def draw_circle(screen, x, y): pygame.draw.ellipse(screen, WHITE, [x, y, 25, 25]) b. def draw_circle(screen,x,y): pygame.draw.ellipse(screen, WHITE, [x, y, 25 + x, 25 + y]) c. def draw_circle(screen, x, y): pygame.draw.ellipse(screen, WHITE, [0, 0, 25 + x, 25 + y]) 2. The following code draws an X as 2 lines. Would the code look like (a), (b), (c), (d), or (e) if it was moved into a function? The function is supplied with the coordinates where X should appear. pygame.draw.line(screen, RED, [80, 80], [100, 100], 2) pygame.draw.line(screen, RED, [80, 100], [100, 80], 2) a. def draw_x(screen, x, y): pygame.draw.line(screen, RED, [80, 80], [100, 100], 2) pygame.draw.line(screen, RED, [80, 100], [100, 80], 2) b. def draw_x(screen, x, y): pygame.draw.line(screen, RED, [80+x, 80+y], [100, 100], 2) pygame.draw.line(screen, RED, [80+x, 100+y], [100, 80], 2) c. def draw_x(screen, x, y): pygame.draw.line(screen, RED, [x, y], [20+x, 20+y], 2) pygame.draw.line(screen, RED, [x, 20+y], [20+x, y], 2) d. def draw_x(screen, x, y): pygame.draw.line(screen, RED, [x, y], [20, 20], 2) pygame.draw.line(screen, RED, [x, 20+y], [20, 0], 2) e. def draw_x(screen, x, y): pygame.draw.line(screen, RED, [80+x, 80+y], [100+x, 100+y], 2) pygame.draw.line(screen, RED, [80+x, 100+y], [100+x, 80+y], 2) 3. In beachbounce.py, if xstep is positive and ystep negative at the start, then which way will the ball begin travelling? a. Up b. Up and right c. Right d. Down and right e. Down f. Down and left g. Left h. Up and left 4. In beachbounce.py, if xstep is zero and ystep positive at the start, then which way will the ball begin travelling? 10
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 "Bouncing Rectangle" program has a problem -- the rectangle doesn't move. Why? import pygame 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() xstep = 5; ystep = 5 while not done: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.quit: done=true xrect = 50; yrect = 50 xrect += xstep yrect += ystep if yrect > 450 or yrect < 0: ystep = ystep * -1 if xrect > 650 or xrect < 0: xstep = xstep * -1 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. Change beachbounce.py to use a different image. The image must have a transparent background. 7. Change the xstep and ystep values in beachbounce.py to make the ball move faster or slower and in different directions. 8. Change beachbounce.py to make the ball bounce off an invisible wall or floor that is not the edge of the window. 11
9. beachbounce.py bounces the ball using four variables. What does each variable do? 10. If the screen is 400 pixels high, and a shape is 20 pixels high, then at what pixel position should the code check to see if the shape is touching the bottom of the screen. 11. Explain how to animate dozens of shapes at the same time. 12. Look at radar_sweep.py in the "5. Animation" folder. Explain how this program animates the line to move in a circle. 7. Create-a-Picture Animation Modify your Create-a-Picture program by animating one of the items in the scene. The item should either move in a smooth circle repeatedly, or if the item is a stick figure then he should wave his arms up and down repeatedly. If you choose to animate the stick figure, then base your code on the stick man from part "4. User Input". Explain your changes in comments at the start of the program. 8. Classes and Objects 1. Select the best class definition for an alien: a. class Alien(): def init (self): self.name = "" self.height = 7.2 self.weight = 156 b. class alien(): def init (self): self.name = "" self.height = 7.2 self.weight = 156 c. class alien.name = "" class alien.height = 7.2 class alien.weight = 156 d. class alien( def init (self): self.name = "" self.height = 7.2 self.weight = 156 ) 2. What does this code do? d1 = Dog() d2 = Dog() a. Creates two objects, of type Dog. b. Creates two classes, of type Dog. c. Creates one object, of type Dog. 12
3. What does this code do? d1 = Dog() d2 = d1 a. Creates two objects, of type Dog. b. Creates two classes, of type Dog. c. Creates one object, of type Dog. 4. What is wrong with the following code: class Book(): def open(self): print("you opened the book") def init (self): self.pages = 347 a. Book should not be capitalized. b. The init method should be first. c. open should be capitalized. 5. What will this code print? class Account(): def init (self): self.money = 0 def deposit(self, amount): self.money += amount 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 6. What is wrong with the following code: 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!") # This creates the dog my_dog = Dog("Rover") a. There should be a self. in front of new_name. b. There should be a self. in front of name. c. There's a problem with init. Say what it is. d. Some lines should be indented (say which ones). e. Some lines should not be indented (say which ones). 13
7. What is the difference between a class and an object? 8. What is the difference between a function and a method? 9. Write a main program to create an instance of this class and set its data: class Dog(): def init (self): self.age = 0 self.name = "" self.weight = 0 10. Write a main program to create two different instances of this class and set data for both objects: class Person(): def init (self): self.name = "" self.cell_phone = "" self.email = "" 11. For the code below, write a class that has the right name and data to allow the code to work. my_bird = Bird() my_bird.color = "green" my_bird.name = "Sunny" my_bird.breed = "Parrot" 12. The following code runs, but it is not correct. What is wrong? class Person(): def init (self): self.name = "" self.money = 0 nancy = Person() name = "Nancy" money = 100 13. This code does not run. What is the error? class Person(): def init (self): self.name = "" self.money = 0 bob = Person() print(bob.name, "has", money, "dollars.") 14. Even with that error fixed, the program will not print: Bob has 0 dollars. Instead it prints: has 0 dollars. Why? 14
9. Creating Animals To answer these questions, write one program. By the end it will contain three classes, called Animal, Cat, and Dog, and a main program. 1. Write a class called Animal: Add data for the animal name. Add an eat() method that prints Munch munch. Add a make_noise() method that prints Grrr says [animal name]. Add a constructor that prints An animal has been born. 2. A class called Cat: Make Animal its parent. Add a make_noise() method for Cat that prints Meow says [animal name]. Add a constructor for Cat that prints A cat has been born. The Cat constructor should call the parent constructor. 3. A class called Dog: Make Animal its parent. Add a make_noise() method for Dog that prints Bark says [animal name]. Add a constructor for Dog that prints A dog has been born. The Dog constructor should call the parent constructor. 4. The main program should: Create a cat, two dogs, and an animal. Set the name for each animal. Call eat() and make_noise() for each animal. 10. Sprites 1. What is a sprite? a. A graphic image that the computer can easily track, draw on the screen, and detect collisions with. b. A very bright color that glows. c. A function that draws images to the screen. d. Another name for fairy. 2. How can a programmer best use sprites? a. Derive a new class from pygame.sprite.sprite using inheritance. 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. 3. What is the usual way to draw sprites in a program? a. Add a sprite to a group. Then call draw(screen) on the group. b. Call the sprite s draw(screen) method. c. Call the sprite s update(screen) method. 15
d. Call the sprite s blit(screen) method. 4. How does a program move a sprite called mysprite? a. Set mysprite.rect.x and mysprite.rect.y. b. Set mysprite.x and mysprite.y. c. Call mysprite.draw(x,y) with x and y values. d. Call mysprite.move(x,y) with x and y values. 5. When a programmer writes a constructor for a sprite, what must be the first line? a. super(). init () b. self.image = pygame.surface([width, height]) c. self.image.set_colorkey(white) 6. If a programmer wants a sprite image to have a transparent background, what type of image should NOT be used? a. jpg b. png c. gif 7. What does True do in this line of code? sprites_hit_list = pygame.sprite.spritecollide(mysprite, spritelist, True) a. Kills mysprite if any sprite in spritelist is touching it. b. Creates an explosion effect when the sprites collide. c. Creates a sound effect when the sprites collide. d. Kills any sprite in spritelist that is touching mysprite. 8. What is special about a sprite s update() function? a. It is called automatically each time through the game loop. b. It is called automatically when the code calls update() on any group that sprite is in. c. There is nothing special about this function. 9. What is the function to add a sprite to a pygame.sprite.group called spritelist? a. spritelist.append(my_sprite) b. spritelist.add(my_sprite) c. spritelist.insert(my_sprite) 10. What is rect collision detection? 11. What is pixel-perfect collision detection, and how is it different from rect collision detection? 12. What are two ways to collect several sprite objects together? 11. Random Pong Change the Pong program so there s randomness to how the ball bounces. You could change the way the ball bounces off the paddle or the walls, make the speed random, or anything else you can think of. Explain your changes in comments at the start of the program. 16
12. Media 1. What is wrong with this 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() a. Pygame doesn't support.wav files. b. The colorkey hasn't been set for click_sound. c. Sounds should be loaded at the start of the program, not in the game loop. d. Sounds should not be played in a game loop. 2. For the following file extensions:.jpg.wav.gif.png.ogg.bmp.mp3 match each extension to the best category: Photos Graphic art Uncompressed images Songs and sound effects Uncompressed sounds 3. Briefly explain how to play background music in a game and how to automatically start playing a new song when the current one ends. 4. What are three types of files used for storing sound? 5. What Pygame module is used for playing music? 6. How do you set the volume for a Pygame sound object? 7. How do you set the volume for background music? 8. How do you make music fade out? 13. Pong Sounds Change the sounds and music used in the Pong game. There are some examples in the sounds/ folder in "09. Media", but you'll have more fun making your own! Use Sound Recorder in Windows, or Audacity (http://audacity.sourceforge.net/). Explain your changes in comments at the start of the program. 17
14. Modifying Invaders Change the Invaders game into something more fun and exciting. It's up to you how you change the program, but I'm looking for two visible changes to how the game plays. Students can work in groups, but the game must have 2 changes for each team member. For instance, a team of two students must have four visible changes. Here are some possible changes you could make, but you can make ANY changes you like: better start screen, with sounds or animation help/instructions screen with pause/resume feature different images, sounds, music all this counts as one thing since it's easy more complex alien movement more complex player movement more complex wall destruction and recreation new game thing, coded as a sprite e.g. super-killer-alien high scores screen for players that is remembered between games this is hard, so counts as TWO changes multiple levels this is hard, so counts as TWO changes For ideas, look at Part 11, "Skier" and at the many games in Part 13 "More Games" If you are not sure if your code counts as one or two changes, then ask me. Explain your changes in comments at the start of the program. If you are in a team, clearly explain who did what coding. 18