z=) Using Modules)
Pygame Module
RCD a eee mrtg tar eed eaten le Nae
tte NO EMMA EEK 21) Roda en Cel eRe
graphical or text-based games.
PYGAMING
Pygame isn't an inherent module to Python but those using the Raspberry Pi will already have it installed. Everyone else will
need to use: pip install pygame from the command prompt.
FETEEEDD Naturally you need to load up the Pygame modules
into memory before you'e able to utilise them.
Once that's done Pygame requires the user to initialseit prior to
any of the Functions being used:
import pygane
pygane.init ()
Let's create asimple game ready window, and give
itatitle:
gamewindow-pygame.display.set_wode (800, 600))
pygame.display. set_caption( Adventure Game")
‘You can see that after the first lines entered, you need to lick back
ino the IDLE Shel to continue entering code; also, you can change
the ite ofthe window to anything you like.
FETSSED S20ly you cant close the newly created Pygame
‘window without closing the Python IDLE Shell,
“which isnt very practical For this reason, you need to work n the
editor (New > File) and create a True/False while loop:
import pygane
from pygame-locals import +
pygane.init ()
gamewindow-pygame. display. set_mode (800, 600))
pygane.display.set_caption(*adventure Gane")
running-True
white running!
for event in pygame.event.get ()
if event .type==QUIT:
rales
running=1
Pygeme.quit ()
‘le Edt Format Bun Gptions Windows Heb
Tapert yea
‘en pypimer cals seport *
pyeanecanati).
ganewindow-pygane. display set mode( (800, 600))
Praone- display seiacoption(
ite runmang:
Preece)PEPID ithe Pyaame windowstilwont
close don’t worry it'sjusta
discrepancy between the IDLE (which is written
vith Tkinter) and the Pygame madule. IF you
run your cade via the command line, closes.
perfectly well
FETED) You're going to shift the cade around a bit now,
running the main Pygame code within a wile loop;
Temakesit neater and easier to Follow, we've downloaded a graphic
to.use and we need to set some parameters For pygame:
import pygame
pygane.init ()
wunning-True
while running:
‘gamewindow-pygane.display.set_mode ( (800,600) )
pygane.display.set_caption ("Adventure Game")
black=(0,0,0)
white= (255,255,255)
|
ing=pygame . inage. Load (*/home/pi /Downloads/
epritel.png")
def sprite(x.y):
gamewindow.biit (img, (01)
x= (8000.45)
y= (6000.8)
gamewindow. £111 (white)
sprite (xy!
pygame.display.update()
for event in pygame.event.get ():
if event .typesspygame.QUIT:
running=False
( Pygame Module CH
Lets quick a through ne code changes. Weve
Sue defined two colours, black and white together
withthelr respective RGB colour values Next we've loaded the
downloaded image called spritet.png and allocated it tothe
variable img; and also defined sprite Function and the Bit Function
wil allow us to eventually move the image
=a seco00r0.15)
Wom pygene cals port * ror0'33
fi 7 ganewindon. F111 (white)
rerminge
ganewindorpygane display set_node( (800,600)
Prgane.dioplay-seiccopeion(-Aaverture cane”)
Biscr=io.0"0)
maiten(255 255,255
Jngrpyeane image, lead(-/hone/pi/Domloads/spritet png”)
ef spritets.y)
menindon-D1ARCing. (2.99)
peer eT)BATESR AD ‘owe can change the code around again, this ngepeed=0
time containing a movement option within the = .
uuhile loop, and adding the variables needed to move the sprite en
: {or event sn pygune. event. 0:
oundthe see SEL ars AIST
sport pysame ‘nninge Peas
a 4 event.type == prune, KEYED:
{Lf event. hey-epygane._LEPT:
unningeTive schaagersb
elif event .eys=pygane.K_RIGHT:
xchange=5
Af event.type==pygane. KEYUP:
gamewindow=pygane .display.set_node( (800, 600))
pygame.display. set_caption ("Adventure Game”)
black= (0, 0,0)
white: (255,255,255)
image load (*/home/pi /Downloads /
og’)
def sprite (x.y) eee
genewindow.buit ting, (x.y) gonewindow. £111 white)
x-(800"0.45) |
y=(500*0.6) ——
a pygane.quit ()
pipraly-Parapilaamenyhn esa pane 7/842) =
| erectatarereute.
Copy the code down and using the left and right arrow keys on the keyboard you can move your sprite across the battom of
the screen. Now, Looks lke you have the makings of a classic arcade 2D scroller in the works.
"sings
somes,FETEEEERD You can nowimplement afew additions and utlise
some previous tutorial code. The new elements re
the Subprocess module, of which ane Function allowsus to launch a
‘second Python script from within another; and we're going tocreatea
New Fl called pygamett py
Pygame Modules
pygene.display.flip()
clock. tick (60)
continue
break
pygane-quit ()
import pygene
inport tine
import. subprocess
pygame. init () Sore tlhe
soreen = pygane.display.set_node((800, 250)) | tat
clock = pygame. time .Clock()
a a
pygame. font -Font (ene, 25)
pygane.tine.set_timer [pygane.USEREVENT, 200)
def text_generator (text)
mp
for letter in tex!
trp += letter
Af letter
yield trp
class DynanicText (object)
def _init_(self, font, text, pos,
autoraset=Faise) :
pelf.done = False
self font = font
aelf.text ~ text
self._gen = text_generator (self, text)
self.pos = pos
self autoreset
self update ()
autoreset,
def reset (self)
self._gen = text_generator(self.text)
self.done = False
self update ()
def update (seit)
AE not sel€.done:
try: self.rendered = self.font
render (next (eelf.gen), True, (0, 128, 0))
‘except StopIteration:
‘self.done = True
‘time sleep (10)
subprocess. Popen(*python3 /howe /pi/Documents/
Python\ Code/pygamel-py 1", shellatrue)
def draw(self, screen):
screen.blit (self.rendered, sel£.pos)
text=("A long time ago, a barbarian strode from the
frozen north. Sword in hand...")
massage = Dynamictext (font, text, (65, 120),
autoreset-True}
waile True:
for event in pygame.event.get ()
AE event.type == pygame.QUIT: break
i€ event .type == pygame.USEREVENT: message.
update)
lee:
screen. £111 [pygame.color Color (‘black’ ))
message.draw (ecreen)
when yourun this code splay along,
BALM row rygare window oth heiniro text
scolingtotheriht tera pase often seconds then launches
theman game Python sept here youcan move the war spre
around: Overaltheefect saute good but there's alvaysroom
forimproement