SlideShare une entreprise Scribd logo
1  sur  43
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

Contenu connexe

Tendances

Get started python programming part 1
Get started python programming   part 1Get started python programming   part 1
Get started python programming part 1Nicholas I
 
Chapter 2 Decision Making (Python Programming Lecture)
Chapter 2 Decision Making (Python Programming Lecture)Chapter 2 Decision Making (Python Programming Lecture)
Chapter 2 Decision Making (Python Programming Lecture)IoT Code Lab
 
Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming KrishnaMildain
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for KidsAimee Maree Forsstrom
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytestHector Canto
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming LanguageTahani Al-Manie
 
Chapter 0 Python Overview (Python Programming Lecture)
Chapter 0 Python Overview (Python Programming Lecture)Chapter 0 Python Overview (Python Programming Lecture)
Chapter 0 Python Overview (Python Programming Lecture)IoT Code Lab
 
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...Edureka!
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
 
Python games
Python gamesPython games
Python gamesmolw
 
Minecraft in 500 lines of Python with Pyglet
Minecraft in 500 lines of Python with PygletMinecraft in 500 lines of Python with Pyglet
Minecraft in 500 lines of Python with PygletRichard Donkin
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1Sunil OS
 
PYTHON - TKINTER - GUI - PART 1.ppt
PYTHON - TKINTER - GUI - PART 1.pptPYTHON - TKINTER - GUI - PART 1.ppt
PYTHON - TKINTER - GUI - PART 1.pptPriyaSoundararajan1
 

Tendances (20)

Get started python programming part 1
Get started python programming   part 1Get started python programming   part 1
Get started python programming part 1
 
Chapter 2 Decision Making (Python Programming Lecture)
Chapter 2 Decision Making (Python Programming Lecture)Chapter 2 Decision Making (Python Programming Lecture)
Chapter 2 Decision Making (Python Programming Lecture)
 
Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming
 
Tic toc game presentation
Tic toc game presentationTic toc game presentation
Tic toc game presentation
 
Python basics
Python basicsPython basics
Python basics
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
 
Python ppt
Python pptPython ppt
Python ppt
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
 
Chapter 0 Python Overview (Python Programming Lecture)
Chapter 0 Python Overview (Python Programming Lecture)Chapter 0 Python Overview (Python Programming Lecture)
Chapter 0 Python Overview (Python Programming Lecture)
 
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Python games
Python gamesPython games
Python games
 
Log4 J
Log4 JLog4 J
Log4 J
 
Python programming
Python  programmingPython  programming
Python programming
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Minecraft in 500 lines of Python with Pyglet
Minecraft in 500 lines of Python with PygletMinecraft in 500 lines of Python with Pyglet
Minecraft in 500 lines of Python with Pyglet
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1
 
PYTHON - TKINTER - GUI - PART 1.ppt
PYTHON - TKINTER - GUI - PART 1.pptPYTHON - TKINTER - GUI - PART 1.ppt
PYTHON - TKINTER - GUI - PART 1.ppt
 
Beginning Python Programming
Beginning Python ProgrammingBeginning Python Programming
Beginning Python Programming
 

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

Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...Edureka!
 
The Ring programming language version 1.7 book - Part 50 of 196
The Ring programming language version 1.7 book - Part 50 of 196The Ring programming language version 1.7 book - Part 50 of 196
The Ring programming language version 1.7 book - Part 50 of 196Mahmoud Samir Fayed
 
Deeper into ARKit with CoreML and Turi Create
Deeper into ARKit with CoreML and Turi CreateDeeper into ARKit with CoreML and Turi Create
Deeper into ARKit with CoreML and Turi CreateSoojin Ro
 
Game programming with Groovy
Game programming with GroovyGame programming with Groovy
Game programming with GroovyJames Williams
 
Python Online Compiler
Python Online CompilerPython Online Compiler
Python Online CompilerMr Examples
 
Day 1 - Python Overview and Basic Programming - Python Programming Camp - One...
Day 1 - Python Overview and Basic Programming - Python Programming Camp - One...Day 1 - Python Overview and Basic Programming - Python Programming Camp - One...
Day 1 - Python Overview and Basic Programming - Python Programming Camp - One...One Year Programming
 
Kinect v2 Introduction and Tutorial
Kinect v2 Introduction and TutorialKinect v2 Introduction and Tutorial
Kinect v2 Introduction and TutorialTsukasa Sugiura
 
Programming simple games with a raspberry pi and
Programming simple games with a raspberry pi andProgramming simple games with a raspberry pi and
Programming simple games with a raspberry pi andKellyn Pot'Vin-Gorman
 
Action Script 3 With Flash Cs3
Action Script 3 With Flash Cs3Action Script 3 With Flash Cs3
Action Script 3 With Flash Cs3ravihamsa
 
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Edureka!
 
Screenflow Podcampaz
Screenflow PodcampazScreenflow Podcampaz
Screenflow PodcampazTerry Lee
 
