** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on PyGame Tutorial covers all the basic aspects of creating and running your own simple game. It establishes the concepts needed like images, sounds, geometry etc needed to build your own games using Python. Below is the agenda of this PPT:
What is PyGame?
Installing PyGame
Anatomy of PyGame
Working with Images
Working with Sounds
Working with Geometric Drawings
Working with Fonts and Text
Understanding Input Methods
Understanding Scene Logic
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
2. Python Certification Training https://www.edureka.co/python
Agenda
Introduction 01
Why
PyGame?
Getting Started 02
Concepts 03
Practical Approach 04
Installing and working
with PyGame
Use-Cases along the way
to understand PyGame
Coding concepts
with PyGame
3. Python Certification Training https://www.edureka.co/python
Making Your Own Game
You decided to make your own game!
Deployment Platform?Language? What sort of game?
But how?
6. Python Certification Training https://www.edureka.co/python
What Is PyGame?
It is a cross-platform set of Python modules designed for writing video gamesWhat is PyGame?
It includes computer graphics and sound libraries designed to be used with Python!
PyGame can handle time, video (both still images and vids), music, fonts, different
image formats, cursors, mouse, keyboard, Joysticks and much much more.
And all of that is very simple.
12. Python Certification Training https://www.edureka.co/python
Anatomy
Simple Python code!
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT
:
done = True
pygame.display.flip()
Programming in Python is fun!
It's easier to understand and write PyGame code
13. Python Certification Training https://www.edureka.co/python
Drawing An Object
Simple Python code!
# Add this somewhere after the event pumping and before the
display.flip()
pygame.draw.rect(screen, (0, 128, 255), pygame.Rect(30, 30, 60, 60))
Surface Instance to draw
Tuple for colours (RGB)
Instance – x, y , width, height
14. Python Certification Training https://www.edureka.co/python
Interactivity
Simple Python code!
is_blue = TrueAdd before loop
Modify rectangle code to
pick a color conditionally
Add this to the for loop!
if is_blue: color = (0, 128, 255)
else: color = (255, 100, 0)
pygame.draw.rect(screen, color, pygame.Rect(30, 30, 60, 60))
if event.type == pygame.KEYDOWN and even
t.key == pygame.K_SPACE:
is_blue = not is_blue
15. Python Certification Training https://www.edureka.co/python
Moving Objects
Simple Python code!
Let’s run the code and see where we stand at this point!
up_pressed = pygame.get_pressed()[pygame.K_UP]
Rectangle from previous
frames remain on screen
Moves EXTREMELY fast!
16. Python Certification Training https://www.edureka.co/python
Moving Objects
Let’s fix the output!
Let’s run the code and see where we stand at this point!
screen.fill((0, 0, 0))
Reset screen to black before
drawing rectangle
Fixing frame rate!
clock = pygame.time.Clock()
...
while not done:
...
# will block execution until 1/60 seconds have passed
# since the previous time clock.tick was called.
clock.tick(60)
18. Python Certification Training https://www.edureka.co/python
Images
Very easy to add images!
surface = pygame.Surface((100, 100))
Instantiate a blank surface by
calling the Surface constructor
What did we just do?
19. Python Certification Training https://www.edureka.co/python
Images
Varying bitrate of image?
surface = pygame.Surface((100, 100), pygame.SRCALPHA)32-bit RGBA image
What did we just do?
This will create a 100 x 100 image
that's initialized to transparent.
20. Python Certification Training https://www.edureka.co/python
Images
Custom Image?
How do we do that?
Let’s load this PNG image
image = pygame.image.load('ball.png')We need the file to be loaded
BALL.PNG
same as
ball.png
Linux
NOT SAME
22. Python Certification Training https://www.edureka.co/python
Sounds
Let’s start with the basics
Playing a song once
pygame.mixer.music.load('foo.mp3')
pygame.mixer.music.play(0)
Playing a song
infinitely
pygame.mixer.music.load('foo.mp3')
pygame.mixer.music.play(-1)
What does this do? pygame.mixer.music.play()
23. Python Certification Training https://www.edureka.co/python
Sounds
More things to do with sounds!
Queuing a song pygame.mixer.music.queue('next_song.mp3')
Stopping a song pygame.mixer.music.stop()
24. Python Certification Training https://www.edureka.co/python
Sounds
Simple code for sounds!
USEREVENT + 1 ensures
number assigned to
SONG_END isn’t equal to
any other event
...
SONG_END = pygame.USEREVENT + 1
pygame.mixer.music.set_endevent(SONG_END)
pygame.mixer.music.load('song.mp3')
pygame.mixer.music.play()
...
while True:
...
for event in pygame.event.get():
...
if event.type == SONG_END:
print("the song ended!")
...
25. Python Certification Training https://www.edureka.co/python
Sounds
More operations with sound!
Consider 5 songs _songs = ['song_1.mp3', 'song_2.mp3', 'song_3.mp3', 'song_4.mp3', 'song_5.mp3']
Stopping a song
import random
def play_a_different_song():
global _currently_playing_song, _songs
next_song = random.choice(_songs)
while next_song == _currently_playing_
song:
next_song = random.choice(_songs)
_currently_playing_song = next_song
pygame.mixer.music.load(next_song)
pygame.mixer.music.play()
Add a flag _currently_playing_song = None
26. Python Certification Training https://www.edureka.co/python
Sounds
More operations with sound!
Consider 5 songs _songs = ['song_1.mp3', 'song_2.mp3', 'song_3.mp3', 'song_4.mp3', 'song_5.mp3']
Play in same sequence
each time
def play_next_song():
global _songs
_songs = _songs[1:] + [_songs[0]] #
move current song to the back of list
pygame.mixer.music.load(_songs[0])
pygame.mixer.music.play(
27. Python Certification Training https://www.edureka.co/python
Sounds
The music API is very centralized
.play() method effect = pygame.mixer.Sound('beep.wav')
effect.play()
_sound_library = {}
def play_sound(path):
global _sound_library
sound = _sound_library.get(path)
if sound == None:
canonicalized_path = path.replace('/', os.sep).replace('', os.sep)
sound = pygame.mixer.Sound(canonicalized_path)
_sound_library[path] = sound
sound.play()
Sound library
34. Python Certification Training https://www.edureka.co/python
Fonts & Texts
Quick answer to – How to render text?
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
done = False
font = pygame.font.SysFont("comicsansms", 72)
text = font.render("Hello, World", True, (0, 128, 0))
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
done = True
screen.fill((255, 255, 255))
screen.blit(text,
(320 - text.get_width() // 2, 240 - text.get_height() // 2))
pygame.display.flip()
clock.tick(60)
35. Python Certification Training https://www.edureka.co/python
Fonts & Texts
Here are certain useful tips!
Enumerate fonts available on the system
all_fonts = pygame.font.get_fonts()
Enumerate default font of the system
font = pygame.font.Font(None, size)
Pass name of font file directly
font = pygame.font.Font("myresources/fonts/Papyrus.ttf", 26)
36. Python Certification Training https://www.edureka.co/python
Fonts & Texts
Let’s optimize the creation process!
def make_font(fonts, size):
available = pygame.font.get_fonts()
# get_fonts() returns a list of lowercase spaceless font names
choices = map(lambda x:x.lower().replace(' ', ''), fonts)
for choice in choices:
if choice in available:
return pygame.font.SysFont(choice, size)
return pygame.font.Font(None, size)
_cached_text = {}
def create_text(text, fonts, size, color):
global _cached_text
key = '|'.join(map(str, (fonts, size, color, text)))
image = _cached_text.get(key, None)
if image == None:
font = get_font(fonts, size)
image = font.render(text, True, color)
_cached_text[key] = image
return image
_cached_fonts = {}
def get_font(font_preferences, size):
global _cached_fonts
key = str(font_preferences) + '|' + str(size)
font = _cached_fonts.get(key, None)
if font == None:
font = make_font(font_preferences, size)
_cached_fonts[key] = font
return font
38. Python Certification Training https://www.edureka.co/python
More on Input
How do you get the state of any input device?
Event Queue Polling
39. Python Certification Training https://www.edureka.co/python
More on Input
How do you get the state of any input device?
Event Queue Polling
Event added to the queue must be emptiedAfter each button press
How can this be done?
Pygame.event.get() Pygame.event.pump()
40. Python Certification Training https://www.edureka.co/python
More on Input
How do you get the state of any input device?
Event Queue Polling
List of Booleans that describe state of each keyPygame.key.get_pressed()
Returns the coordinates of mouse cursorPygame.key.mouse.get_pos()
Returns state of each mouse buttonPygame.mouse.get_pressed()
42. Python Certification Training https://www.edureka.co/python
Scene Logic
Class definition for a SceneBase:
class SceneBase:
def __init__(self):
self.next = self
def ProcessInput(self, events):
print(“You didn't override this in the child class")
def Update(self):
print(“You didn't override this in the child class")
def Render(self, screen):
print(“You didn't override this in the child class")
def SwitchToScene(self, next_scene):
self.next = next_scene
Receives all events happened since last frameProcessInput
Game logic for the scene goes herePygame.key.mouse.get_pos()
Render code goes here
It receives main screen surface as input
Pygame.mouse.get_pressed()