SlideShare a Scribd company logo
Python Certification Training https://www.edureka.co/python
Agenda
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
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?
Python Certification Training https://www.edureka.co/python
Making Your Own Game
Independency!
I’m a happy gamer!
Python Certification Training https://www.edureka.co/python
What is PyGame?
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.
Python Certification Training https://www.edureka.co/python
Installing PyGame
Python Certification Training https://www.edureka.co/python
Installing PyGame
Installation is very easy!
Python Certification Training https://www.edureka.co/python
Prerequisites for learning PyGame
Python Certification Training https://www.edureka.co/python
Prerequisites
Just the workflow in Python
Python Certification Training https://www.edureka.co/python
Anatomy of PyGame
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
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
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
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!
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)
Python Certification Training https://www.edureka.co/python
Working with Images!
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?
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.
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
Python Certification Training https://www.edureka.co/python
Working with Sounds!
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()
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()
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!")
...
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
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(
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
Python Certification Training https://www.edureka.co/python
Geometric Drawing
Python Certification Training https://www.edureka.co/python
Geometric Drawing
Drawing API is straightforward!
Rectangle pygame.draw.rect(surface, color, pygame.Rect(left, top, width, height))
Circle pygame.draw.circle(surface, color, (x, y), radius)
Python Certification Training https://www.edureka.co/python
Geometric Drawing
Drawing API is straightforward!
Built-in Outlines
Fix those gaps?
# draw a rectangle
pygame.draw.rect(surface, color, pygame.Rect(10, 10, 100, 100), 10)
# draw a circle
pygame.draw.circle(surface, color, (300, 60), 50, 10)
Python Certification Training https://www.edureka.co/python
Geometric Drawing
Drawing API is straightforward!
Acceptable Outlines Polygons Lines
pygame.draw.polygon(surface, color, point_list)
Python Certification Training https://www.edureka.co/python
Geometric Drawing
Drawing API is straightforward!
Acceptable Outlines Polygons Lines
pygame.draw.line(surface, color, (startX, startY), (endX, endY), width)
Python Certification Training https://www.edureka.co/python
Fonts & Text
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)
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)
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
Python Certification Training https://www.edureka.co/python
More on Input
Python Certification Training https://www.edureka.co/python
More on Input
How do you get the state of any input device?
Event Queue Polling
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()
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()
Python Certification Training https://www.edureka.co/python
Centralized Scene Logic
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()
PyGame Tutorial | PyGame Python Tutorial For Beginners | Python Certification Training | Edureka

More Related Content

What's hot (20)

PPT
Introduction to Python
amiable_indian
 
PPT
Synfig
jankimodi
 
PPT
introduction to blender
anand09
 
PDF
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Edureka!
 
PDF
Variables & Data Types In Python | Edureka
Edureka!
 
PDF
Introduction to Game Development
Reggie Niccolo Santos
 
PPTX
Unity 3D, A game engine
Md. Irteza rahman Masud
 
DOC
COMPUTER GRAPHICS LAB MANUAL
Vivek Kumar Sinha
 
PDF
【Unite Tokyo 2018】Audio機能の基礎と実装テクニック
UnityTechnologiesJapan002
 
PDF
Unity2018/2019における最適化事情
Unity Technologies Japan K.K.
 
PPTX
Computer Graphics
Deepak Kumar Mohapatra
 
PPT
Python ppt
Mohita Pandey
 
PPTX
Web Design Basics for Kids: HTML & CSS
AnnMarie Ppl
 
PPTX
Beginning Python Programming
St. Petersburg College
 
PDF
Introduction To Python | Edureka
Edureka!
 
PDF
Cinemachineで見下ろし視点のカメラを作る
Unity Technologies Japan K.K.
 
PPSX
An Introduction To Game development
Ahmed
 
PDF
VRM 標準シェーダ MToon の使い方
VirtualCast, Inc.
 
PDF
Intro to Python for Non-Programmers
Ahmad Alhour
 
ODP
Python Presentation
Narendra Sisodiya
 
Introduction to Python
amiable_indian
 
Synfig
jankimodi
 
introduction to blender
anand09
 
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Edureka!
 
Variables & Data Types In Python | Edureka
Edureka!
 
Introduction to Game Development
Reggie Niccolo Santos
 
Unity 3D, A game engine
Md. Irteza rahman Masud
 
COMPUTER GRAPHICS LAB MANUAL
Vivek Kumar Sinha
 
【Unite Tokyo 2018】Audio機能の基礎と実装テクニック
UnityTechnologiesJapan002
 
