Pygame workshop


Paweł Fertyk

Slides:

pyladies-pygame.pfertyk.me

Workshop:

github.com/pfertyk/workshop-pyladies-pygame/blob/master/game.py

RGB

rgb color mixing

Red, Green, Blue

Python tuple: (R, G, B)

0 <= R, G, B <= 255

(0, 0, 0)     
(0, 0, 60)     
(0, 0, 255)     
(0, 255, 0)     
(255, 0, 0)     
(255, 0, 255)     
(255, 255, 255)     

Surface

pygame surface

Blit

surface.blit(other_surface, (x, y))

pygame blit

GameObject

game object

GameObject

  • __init__(pos, radius, speed, angle_deg)
  • draw(surface)
  • contain(surface)
  • animate()
  • collides_with(other_obj)

Blit position

correcting the blit

Rotation

surface = pygame.transform.rotozoom(
    original_surface,
    angle,  # in degrees, counterclockwise
    scale  # set to 1.0 for rotation only
)

Acceleration vs direction

acceleration and direction

Vectors

adding vectors

Text

font = pygame.font.Font(
  None,  # filename
  64  # in pixels
)

...

text_surface = font.render(
  'Hello',  # text
  1,  # antialias
  (200, 200, 0)  # color
)

Sounds

pygame.mixer.init()
pygame.init()

sound = pygame.mixer.Sound('laser.wav')

...

sound.play()

Fixing sound lag:

pygame.mixer.init(buffer=1024)

Exercise 1

Make the ESC key (K_ESCAPE) close the game

Splitting the asteroid

splitting the asteroid

Cleaning up the code

from itertools import chain

...

for obj in chain(asteroids, bullets, starship):
    obj.animate()
    obj.draw(SCREEN)

Starship can be None:

chain(asteroids, bullets, (starship, ) if starship else ())

Exercise 2

Display the number of asteroids left:

  • Big = 7
  • Medium = 3
  • Small = 1

Hint: use the radius

Exercise 3

Save the best (winning) score in a file

import os.path
best_score = 0

if os.path.isfile('score.txt'):
...
else:
...

Creating a file if it doesn't exist:

with open('score.txt', 'w+') as score_file:

Notable Pygame games

Frets On Fire

frets on fire

Squirrel Eat Squirrel

squirrel eat squirrel

Ren'Py

renpy

More info:

Thank you!



Questions?