Introduction to Raspberry Pi and GPIO
Introduction to Raspberry Pi and GPIOIntroduction to Raspberry Pi and GPIO
Introduction to Raspberry Pi and GPIOKris Findlay
 
Python and Machine Learning
Python and Machine LearningPython and Machine Learning
Python and Machine Learningtrygub
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance PythonIan Ozsvald
 
Python week 2 2019 2020 for g10 by eng.osama ghandour
Python week 2 2019 2020 for g10 by eng.osama ghandourPython week 2 2019 2020 for g10 by eng.osama ghandour
Python week 2 2019 2020 for g10 by eng.osama ghandourOsama Ghandour Geris
 

Similaire à PyGame Tutorial | PyGame Python Tutorial For Beginners | Python Certification Training | Edureka (20)

Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
 
3.Pi for Python
3.Pi for Python3.Pi for Python
3.Pi for Python
 
The Ring programming language version 1.7 book - Part 50 of 196
The Ring programming language version 1.7 book - Part 50 of 196The Ring programming language version 1.7 book - Part 50 of 196
The Ring programming language version 1.7 book - Part 50 of 196
 
Deeper into ARKit with CoreML and Turi Create
Deeper into ARKit with CoreML and Turi CreateDeeper into ARKit with CoreML and Turi Create
Deeper into ARKit with CoreML and Turi Create
 
Game programming with Groovy
Game programming with GroovyGame programming with Groovy
Game programming with Groovy
 
Python Online Compiler
Python Online CompilerPython Online Compiler
Python Online Compiler
 
Day 1 - Python Overview and Basic Programming - Python Programming Camp - One...
Day 1 - Python Overview and Basic Programming - Python Programming Camp - One...Day 1 - Python Overview and Basic Programming - Python Programming Camp - One...
Day 1 - Python Overview and Basic Programming - Python Programming Camp - One...
 
Kinect v2 Introduction and Tutorial
Kinect v2 Introduction and TutorialKinect v2 Introduction and Tutorial
Kinect v2 Introduction and Tutorial
 
Programming simple games with a raspberry pi and
Programming simple games with a raspberry pi andProgramming simple games with a raspberry pi and
Programming simple games with a raspberry pi and
 
Charming python
Charming pythonCharming python
Charming python
 
Async and Parallel F#
Async and Parallel F#Async and Parallel F#
Async and Parallel F#
 
Async and Parallel F#
Async and Parallel F#Async and Parallel F#
Async and Parallel F#
 
Action Script 3 With Flash Cs3
Action Script 3 With Flash Cs3Action Script 3 With Flash Cs3
Action Script 3 With Flash Cs3
 
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
 
Screenflow Podcampaz
Screenflow PodcampazScreenflow Podcampaz
Screenflow Podcampaz
 
Introduction to Raspberry Pi and GPIO
Introduction to Raspberry Pi and GPIOIntroduction to Raspberry Pi and GPIO
Introduction to Raspberry Pi and GPIO
 
Python and Machine Learning
Python and Machine LearningPython and Machine Learning
Python and Machine Learning
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance Python
 
Vanmathy python
Vanmathy python Vanmathy python
Vanmathy python
 
Python week 2 2019 2020 for g10 by eng.osama ghandour
Python week 2 2019 2020 for g10 by eng.osama ghandourPython week 2 2019 2020 for g10 by eng.osama ghandour
Python week 2 2019 2020 for g10 by eng.osama ghandour
 

Plus de Edureka!

What to learn during the 21 days Lockdown | Edureka
What to learn during the 21 days Lockdown | EdurekaWhat to learn during the 21 days Lockdown | Edureka
What to learn during the 21 days Lockdown | EdurekaEdureka!
 
Top 10 Dying Programming Languages in 2020 | Edureka
Top 10 Dying Programming Languages in 2020 | EdurekaTop 10 Dying Programming Languages in 2020 | Edureka
Top 10 Dying Programming Languages in 2020 | EdurekaEdureka!
 
Top 5 Trending Business Intelligence Tools | Edureka
Top 5 Trending Business Intelligence Tools | EdurekaTop 5 Trending Business Intelligence Tools | Edureka
Top 5 Trending Business Intelligence Tools | EdurekaEdureka!
 
Tableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | EdurekaTableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | EdurekaEdureka!
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaEdureka!
 
Top 5 PMP Certifications | Edureka
Top 5 PMP Certifications | EdurekaTop 5 PMP Certifications | Edureka
Top 5 PMP Certifications | EdurekaEdureka!
 
Top Maven Interview Questions in 2020 | Edureka
Top Maven Interview Questions in 2020 | EdurekaTop Maven Interview Questions in 2020 | Edureka
Top Maven Interview Questions in 2020 | EdurekaEdureka!
 
Linux Mint Tutorial | Edureka
Linux Mint Tutorial | EdurekaLinux Mint Tutorial | Edureka
Linux Mint Tutorial | EdurekaEdureka!
 
How to Deploy Java Web App in AWS| Edureka
How to Deploy Java Web App in AWS| EdurekaHow to Deploy Java Web App in AWS| Edureka
How to Deploy Java Web App in AWS| EdurekaEdureka!
 