Unity2018/2019における最適化事情
Unity Technologies Japan K.K.
 
Computer Graphics
Deepak Kumar Mohapatra
 
Python ppt
Mohita Pandey
 
Web Design Basics for Kids: HTML & CSS
AnnMarie Ppl
 
Beginning Python Programming
St. Petersburg College
 
Introduction To Python | Edureka
Edureka!
 
Cinemachineで見下ろし視点のカメラを作る
Unity Technologies Japan K.K.
 
An Introduction To Game development
Ahmed
 
VRM 標準シェーダ MToon の使い方
VirtualCast, Inc.
 
Intro to Python for Non-Programmers
Ahmad Alhour
 
Python Presentation
Narendra Sisodiya
 

Similar to PyGame Tutorial | PyGame Python Tutorial For Beginners | Python Certification Training | Edureka (20)

PPT
Pygame : créer des jeux interactifs en Python.
fakhroushka
 
PPT
"Pemrograman Python untuk Pemula dan Ahli"
Muhammadlenterabawon
 
PDF
learning_Pygame_Basics_Part _1f_for_beginner.pdf
AihamSlaiman1
 
PDF
Introduction to Pygame (Lecture 7 Python Game Development)
abdulrafaychaudhry
 
PDF
Python lecture 10
Tanwir Zaman
 
PDF
Денис Ковалев «Python в игровой индустрии»
DataArt
 
PPTX
Day2
Avilay Parekh
 
ODP
Python Games
FahadAlH
 
PDF
Makinggames
Ritu Raj
 
PDF
Is Pygame a Programming Language - Key Insights you should know
SOC Learning
 
PDF
Makinggames
Rashi Agarwal
 
PPTX
Python games
dxbeeh
 
PDF
Entering the world of Serious Games with Python
Harshinee Sriram
 
PPTX
XIX PUG-PE - Pygame game development
matheuscmpm
 
PPTX
Python games
dxbeeh
 
PDF
bv-python-einfuehrung aplication learn.pdf
Mohammadalhaboob2030
 
PDF
Object-Oriented Python 1st Edition Irv Kalb
lovisvulic0m
 
PPTX
Python games (pygames)
Ahmed Alyazji
 
PDF
Introduction to Python
Dylan Seychell
 
PDF
Object-Oriented Python 1st Edition Irv Kalb
dassetevell4
 
Pygame : créer des jeux interactifs en Python.
fakhroushka
 
"Pemrograman Python untuk Pemula dan Ahli"
Muhammadlenterabawon
 
learning_Pygame_Basics_Part _1f_for_beginner.pdf
AihamSlaiman1
 
Introduction to Pygame (Lecture 7 Python Game Development)
abdulrafaychaudhry
 
Python lecture 10
Tanwir Zaman
 
Денис Ковалев «Python в игровой индустрии»
DataArt
 
Python Games
FahadAlH
 
Makinggames
Ritu Raj
 
Is Pygame a Programming Language - Key Insights you should know
SOC Learning
 
Makinggames
Rashi Agarwal
 
Python games
dxbeeh
 
Entering the world of Serious Games with Python
Harshinee Sriram
 
XIX PUG-PE - Pygame game development
matheuscmpm
 
Python games
dxbeeh
 
bv-python-einfuehrung aplication learn.pdf
Mohammadalhaboob2030
 
Object-Oriented Python 1st Edition Irv Kalb
lovisvulic0m
 
Python games (pygames)
Ahmed Alyazji
 
Introduction to Python
Dylan Seychell
 
Object-Oriented Python 1st Edition Irv Kalb
dassetevell4
 
Ad

More from Edureka! (20)

PDF
What to learn during the 21 days Lockdown | Edureka
Edureka!
 
PDF
Top 10 Dying Programming Languages in 2020 | Edureka
Edureka!
 
PDF
Top 5 Trending Business Intelligence Tools | Edureka
Edureka!
 
PDF
Tableau Tutorial for Data Science | Edureka
Edureka!
 
PDF
Python Programming Tutorial | Edureka
Edureka!
 
PDF
Top 5 PMP Certifications | Edureka
Edureka!
 
PDF
Top Maven Interview Questions in 2020 | Edureka
Edureka!
 
PDF
Linux Mint Tutorial | Edureka
Edureka!
 
PDF
How to Deploy Java Web App in AWS| Edureka
Edureka!
 
PDF
Importance of Digital Marketing | Edureka
Edureka!
 
PDF
RPA in 2020 | Edureka
Edureka!
 
PDF
Email Notifications in Jenkins | Edureka
Edureka!
 
