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
Ad

More Related Content

What's hot (20)

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!
 
Python games
Python gamesPython games
Python games
molw
 
Python tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academyPython tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academy
TIB Academy
 
Python games (pygames)
Python games (pygames)Python games (pygames)
Python games (pygames)
Ahmed Alyazji
 
What is Python? | Edureka
What is Python? | EdurekaWhat is Python? | Edureka
What is Python? | Edureka
Edureka!
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Mohammed Rafi
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
Srinivas Narasegouda
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
AnirudhaGaikwad4
 
Variables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaVariables & Data Types In Python | Edureka
Variables & Data Types In Python | Edureka
Edureka!
 
Python_in_Detail
Python_in_DetailPython_in_Detail
Python_in_Detail
MAHALAKSHMI P
 
Python Programming Draft PPT.pptx
Python Programming Draft PPT.pptxPython Programming Draft PPT.pptx
Python Programming Draft PPT.pptx
LakshmiNarayanaReddy48
 
Python
PythonPython
Python
Suman Chandra
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
Fariz Darari
 
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Edureka!
 
Python
PythonPython
Python
대갑 김
 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | Edureka
Edureka!
 
Python Programming
Python ProgrammingPython Programming
Python Programming
shahid sultan
 
Python final ppt
Python final pptPython final ppt
Python final ppt
Ripal Ranpara
 
Python
PythonPython
Python
Aashish Jain
 
Python projects
Python projectsPython projects
Python projects
Zealous System
 
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!
 
Python games
Python gamesPython games
Python games
molw
 
Python tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academyPython tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academy
TIB Academy
 
Python games (pygames)
Python games (pygames)Python games (pygames)
Python games (pygames)
Ahmed Alyazji
 
What is Python? | Edureka
What is Python? | EdurekaWhat is Python? | Edureka
What is Python? | Edureka
Edureka!
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Mohammed Rafi
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
Srinivas Narasegouda
 
Variables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaVariables & Data Types In Python | Edureka
Variables & Data Types In Python | Edureka
Edureka!
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
Fariz Darari
 
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Edureka!
 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | Edureka
Edureka!
 

Similar to 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...
Edureka!
 
3.Pi for Python
3.Pi for Python3.Pi for Python
3.Pi for Python
Mayank Joneja
 
bv-python-einfuehrung aplication learn.pdf
bv-python-einfuehrung aplication learn.pdfbv-python-einfuehrung aplication learn.pdf
bv-python-einfuehrung aplication learn.pdf
Mohammadalhaboob2030
 
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
Mahmoud 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 Create
Soojin Ro
 
Game programming with Groovy
Game programming with GroovyGame programming with Groovy
Game programming with Groovy
James Williams
 
Python Online Compiler
Python Online CompilerPython Online Compiler
Python Online Compiler
Mr 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
 
Boost Productivity with 30 Simple Python Scripts.pdf
Boost Productivity with 30 Simple Python Scripts.pdfBoost Productivity with 30 Simple Python Scripts.pdf
Boost Productivity with 30 Simple Python Scripts.pdf
SOFTTECHHUB
 
Kinect v2 Introduction and Tutorial
Kinect v2 Introduction and TutorialKinect v2 Introduction and Tutorial
Kinect v2 Introduction and Tutorial
Tsukasa 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 and
Kellyn Pot'Vin-Gorman
 
Charming python
Charming pythonCharming python
Charming python
Abu Ashraf Masnun
 
Async and Parallel F#
Async and Parallel F#Async and Parallel F#
Async and Parallel F#
mattpodwysocki
 
Async and Parallel F#
Async and Parallel F#Async and Parallel F#
Async and Parallel F#
mattpodwysocki
 
Action Script 3 With Flash Cs3
Action Script 3 With Flash Cs3Action Script 3 With Flash Cs3
Action Script 3 With Flash Cs3
ravihamsa
 
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 Podcampaz
Terry Lee
 
Introduction to Raspberry Pi and GPIO
Introduction to Raspberry Pi and GPIOIntroduction to Raspberry Pi and GPIO
Introduction to Raspberry Pi and GPIO
Kris Findlay
 
Python and Machine Learning
Python and Machine LearningPython and Machine Learning
Python and Machine Learning
trygub
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance Python
Ian Ozsvald
 
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!
 
bv-python-einfuehrung aplication learn.pdf
bv-python-einfuehrung aplication learn.pdfbv-python-einfuehrung aplication learn.pdf
bv-python-einfuehrung aplication learn.pdf
Mohammadalhaboob2030
 
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
Mahmoud 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 Create
Soojin Ro
 
Game programming with Groovy
Game programming with GroovyGame programming with Groovy
Game programming with Groovy
James Williams
 
Python Online Compiler
Python Online CompilerPython Online Compiler
Python Online Compiler
Mr 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
 