Importance of Digital Marketing | Edureka
Importance of Digital Marketing | EdurekaImportance of Digital Marketing | Edureka
Importance of Digital Marketing | EdurekaEdureka!
 
RPA in 2020 | Edureka
RPA in 2020 | EdurekaRPA in 2020 | Edureka
RPA in 2020 | EdurekaEdureka!
 
Email Notifications in Jenkins | Edureka
Email Notifications in Jenkins | EdurekaEmail Notifications in Jenkins | Edureka
Email Notifications in Jenkins | EdurekaEdureka!
 
EA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | EdurekaEA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | EdurekaEdureka!
 
Cognitive AI Tutorial | Edureka
Cognitive AI Tutorial | EdurekaCognitive AI Tutorial | Edureka
Cognitive AI Tutorial | EdurekaEdureka!
 
AWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | EdurekaAWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | EdurekaEdureka!
 
Blue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | EdurekaBlue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | EdurekaEdureka!
 
Big Data on AWS Tutorial | Edureka
Big Data on AWS Tutorial | Edureka Big Data on AWS Tutorial | Edureka
Big Data on AWS Tutorial | Edureka Edureka!
 
A star algorithm | A* Algorithm in Artificial Intelligence | Edureka
A star algorithm | A* Algorithm in Artificial Intelligence | EdurekaA star algorithm | A* Algorithm in Artificial Intelligence | Edureka
A star algorithm | A* Algorithm in Artificial Intelligence | EdurekaEdureka!
 
Kubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | EdurekaKubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | EdurekaEdureka!
 
Introduction to DevOps | Edureka
Introduction to DevOps | EdurekaIntroduction to DevOps | Edureka
Introduction to DevOps | EdurekaEdureka!
 

Plus de Edureka! (20)

What to learn during the 21 days Lockdown | Edureka
What to learn during the 21 days Lockdown | EdurekaWhat to learn during the 21 days Lockdown | Edureka
What to learn during the 21 days Lockdown | Edureka
 
Top 10 Dying Programming Languages in 2020 | Edureka
Top 10 Dying Programming Languages in 2020 | EdurekaTop 10 Dying Programming Languages in 2020 | Edureka
Top 10 Dying Programming Languages in 2020 | Edureka
 
Top 5 Trending Business Intelligence Tools | Edureka
Top 5 Trending Business Intelligence Tools | EdurekaTop 5 Trending Business Intelligence Tools | Edureka
Top 5 Trending Business Intelligence Tools | Edureka
 
Tableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | EdurekaTableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | Edureka
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | Edureka
 
Top 5 PMP Certifications | Edureka
Top 5 PMP Certifications | EdurekaTop 5 PMP Certifications | Edureka
Top 5 PMP Certifications | Edureka
 
Top Maven Interview Questions in 2020 | Edureka
Top Maven Interview Questions in 2020 | EdurekaTop Maven Interview Questions in 2020 | Edureka
Top Maven Interview Questions in 2020 | Edureka
 
Linux Mint Tutorial | Edureka
Linux Mint Tutorial | EdurekaLinux Mint Tutorial | Edureka
Linux Mint Tutorial | Edureka
 
How to Deploy Java Web App in AWS| Edureka
How to Deploy Java Web App in AWS| EdurekaHow to Deploy Java Web App in AWS| Edureka
How to Deploy Java Web App in AWS| Edureka
 
Importance of Digital Marketing | Edureka
Importance of Digital Marketing | EdurekaImportance of Digital Marketing | Edureka
Importance of Digital Marketing | Edureka
 
RPA in 2020 | Edureka
RPA in 2020 | EdurekaRPA in 2020 | Edureka
RPA in 2020 | Edureka
 
Email Notifications in Jenkins | Edureka
Email Notifications in Jenkins | EdurekaEmail Notifications in Jenkins | Edureka
Email Notifications in Jenkins | Edureka
 
EA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | EdurekaEA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | Edureka
 
Cognitive AI Tutorial | Edureka
Cognitive AI Tutorial | EdurekaCognitive AI Tutorial | Edureka
Cognitive AI Tutorial | Edureka
 
AWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | EdurekaAWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | Edureka
 
Blue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | EdurekaBlue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | Edureka
 
Big Data on AWS Tutorial | Edureka
Big Data on AWS Tutorial | Edureka Big Data on AWS Tutorial | Edureka
Big Data on AWS Tutorial | Edureka
 
A star algorithm | A* Algorithm in Artificial Intelligence | Edureka
A star algorithm | A* Algorithm in Artificial Intelligence | EdurekaA star algorithm | A* Algorithm in Artificial Intelligence | Edureka
A star algorithm | A* Algorithm in Artificial Intelligence | Edureka
 
Kubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | EdurekaKubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | Edureka
 
Introduction to DevOps | Edureka
Introduction to DevOps | EdurekaIntroduction to DevOps | Edureka
Introduction to DevOps | Edureka
 

Dernier

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 

Dernier (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 

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()