PDF
EA Algorithm in Machine Learning | Edureka
Edureka!
 
PDF
Cognitive AI Tutorial | Edureka
Edureka!
 
PDF
AWS Cloud Practitioner Tutorial | Edureka
Edureka!
 
PDF
Blue Prism Top Interview Questions | Edureka
Edureka!
 
PDF
Big Data on AWS Tutorial | Edureka
Edureka!
 
PDF
A star algorithm | A* Algorithm in Artificial Intelligence | Edureka
Edureka!
 
PDF
Kubernetes Installation on Ubuntu | Edureka
Edureka!
 
PDF
Introduction to DevOps | Edureka
Edureka!
 
What to learn during the 21 days Lockdown | Edureka
Edureka!
 
Top 10 Dying Programming Languages in 2020 | Edureka
Edureka!
 
Top 5 Trending Business Intelligence Tools | Edureka
Edureka!
 
Tableau Tutorial for Data Science | Edureka
Edureka!
 
Python Programming Tutorial | Edureka
Edureka!
 
Top 5 PMP Certifications | Edureka
Edureka!
 
Top Maven Interview Questions in 2020 | Edureka
Edureka!
 
Linux Mint Tutorial | Edureka
Edureka!
 
How to Deploy Java Web App in AWS| Edureka
Edureka!
 
Importance of Digital Marketing | Edureka
Edureka!
 
RPA in 2020 | Edureka
Edureka!
 
Email Notifications in Jenkins | Edureka
Edureka!
 
EA Algorithm in Machine Learning | Edureka
Edureka!
 
Cognitive AI Tutorial | Edureka
Edureka!
 
AWS Cloud Practitioner Tutorial | Edureka
Edureka!
 
Blue Prism Top Interview Questions | Edureka
Edureka!
 
Big Data on AWS Tutorial | Edureka
Edureka!
 
A star algorithm | A* Algorithm in Artificial Intelligence | Edureka
Edureka!
 
Kubernetes Installation on Ubuntu | Edureka
Edureka!
 
Introduction to DevOps | Edureka
Edureka!
 
Ad

Recently uploaded (20)

PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 

PyGame Tutorial | PyGame Python Tutorial For Beginners | Python Certification Training | Edureka

  • 1. Python Certification Training https://www.edureka.co/python Agenda
  • 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?
  • 4. Python Certification Training https://www.edureka.co/python Making Your Own Game Independency! I’m a happy gamer!
  • 5. Python Certification Training https://www.edureka.co/python What is PyGame?
  • 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.
  • 7. Python Certification Training https://www.edureka.co/python Installing PyGame
  • 8. Python Certification Training https://www.edureka.co/python Installing PyGame Installation is very easy!
  • 9. Python Certification Training https://www.edureka.co/python Prerequisites for learning PyGame
  • 10. Python Certification Training https://www.edureka.co/python Prerequisites Just the workflow in Python
  • 11. Python Certification Training https://www.edureka.co/python Anatomy of PyGame
  • 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)
  • 17. Python Certification Training https://www.edureka.co/python Working with Images!
  • 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
  • 21. Python Certification Training https://www.edureka.co/python Working with Sounds!
  • 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
  • 28. Python Certification Training https://www.edureka.co/python Geometric Drawing
  • 29. Python Certification Training https://www.edureka.co/python Geometric Drawing Drawing API is straightforward! Rectangle pygame.draw.rect(surface, color, pygame.Rect(left, top, width, height)) Circle pygame.draw.circle(surface, color, (x, y), radius)
  • 30. Python Certification Training https://www.edureka.co/python Geometric Drawing Drawing API is straightforward! Built-in Outlines Fix those gaps? # draw a rectangle pygame.draw.rect(surface, color, pygame.Rect(10, 10, 100, 100), 10) # draw a circle pygame.draw.circle(surface, color, (300, 60), 50, 10)
  • 31. Python Certification Training https://www.edureka.co/python Geometric Drawing Drawing API is straightforward! Acceptable Outlines Polygons Lines pygame.draw.polygon(surface, color, point_list)
  • 32. Python Certification Training https://www.edureka.co/python Geometric Drawing Drawing API is straightforward! Acceptable Outlines Polygons Lines pygame.draw.line(surface, color, (startX, startY), (endX, endY), width)
  • 33. Python Certification Training https://www.edureka.co/python Fonts & Text
  • 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
  • 37. Python Certification Training https://www.edureka.co/python More on Input
  • 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()
  • 41. Python Certification Training https://www.edureka.co/python Centralized Scene Logic
  • 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()