Let’s Learn
Aj. Andrew Davison, CoE, PSU Hat Yai Campus
E-mail: ad@[Link]
12. More Games
I don't have time to teach these in class,
but they contain interesting features.
Outline Look at the code, and if you don't
understand it, please contact me.
1. Whack-a-Mole 9. Menu Test
2. Snake 10. Card Game Basics
3. Fred's Bad Day 11. Tank
4. Breakout 12. Platformer
5. Breakout with High 13. 15-Puzzle
Scores 14. 15-Puzzle with Tweening
6. Bomber Pilot 15. Cannon
7. Tetrominoes 16. Cannon with Physics
8. Tic-Tac-Toe
2
1. Whack-a-Mole
3
Classes Used
4
Interesting Features
▪The shovel follows the mouse
▪ uses MOUSEMOTION and MOUSEBUTTONDOWN
events in the game loop
▪Displays the passing time in seconds
▪ uses [Link].get_ticks(), which returns
milliseconds, ms
5
2. Snake
6
Classes Used
7
Interesting Features
▪Separate files for the Food and Snake classes
▪ they are imported into [Link]
▪I use a [Link] attribute instead of the usual
gameOver variable
▪Time-constraints used to create new food and
make the snake longer.
▪"Distance apart" calculations work out if the snake
is 'near' enough to food to eat it
8
▪The Food and Snake classes do not inherit
Sprite since they do not use images.
9
3. Fred's Bad Day
A full-screen game
10
Start Screen
11
Restart Screen
12
Classes Used
13
Interesting Features
▪Separate files for the Barrel and Fred classes
▪ they are imported into [Link]
▪A time-constraint decides when to create a new
barrel
▪ see updateBarrels() in [Link]
▪The end of a game includes a restart screen
▪ lets gameOver be reset to False
14
▪The game uses FULLSCREEN mode
▪ screen = [Link].set_mode([1000,768],
[Link])
▪KEYDOWN and KEYUP events allow repeated
movement left and right.
▪Fred's life points are represented by a yellow
rectangle drawn at the bottom of the window
15
▪The game's images, music and sound effects
are stored in an assets/ sub-directory.
▪Barrel start positions are stored in a class
variable called SLOTS in the Barrel class
▪A barrel 'splits' into two, by changing its display
image
▪ from [Link] to Barrel_break.png
16
▪Fred can change between 4 different images
▪There is a time-constraint on Fred for how long
he is "hit" by a barrel, which affects which
image is shown
▪ see start of [Link]() and [Link]()
17
4. Breakout
18
Classes Used
19
Interesting Features
▪A more complex version of [Link]
▪The wall is a single sprite that stores a list of
(x,y,w,h) rectangles in [Link]
▪ see build() in the Wall class
▪[Link]() draws a single brick image multiple
times at each of the (x,y) rectangle coordinates
20
▪The ball rebounds from the bat in a complex
way along the x-axis
▪ it depends on the position of the ball's center relative
to the bat's center
▪ see [Link]() and [Link]()
▪The ball rebounds off a brick differently
depending on if it hits the sides or top/bottom of
the brick's rectangle.
▪ see [Link]()
21
▪Unlike [Link], there is no Block class since
the collisions on the walls are implemented
using scrWidth and scrHeight calculations
▪ see [Link]()
▪If the player removes all the bricks, the wall is
recreated; the game continues until the no. of
lives == 0
▪ see call to [Link]() at the end of [Link]()
22
5. Breakout with High Scores
23
Name Entry at Game End
you
type the
name and
then enter
24
High Scores List
these
scores
are
remembered
across
games
25
Classes Used
new classes
26
Interesting Features
▪The NameBox and HighScores classes are
imported into main:
from NameBox import NameBox
from HighScores import HighScores
▪Two extra game state booleans: enteringName
and showingScores
▪ gameOver → enteringName → showingScores
▪ represents 3 stages of finishing
▪ gameOver is implemented using a lives counter
27
▪Redirection of text input to NameBox object inside
event handling
▪The NameBox object deals with text entry, and
handles backspaces
▪The HighScores class stores a Python list of
(name,score) pairs in a binary file using the Pickle
module
▪The list is sorted, and only the top-10 highest
scores are stored in the file.
28
6. Bomber Pilot
29
Start Screen
30
Classes Used
31
Interesting Features
▪This is a top-down scroller, similar to the "Skier"
example, except the plane appears to be moving
up the screen.
▪In fact, the plane does not move vertically, instead
the clouds, islands, and the ocean background
move down.
▪The ocean background resets when the top of its
image reaches the top of the window
▪ the reset causes the bottom of the image to be aligned
with the bottom of the window
32
▪The start screen is generated by calling
renderInstructions() with a list of text lines.
▪There are two animated sprites: one for
explosions, and another for lightning.
33
7. Tetrominoes
34
Start Screen and Instructions
Help instructions
35
Classes Used
36
Interesting Features
▪A clone of the famous "Tetris" game
▪ [Link]
▪This code is based on the game in Chapter 7 of
"Making Games with Python and Pygame" by
Al. Sweigart, but changed to use classes,
sprites, and a simpler game loop
▪ a copy of the chapter is included in "[Link]"
37
▪The game can be paused, and help shown
▪ requires game state variables isPaused and
showHelp
▪Two classes:
▪ TetPiece: represents the current falling piece
▪ TetBoard: represents the board, including all the
squares at the bottom of the board
▪Two time-constraints:
▪ a piece is moved down after a fixed amount of time,
which gets less as the game progresses
▪ a user can only press a key every 0.1 sec
38
▪TetPiece stores the definition of the 7 shapes
for the pieces, which are made up of 4 squares
each.
▪Each shape template defines the look of the
piece when it is rotated 90, so a template may
consist of at most 4 different 'shapes'
▪ this large amount of data makes the coding of shape
rotation much smaller
39
▪The TetBoard class stores the squares on the
board in a [Link] 2D list.
▪ board[x][y], where y is the row
▪ y == 0 is the top row of squares in the board
▪When a piece lands on the board, the squares
in the piece are added to the squares already in
[Link], and any complete rows (lines) are
deleted.
▪When a line is deleted, the rows (lines) above it
must be moved down
▪ this means moving row y to row y+1
40
8. Tic-Tac-Toe
You (o) versus
the computer (x)
41
Classes Used
42
Interesting Features
▪A turn-based game, where the other player is
the computer.
▪The turn state is implemented using a
isPlayerTurn boolean.
▪The computer player is implemented by the
XMachine class
▪ so named since it is the "X" player in the game
43
▪Both XMachine and the human player use the
Board class, which is the Tic-Tac-Toe board
▪ the board is a 9 element list using the format:
0 1 2
3 4 5
6 7 8
▪XMachine is not a clever Artificial Intelligence
(AI) program since Tic-Tac-Toe is so simple
▪ XMachine checks all the 8 ways of winning in
TicTacToe – 3 across, 3 down, and 2 diagonals
44
9. Menu Test
45
Classes Used
46
Interesting Features
▪[Link] is not a game, but an example of
how to use Button objects to build a menu.
▪This Button class is a slightly extended version
of the Button class in the Skier game
▪ this class changes the color of the button when the
mouse moves over it
▪The menu items can be selected by mouse
clicking or by using the up, down and enter
keys
47
▪The button objects are stored in a list called
buttons in main
▪The buttons do not do anything themselves.
▪Instead when a button is selected, the game
loop sets a pressedIdx variable to the index
number of the button in the list
▪The selection of a button plays a 'click' sound.
48
the Deck object
showing the
10. Card Game Basics current top card
two Hand objects
each with 5 cards
the cards are
manipulated
using the three
mouse buttons
and mouse
dragging
49
Classes Used
50
Interesting Features
▪Basic classes for Card, Deck and Hand along with
a game loop that allows card movement, card
flipping, card position resetting, and deck rotation
▪The cards in a hand can be moved by selecting
and dragging with the left mouse button.
▪The position of the cards in the hands can be reset
to their starting position by clicking on any card
using the middle mouse button.
51
▪A card can be turned over by clicking on it
using the right mouse button.
▪The top card of the deck can be moved to the
bottom by clicking on it with the left mouse
button.
52
11. Tank Shell sprites
Made from
Brick sprites
53
Classes Used
54
Interesting Features
▪The tank sprite is rotatable, and can move forwards
and backwards.
▪The tank can shoot Shell sprites forwards from its
gun.
▪The walls are generated using 8x8 Brick sprites,
which are destroyed when a Shell sprite hits them.
▪The walls are specified using a text-based 'map'
which is converted into sprites at run-time.
55
▪The tank cannot drive off the window (because
of BlockSprites) or through walls.
▪When a big-enougth hole has been made in a
wall, the tank can drive through it.
▪The shell explosions are AnimSprite objects
56
12. Platformer
fireballs
player
jump
platforms
57
Classes Used
58
Interesting Features
▪This is a simple side-scroller platform game
▪ the player appears to move left and right, but doesn't
actually move horizontally
▪ instead the background, platforms, and fireballs
move horizontally in the opposite direction
▪The player can jump up, and is affected by
gravity which makes it come back down
▪ it can land on a platform or on the floor (the base of
the window)
59
▪The platforms and goal are defined in a text-
based map, which are converted into
BlockSprite objects at run-time
▪ a similar technique is used in the tank game for
creating the walls as Bricks
▪The platforms and goal are created and
managed by the World class
▪The platforms extend beyond the right-hand
side of the window, but become visible as the
player moves right.
60
▪The background image was chosen such that
it's left side matches its right side
▪ the background moves left and right, but slower than
the foreground platforms to mimic the idea that it is
further away
▪ it is sometimes necessary to draw two copies of the
background so that it seemlessly covers the entire
window
▪ this is handled by the Scenery class
61
▪The player consists of a left-facing and right-
facing version which changes depending on
which way the player is moving.
▪A fireball is represented by a Fireball sprite, but
all the fireballs are managed by the Fireballs
class
62
13. 15-Puzzle
63
Classes Used
64
Interesting Features
▪This is another famous puzzle game, usually called
the 15-puzzle
▪ see [Link]
▪The 15 squares (and an invisible square for the
space) are implemented as 16 Block sprites
▪When the user clicks on a block adjacent to the
space, it instantly moves into that space
▪ this is implemented by swapping the invisible block and
the number block
65
14. 15-Puzzle with Tweening
the move
takes some Tweening means the
time creation of animation
steps between the start
and end position of a
game movement.
Tweening is used here to
make a number square
move into the space over
the course of a few
animation frames,
instead of instantly.
66
Classes Used
new class
67
Interesting Features
▪A related idea to tweening is easing which is a
position equation (or function) to move beween
a start and end position
▪ the most common easing function is "linear" which
means that the game object moves with a fixed
velocity between the start and end position
▪ this can be drawn as a graph showing position vs
time:
position
position equation
time 68
▪The idea of tweening with easing was first
developed by Robert Penner
▪ see [Link]
▪ includes slides, a book chapter, code
▪Many easing equations have been defined
which tween an object in interesting ways
▪ see graphs on the next slide
69
used in my
Some Easing Equations program
70
Animating with Easing Functions
▪Penner's easing equations have been
implemented as functions in many languages
▪ e.g. Python code at [Link]
cleure/e5ba94f94e828a3f5466
▪ stored as [Link] in the code directory
▪My Animator class can use any of these easing
functions to tween a block into the empty
space.
71
Tweening as a Game State
▪The tweening of a block uses a new game state
in the game loop: the isTweening boolean
▪When isTweening is true, updates to the game
by the user are ignored until the tweening is
finished; then isTweening is set to false
72
the current mouse
15. Cannon position is drawn
Only 5 shells can
in the game as
be on-screen at
'crosshairs'
any time.
shells shoot out
shells: when
from the current
a shell hits a wall
position of the
it disappears
end of the gun
and travel in a
straight line
bricks: when
a shell hits a
cannon: brick, both of
the gun rotates them
to follow the disappear
mouse position
bricks can be different sizes
73
Classes Used
74
Rotating the Cannon
▪The cannon gun was drawn so that it's rotation
point (a black dot) is at the center of the image:
[Link]
75
▪This means that rotating the gun image will
always leave the rotation point unchanged at
the center:
76
▪The gun image is drawn by Pygame using
[Link], which means that its rotation point
(the center) will never move.
▪The base of the cannon is a gray circle drawn
at the bottom of the window, so half of the circle
cannot be seen.
not visible
77
Firing a Shell
▪The shells starting position (x, y) and its x- and
y- steps are based on calculating the gun's
angle to the x-axis, and on its barrel's length.
yStep
(x,y)
barrel
length xStep
angle
(xRot,yRot)
78
16. Cannon with Physics
Shells disappear when their
velocity is close to 0
The Pymunk module is
used to calculate the
physics of the moving
objects (the shells and
the bricks)
The shells and the
The cannon class bricks move and
is unchanged collide in much more
interesting ways, and
with less coding by us.
Bricks no longer disappear
79
Classes Used
Shell and Brick
contain Pymunk
Cannon is physics code in
unchanged the init functions
No need for an
update() function;
Pymunk handles it 80
Pymunk [Link]
▪A 2D physics library for implementing
complicated (real-looking) movement and
collisions between "rigid" (hard) shapes
▪ uses mass, velocity, momentum, forces, gravity, etc.
▪Often used with pygame to add more real
actions to a game.
▪How to install:
▪ pip install pymunk
▪ or [Link]
81
A python interface to a C library
called chipmunk
Pymunk Info ([Link]
▪ Downloaded [Link]
▪ source code, but also contains docs, examples
▪ Online docs:
▪ [Link]
▪ Step-by=step programming example:
▪ [Link]
▪ Example docs
▪ [Link]
▪ [Link] (uses pygame)
▪ [Link] (uses pygame)
82
Chipmunk Tutorials
▪ [Link]
chipmunk-tutorial-for-ios-how-to-create-a-simple-
iphone-game
▪ [Link]
articles/chipmunk/
▪ [Link]
SimpleObjectiveChipmunk/
83
Pymunk Ideas
▪Space: the world holding the objects
▪ set gravity and other forces; it calculates velocities and
positions for objects each time that step() is called
▪An object usually has two parts:
▪ body: defines the mass, inertia, position
▪ shape: Pymunk supports circle, poly, segment
▪ necessary if you want shapes to collide
▪ Pymunk cannot draw shapes
▪Joints: limits how objects can move
▪ types: pins, pivots, sliders, grooves
84
Pymunk and Pygame
▪Use pymunk to update an object's position,
velocity and collisions inside the game loop
▪No need for (much) code for updating game
objects since pygame does most of it each time
that [Link]() is called
▪Pygame is used for drawing shapes
▪ no need for collision detection or groups
85