Graphics - Informatics: Indiana

Guide to Programming with
Python
Chapter Eleven
Graphics: The Pizza Panic Game
Objectives
•
•
•
•
•
•
Create a graphics window
Create and manipulate sprites
Display text in a graphics window
Test for collisions between sprites
Handle mouse input
Control a computer opponent
Guide to Programming with Python
2
The Pizza Panic Game
Figure 11.1: Sample run of the Pizza Panic game
The player must catch the falling pizzas.
Guide to Programming with Python
3
The Pizza Panic Game (continued)
Figure 11.2: Sample run of the Pizza Panic game
Once the player misses a pizza, the game is over.
Guide to Programming with Python
pizza_panic.py
4
The pygame and livewires Packages
• Package: Set of modules
• pygame module
– Provides access to wide range of multimedia classes
– Made especially for writing games
• livewires
module
– Built on top of pygame, easier to use
– Used for all graphics games in textbook
Guide to Programming with Python
5
Creating a Graphics Window
• Graphics window
– Must create as first step in graphics program
– All images and text displayed on it
Guide to Programming with Python
6
The New Graphics Window Program
Figure 11.3: Sample run of the New Graphics Window program
A first graphics window. Not much, but it’s a start.
Guide to Programming with Python
7
The New Graphics Window Program
(continued)
from livewires import games
games.init(screen_width = 640, screen_height = 480,
fps = 50)
games.screen.mainloop()
(screen_width is really window width
screen_height is really window height)
Guide to Programming with Python
8
Importing the games Module
from livewires import games
statement lets you import specific module from
a package
livewires package made up of several important
modules, including games
games contains classes and functions for game
programming
• from
•
•
new_graphics_window.py
Guide to Programming with Python
9
games Module Objects
Table 11.1: Useful games module objects
Guide to Programming with Python
10
games Module Classes
Table 11.2: Useful games module classes
Guide to Programming with Python
11
Initializing a Graphics Window
games.init(screen_width = 640, screen_height = 480,
fps = 50)
• games init()
creates a new graphics window
– screen_width for screen (window) width
– screen_height for screen (window) height
– Screen dimensions measured in pixels
– Pixel: single point on graphics screen
– fps (frames per second) for number of times screen
updated each second
• Here, window width 640, height 480, updated 50
times per second
Guide to Programming with Python
12
Starting the Main Loop
games.screen.mainloop()
• screen
represents the graphics screen
• screen.mainloop()
– Updates graphics screen fps times per second
– Keeps the graphics window open
Guide to Programming with Python
13
Useful screen Properties
Can get and set these properties with game.screen.<property>
Table 11.3: Useful screen properties
Guide to Programming with Python
14
Useful screen Methods
Table 11.4: Useful screen methods
Guide to Programming with Python
15
Setting a Background Image
• Background image
– Generally want one
– Example: Brick wall image in Pizza Panic game
Guide to Programming with Python
16
The Background Image Program
Figure 11.4: Sample run of the Background Image program;
background property of screen used to set background.
Guide to Programming with Python
17
The Background Image Program
(continued)
from livewires import games
games.init(screen_width = 640, screen_height = 480,
fps = 50)
wall_image = games.load_image("wall.jpg",
transparent = False)
games.screen.background = wall_image
games.screen.mainloop()
Guide to Programming with Python
18
Loading an Image
wall_image = games.load_image("wall.jpg",
transparent = False)
• load_image()
function
– Loads and returns image object
– Works with JPG, BMP, GIF, PNG, PCX, and TGA
files
– Takes two arguments
• String for file name of the image
• True or False for transparent (use False for
background image)
• Here, wall_image set to image stored in wall.jpg
Guide to Programming with Python
19
Setting the Background
games.screen.background = wall_image
• background
property
– Represents background of graphics screen
– Can be assigned an image object
• Here, screen background is set to wall_image
background_image.py
Guide to Programming with Python
20
Understanding the Graphics
Coordinate System
• Graphics screen made up of rows and columns of
pixels
• Specify point on screen with coordinates: x and y
– x represents column
– y represents row
– Upper-leftmost pixel is (0,0)
• Can place graphics objects anywhere on screen
using this coordinate system
Guide to Programming with Python
21
Understanding the Graphics
Coordinate System (continued)
Figure 11.5: Graphics coordinate system
Specify points on graphics screen with x- and y-coordinate pairs.
Guide to Programming with Python
22
Displaying a Sprite
• Sprite: A graphics object with an image
• Example: The chef, pizzas, and pan in the Pizza
Panic game
Guide to Programming with Python
23
The Pizza Sprite Program
Figure 11.6: Sample run of the Pizza Sprite program
The pizza image is not part of the background, but a sprite.
Guide to Programming with Python
24
The Pizza Sprite Program (continued)
from livewires import games
games.init(screen_width = 640, screen_height = 480,
fps = 50)
wall_image = games.load_image("wall.jpg",
transparent = False)
games.screen.background = wall_image
pizza_image = games.load_image("pizza.bmp")
pizza = games.Sprite(image = pizza_image,
x = 320, y = 240)
games.screen.add(pizza)
games.screen.mainloop()
Guide to Programming with Python
25
Loading an Image for a Sprite
pizza_image = games.load_image("pizza.bmp")
• In load_image(), default value for transparent is True
• transparent set to True allows background to show
through transparent parts of image
• Color of pixel at the upper-left corner of image is its
transparent color
Guide to Programming with Python
26
Loading an Image for a Sprite
(continued)
• All parts of image that are its transparent color
allow background to show through
• Here, pizza_image set to image stored in
pizza.bmp with transparency
Guide to Programming with Python
27
Loading an Image for a Sprite
(continued)
Figure 11.7: Swiss cheese image
On solid background to take advantage of transparency.
Guide to Programming with Python
28
Loading an Image for a Sprite
(continued)
Figure 11.8: Swiss cheese image loaded two ways
On left, transparent True; on right, transparent False.
Guide to Programming with Python
29
Creating a Sprite
pizza = games.Sprite(image = pizza_image,
x = 320, y = 240)
• Sprite
is class for sprite
– image is for image
– x is for x-coordinate
– y is for y-coordinate
• Here, pizza gets Sprite object with pizza image at
(320,240) – center of screen
Guide to Programming with Python
30
Adding a Sprite to the Screen
games.screen.add(pizza)
• Sprite must be added to screen to be displayed
• screen.add() adds sprite to screen
• Here, pizza is added to screen
Guide to Programming with Python
31
Useful Sprite Properties
Table 11.5: Useful Sprite properties
Guide to Programming with Python
32
Useful Sprite Methods
pizza_sprite.py
Table 11.6: Useful Sprite methods
Guide to Programming with Python
33
Displaying Text
• Can display text on screen
• Example: The player’s score in the Pizza Panic
game
Guide to Programming with Python
34
The Big Score Program
Figure 11.9: Sample run of the Big Score program
The score is displayed after a Text object is instantiated.
Guide to Programming with Python
35
Importing the color Module
from livewires import games, color
• color
–
–
–
–
Module in livewires package
Defines set of constants for colors
Constants can be used with Text objects
Example: color.black
Guide to Programming with Python
36
Creating a Text Object
score = games.Text(value = 1756521, size = 60,
color = color.black, x = 550, y = 30)
• Text
is class for text on graphics screen
– value is for value to be displayed as text
– size is for height in pixels
– color is for color
• Here, score gets Text object displayed as 1756521,
60 pixels high in black at (550,30)
Guide to Programming with Python
37
Adding a Text Object to the Screen
games.screen.add(score)
object must be added to screen to be
displayed
• Here, score is added to the screen
• Text
Guide to Programming with Python
38
Useful Text Properties
big_score.py
Table 11.7: Additional Text properties
Guide to Programming with Python
39
Displaying a Message
• Message is temporary text, disappears after set
period of time
• Example: “Game Over!” in the Pizza Panic game
Guide to Programming with Python
40
The You Won Program
Figure 11.10: Sample run of the You Won program
The message disappears after a few seconds.
Guide to Programming with Python
41
Importing the color Module
from livewires import games, color
• color
– Constants can be used with Message objects
Guide to Programming with Python
42
Creating a Message Object
won_message = games.Message(
value = "You won!",
size = 100,
color = color.red,
x = games.screen.width/2,
y = games.screen.height/2,
lifetime = 250,
after_death = games.screen.quit)
Guide to Programming with Python
43
Creating a Message Object (continued)
• Message
is class for message on graphics screen
– lifetime is for number of mainloop() cycles
message lives (fps * seconds)
– after_death is for function to be called just before
object disappears (default value None)
• Here, message “You Won!” appears in big, red
letters at the center of screen for about five
seconds, then program ends
Guide to Programming with Python
44
Using the Screen’s Width and Height
• screen.width
property represents width of graphics
screen
property represents height of
graphics screen
• Sometimes clearer to use screen.width and
screen.height rather than literal integers
• screen.height
is
middle of screen regardless of screen dimensions
• (games.screen.width/2, games.screen.height/2)
Guide to Programming with Python
45
Adding a Message Object to the
Screen
games.screen.add(won_message)
object must be added to screen to be
displayed
• Here, won_message is added to the screen
• Message
Guide to Programming with Python
46
Adding a Message Object to the
Screen (continued)
you_won.py
Table 11.8: Additional Message attributes
Guide to Programming with Python
47
Moving Sprites
• Moving images essence of most games
• Sprites have properties for movement
Guide to Programming with Python
48
The Moving Pizza Program
Figure 11.11: Sample run of the Moving Pizza Program
Pizza moves in direction of arrow.
Guide to Programming with Python
49
Setting a Sprite’s Velocity Values
the_pizza = games.Sprite(
image = pizza_image,
x = games.screen.width/2,
y = games.screen.height/2,
dx = 1,
dy = 1)
Guide to Programming with Python
50
Setting a Sprite’s Velocity Values
(continued)
• dx
– "delta" x (change in x)
– Value added to x each mainloop() cycle
– Default value is 0
• dy
– "delta" y (change in y)
– Value added to y each mainloop() cycle
– Default value is 0
moving_pizza.py
Guide to Programming with Python
51
Dealing with Screen Boundaries
• Create mechanism to deal with the graphics
window’s boundaries for moving sprites
• Some options for sprite reaching screen edge
– Explode
– Bounce
– Wrap around
Guide to Programming with Python
52
The Bouncing Pizza Program
Figure 11.12: Sample run of the Bouncing Pizza program
Pizza bounces around, following path of arrow.
Guide to Programming with Python
53
Setting Up the Program
from livewires import games
games.init(screen_width = 640, screen_height = 480,
fps = 50)
Guide to Programming with Python
54
Deriving a New Class from Sprite
class Pizza(games.Sprite):
""" A bouncing pizza. """
def update(self):
""" Reverse a velocity component if edge of screen
reached. """
if self.right > games.screen.width or self.left < 0:
self.dx = -self.dx
if self.bottom > games.screen.height or self.top < 0:
self.dy = -self.dy
Guide to Programming with Python
55
Overriding the update() Method
• Sprite.update()
– Called for each Sprite object every mainloop()
cycle
– Provides opportunity for object to do something
• Pizza.update()
– Overrides Sprite.update(), which does nothing
– Checks if object is about to go beyond screen limits;
if so, reverses the responsible velocity
– Causes pizza to "bounce" off screen edges
Guide to Programming with Python
56
Wrapping Up the Program
def main():
wall_image = games.load_image("wall.jpg",
transparent = False)
games.screen.background = wall_image
pizza_image = games.load_image("pizza.bmp")
the_pizza = Pizza(image = pizza_image,
x = games.screen.width/2,
y = games.screen.height/2,
dx = 1,
dy = 1)
games.screen.add(the_pizza)
games.screen.mainloop()
# kick it off!
main()
Guide to Programming with Python
bouncing_pizza.py
57
Handling Mouse Input
• Interactivity is key ingredient in games
• Can check mouse position for player input
Guide to Programming with Python
58
The Moving Pan Program
Figure 11.13: Sample run of the Moving Pan program
Pan sprite follows mouse around graphics screen.
Guide to Programming with Python
59
Setting Up the Program
from livewires import games
games.init(screen_width = 640, screen_height = 480,
fps = 50)
Guide to Programming with Python
60
Reading Mouse X- and Y-Coordinates
class Pan(games.Sprite):
"""" A pan controlled by the mouse. """
def update(self):
""" Move to mouse coordinates. """
self.x = games.mouse.x
self.y = games.mouse.y
• mouse
– games object
– Represents mouse pointer
– x property for its x-coordinate
– y property for its y-coordinate
Guide to Programming with Python
61
Reading Mouse X- and Y-Coordinates
(continued)
def main():
wall_image = games.load_image("wall.jpg",
transparent = False)
games.screen.background = wall_image
pan_image = games.load_image("pan.bmp")
the_pan = Pan(image = pan_image,
x = games.mouse.x,
y = games.mouse.y)
games.screen.add(the_pan)
• Pan
object starts off at mouse coordinates
Guide to Programming with Python
62
Setting Mouse Pointer Visibility
games.mouse.is_visible = False
• is_visible
– Property determines if mouse pointer displayed
– Set to True, mouse pointer displayed
– Set to False, mouse pointer not displayed
Guide to Programming with Python
63
Grabbing Input to the Graphics
Window
games.screen.event_grab = True
• event_grab
– Property determines if input focused to screen
– Set to True, input focused to screen (mouse pointer
won't leave screen)
– Set to False, input not focused to screen (mouse
pointer can leave screen)
Guide to Programming with Python
64
Wrapping Up the Program
games.screen.mainloop()
# kick it off!
main()
Guide to Programming with Python
65
Wrapping Up the Program (continued)
moving_pan.py
Table 11.9: Useful Mouse properties
Guide to Programming with Python
66
Detecting Collisions
• Collisions play role in almost all games
• Can detect collisions between sprites
Guide to Programming with Python
67
The Slippery Pizza Program
Figure 11.14: Sample run of the Slippery Pizza program
The player almost reaches the pizza.
Guide to Programming with Python
68
The Slippery Pizza Program
(continued)
Figure 11.15: Sample run of the Slippery Pizza program
The slippery pizza gets away again.
Guide to Programming with Python
69
Setting Up the Program
from livewires import games
import random
games.init(screen_width = 640, screen_height = 480,
fps = 50)
Guide to Programming with Python
70
Detecting Collisions
class Pan(games.Sprite):
"""" A pan controlled by the mouse. """
def update(self):
""" Move to mouse position. """
self.x = games.mouse.x
self.y = games.mouse.y
self.check_collide()
def check_collide(self):
""" Check for collision with pizza. """
for pizza in self.overlapping_sprites:
pizza.handle_collide()
Guide to Programming with Python
71
Detecting Collisions (continued)
• overlapping_sprites
– Sprite property
– List of all of the sprites that overlap given sprite
invokes check_collide()
• check_collide() loops through Pan object’s
overlapping_sprites property
• Each object that overlaps Pan object has its
handle_collide() method called
• update()
Guide to Programming with Python
72
Handling Collisions
class Pizza(games.Sprite):
"""" A slippery pizza. """
def handle_collide(self):
""" Move to a random screen location. """
self.x = random.randrange(games.screen.width)
self.y = random.randrange(games.screen.height)
• handle_collide()
moves Pizza object to random
location
• So, every time the pan hits a pizza, the pizza jumps to
a random location
Guide to Programming with Python
73
Wrapping Up the Program
def main():
wall_image = games.load_image("wall.jpg",
transparent = False)
games.screen.background = wall_image
pizza_image = games.load_image("pizza.bmp")
pizza_x = random.randrange(games.screen.width)
pizza_y = random.randrange(games.screen.height)
the_pizza = Pizza(image = pizza_image,
x = pizza_x, y = pizza_y)
games.screen.add(the_pizza)
Guide to Programming with Python
74
Wrapping Up the Program (continued)
pan_image = games.load_image("pan.bmp")
the_pan = Pan(image = pan_image,
x = games.mouse.x,
y = games.mouse.y)
games.screen.add(the_pan)
games.mouse.is_visible = False
games.screen.event_grab = True
games.screen.mainloop()
# kick it off!
main()
Guide to Programming with Python
slippery_pizza.py
75
The Pizza Panic Game
Figure 11.1: Sample run of the Pizza Panic game
The player must catch the falling pizzas.
Guide to Programming with Python
pizza_panic.py
76
Summary
is a module that contains objects, functions,
and classes for writing 2D games
• The games.init() function creates a new graphics
screen
• The games.load_image() function loads an image
stored in a graphics file and returns an image
object
• color is a module that defines a set of constants for
colors
• screen is a games module object that provides
access to the graphics screen
• games
Guide to Programming with Python
77
Summary (continued)
has properties for width, height, background,
and update rate, among others
• The screen object has methods to add an object,
remove all objects, begin its main loop, and quit,
among others
• mouse is a games module object that provides access
to the mouse
• mouse has properties for the x-coordinate and the ycoordinate of the mouse pointer as well as a
property for mouse pointer visibility
• Sprite is a class in the games module for graphics
objects that can be displayed on the graphics
screen
• screen
Guide to Programming with Python
78
Summary (continued)
• A Sprite object has properties for its image,
location, speed, orientation, and overlapping
objects, among others
• A Sprite object has methods for updating itself and
destroying itself, among others
• Text is a subclass of Sprite for text displayed on
the graphics screen
• Message is a subclass of Text for text displayed on
the graphics screen that disappears after a set
period of time
Guide to Programming with Python
79