Boost Productivity with 30 Simple Python Scripts.pdf
Boost Productivity with 30 Simple Python Scripts.pdfBoost Productivity with 30 Simple Python Scripts.pdf
Boost Productivity with 30 Simple Python Scripts.pdf
SOFTTECHHUB
 
Kinect v2 Introduction and Tutorial
Kinect v2 Introduction and TutorialKinect v2 Introduction and Tutorial
Kinect v2 Introduction and Tutorial
Tsukasa 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 and
Kellyn 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 Cs3
ravihamsa
 
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 Podcampaz
Terry Lee
 
Introduction to Raspberry Pi and GPIO
Introduction to Raspberry Pi and GPIOIntroduction to Raspberry Pi and GPIO
Introduction to Raspberry Pi and GPIO
Kris Findlay
 
Python and Machine Learning
Python and Machine LearningPython and Machine Learning
Python and Machine Learning
trygub
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance Python
Ian Ozsvald
 
Ad

More from 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
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
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
Edureka!
 
Tableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | EdurekaTableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | Edureka
Edureka!
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | Edureka
Edureka!
 
Top 5 PMP Certifications | Edureka
Top 5 PMP Certifications | EdurekaTop 5 PMP Certifications | Edureka
Top 5 PMP Certifications | Edureka
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
Edureka!
 
Linux Mint Tutorial | Edureka
Linux Mint Tutorial | EdurekaLinux Mint Tutorial | Edureka
Linux Mint Tutorial | Edureka
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
Edureka!
 
Importance of Digital Marketing | Edureka
Importance of Digital Marketing | EdurekaImportance of Digital Marketing | Edureka
Importance of Digital Marketing | Edureka
Edureka!
 
RPA in 2020 | Edureka
RPA in 2020 | EdurekaRPA in 2020 | Edureka
RPA in 2020 | Edureka
Edureka!
 
Email Notifications in Jenkins | Edureka
Email Notifications in Jenkins | EdurekaEmail Notifications in Jenkins | Edureka
Email Notifications in Jenkins | Edureka
Edureka!
 
EA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | EdurekaEA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | Edureka
Edureka!
 
Cognitive AI Tutorial | Edureka
Cognitive AI Tutorial | EdurekaCognitive AI Tutorial | Edureka
Cognitive AI Tutorial | Edureka
Edureka!
 
AWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | EdurekaAWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | Edureka
Edureka!
 
Blue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | EdurekaBlue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | Edureka
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
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
Edureka!
 
Kubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | EdurekaKubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | Edureka
Edureka!
 
Introduction to DevOps | Edureka
Introduction to DevOps | EdurekaIntroduction to DevOps | Edureka
Introduction to DevOps | Edureka
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 | Edureka
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
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
Edureka!
 
Tableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | EdurekaTableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | Edureka
Edureka!
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | Edureka
Edureka!
 
Top 5 PMP Certifications | Edureka
Top 5 PMP Certifications | EdurekaTop 5 PMP Certifications | Edureka
Top 5 PMP Certifications | Edureka
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
Edureka!
 
Linux Mint Tutorial | Edureka
Linux Mint Tutorial | EdurekaLinux Mint Tutorial | Edureka
Linux Mint Tutorial | Edureka
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
Edureka!
 
Importance of Digital Marketing | Edureka
Importance of Digital Marketing | EdurekaImportance of Digital Marketing | Edureka
Importance of Digital Marketing | Edureka
Edureka!
 
RPA in 2020 | Edureka
RPA in 2020 | EdurekaRPA in 2020 | Edureka
RPA in 2020 | Edureka
Edureka!
 
Email Notifications in Jenkins | Edureka
Email Notifications in Jenkins | EdurekaEmail Notifications in Jenkins | Edureka
Email Notifications in Jenkins | Edureka
Edureka!
 
EA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | EdurekaEA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | Edureka
Edureka!
 
Cognitive AI Tutorial | Edureka
Cognitive AI Tutorial | EdurekaCognitive AI Tutorial | Edureka
Cognitive AI Tutorial | Edureka
Edureka!
 
AWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | EdurekaAWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | Edureka
Edureka!
 
Blue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | EdurekaBlue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | Edureka
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
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
Edureka!
 
Kubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | EdurekaKubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | Edureka
Edureka!
 
Introduction to DevOps | Edureka
Introduction to DevOps | EdurekaIntroduction to DevOps | Edureka
Introduction to DevOps | Edureka
Edureka!
 
Ad

Recently uploaded (20)

Build With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdfBuild With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdf
Google Developer Group - Harare
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
BookNet Canada
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and MLGyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
Gyrus AI
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
BookNet Canada
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and MLGyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
Gyrus AI
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 

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()
  翻译: