a) [True, True, False, True, True, False]
b) False
c) [0, 0, 1, 0, 0, 1]
d) [-4, 2, 2, -2]
18. Which of the following lines of code will cause an error?
Use the following definition of ages:
ages = (12, 5, 8)
a) ages = ages + (1, 3, 5)
b) print ages[2]
c) ages = ages[2:]
d) ages[0] = 3
19. What does this code snippet print?
fruit = [“b”, “n”, “n”, “”]
print “a”.join(fruit)
a) bnn
b) ba na na
c) banana
d) abanana
20. What is the value of num after this code runs?
shapes = [“triangle”, “square”, “hexagon”, “circle”, “pentagon”]
num = len(shapes)
a) 0
b) 4
c) 5
d) 35
CHAPTER 4. PROGRAMMING 2D GAMES
4.1 PYGAME LIBRARY
You will:
Install PyGame library;
use the PyGame library to create a window for the game.
What does ‘library’ mean in the case of programming languages?
What is PyGame?
PyGame (the library) is a Free and Open Source python programming language library for making multimedia applications. Pygame is highly portable and runs on nearly every platform and operating system.
PyGame makes it simple to:
- Draw graphic shapes
- Display bitmapped images
- Animate
- Interact with keyboard, mouse, and gamepad
- Play sound
- Detect when objects collide
How to install Pygame library
The best way to install pygame is with the pip tool (which is what python uses to install packages). Note, this comes with python in recent versions. We use the --user fl ag to tell it to install into the home directory, rather than globally.
py -m pip install -U pygame --user
To see if it works, run one of the included examples
py -m pygame.examples.aliens
If it works, you are ready to go!
The first code a Pygame program needs to do is load and initialize the Pygame library. Every program that uses Pygame should start with Importing and initializing Pygame:
# Import a library of functions called ‘pygame’
import pygame
# Initialize all imported pygame modules
pygame.init()
Simple Pygame Window
pygame.display.set_mode(resolution=(width, height))
This function will create a display Surface. The resolution argument is a pair of numbers representing the width and height.
Keep in mind
Important:
Don’t name any file “pygame.py”
The import pygame looks for a library file named pygame. If a programmer creates a new program named pygame.py, the computer will import that file instead! This will prevent any pygame programs from working until that pygame.py file is deleted
Practice 1
Create a simple PyGame window of 600 pixels in height and 400 pixels in width and run. What did you notice?