1 of 42

Building Video Games for Fun with PyGame

Shannon -jj Behrens | @jjinux | jjinux.com

2 of 42

Sometimes, it's a lot of fun to be an amateur

3 of 42

PyGame

4 of 42

Introduction

  • PyGame is a library for building simple video games in Python
  • It's based on SDL, and thus runs on Windows, Mac, and Linux
  • There are also higher-level libraries and frameworks built on top of PyGame

5 of 42

Installation

  • Usually, you can install PyGame with pip
  • However, there's a bug for macOS Mojave right now
  • Here's the workaround:
    • Install Miniconda
    • Restart your terminal
    • conda create -n pygameon3 python=3
    • This is less than ideal, and occasionally it crashes
  • Pay attention to whether you're using Python 2 or 3

6 of 42

Tutorial

7 of 42

Pummel the Chimp

  • There are a ton of nice PyGame tutorials
  • I particularly liked Line By Line Chimp which I'm shamelessly stealing borrowing from
  • Here's how to run the code:
    • source activate pygameon3
    • python -m pygame.examples.chimp
  • Here's a video
  • Here's the code

8 of 42

Importing Modules

Please forgive the style; this isn't my code ;)

pygame imports things recursively

The locals module has commonly used constants and functions (optional)

Warn if fonts or the mixer aren't available

9 of 42

Loading Images

Create platform independent file paths

Just die if we can't load images

Convert the image in order to optimize it for our display in order to blit it (i.e. copy it to the screen) faster

A colorkey is the color that should be used to represent transparency

RGB white is (255, 255, 255)

10 of 42

Loading Sounds

If pygame can't initialize the mixer, just make the sounds do nothing

If it can, but we can't load the sound file, then just die

11 of 42

Fist Part 1

This is part 1 of our Fist object

It inherits from Sprite which is like an image in the game

A sprite has an image and a rect for the location

Sprites have an update method which is called once per frame

Move the fist to where the mouse is

12 of 42

Fist Part 2

Track whether the user is punching with the punching instance variable

If the user punches, move the fist slightly (on previous slide)

The punch method takes a target parameter

The punch method returns true if the fist is colliding with the target

13 of 42

Chimp Part 1

If the chimp is dizzy, he's spinning

Otherwise, he's walking from side to side

Use the move instance variable to keep track of which direction the chimp is moving

Use the dizzy instance variable to control the spinning motion the chimp does when it gets hit

14 of 42

Chimp Part 2

To walk, just change self.rect

If the chimp hits the edge of the screen, flip the image around and move the other way

When spinning, rotate 360 degrees 12 degrees per frame

When rotating, always start with the original image to compensate for quality loss at each step

15 of 42

Chimp Part 3

If the chimp was punched, just set dizzy to 1

Save a reference to the original image so that we can mutate self.image

16 of 42

Main Part 1

This is the main method for the game

Initialize pygame, set up the display, and set a window title

Make the mouse invisible since we draw the fist wherever the mouse is

17 of 42

Main Part 2

Create a background "surface" that is the same size as our screen

Then fill it with an off-white color

Note, we haven't yet drawn the background; we've just created a surface object

18 of 42

Main Part 3

If the font subsystem couldn't load, we just ignore this part

Create a new Font using a TrueType font (use None for the default) and a size

Render the string using the font with antialiasing turned on in a dark gray

Center the text on the background

Finally "blit" (i.e. copy or paste) the text onto the background

19 of 42

Main Part 4

We haven't actually shown anything yet

Now blit the background onto the screen

We use a technique called "double buffering"

Imagine a painting with two sides. You paint one side while the user looks at the other side. When you're ready, you flip the painting around and start working on painting the other side.

20 of 42

Main Part 5

Create a clock to control our framerate so the game doesn't run too fast

Create the two sounds that we'll use for sound effects

Create the Chimp and the Fist sprites

RenderPlain is a "sprite group" which takes care of rendering our two sprites, fist and chimp

21 of 42

Main Part 6

This is an infinite loop

All games run in some sort of a loop

Inside the loop, you generally check for user input, update the state of the world, and then draw it to the screen

Run at 60 frames per second

22 of 42

Main Part 7

On each frame, process all the events

If the user closed the window or hit escape, exit the loop

If the user pressed the mouse, tell the fist to try to punch the chimp

If it succeeds, tell the chimp it was punched

Play the relevant sounds

On mouse up, tell the fist to unpunch

​

23 of 42

Main Part 8

Calling update on the sprite group calls update for all of the sprites in the group

This gives each sprite a chance to update itself

The chimp will step a little to the side or spin a little if it's dizzy

The fist will update based on the position of the mouse

24 of 42

Main Part 9

Draw the background onto the screen to erase everything

This is slightly inefficient, but okay for this game

Draw all the sprites

Flip the display which shows everything we've drawn at the same time

25 of 42

Quitting

Outside of the loop, just call pygame.quit()

At the bottom of the file, call main()

That's it!

26 of 42

PyWeek

27 of 42

Introduction

  • PyWeek is a world-wide hackathon in which you must build a video game from scratch in Python either as an individual or in a team
  • It happens twice a year
  • You must follow a theme which is announced at the start of the week
  • The entries are judged by the contestants

28 of 42

Some Thoughts

  • It's more fun and a little less stressful than a 3 day hackathon
  • It's a little like running a marathon (not that I actually know what that's like!)
    • It's a challenge to finish
    • It's very rewarding when you do
    • You almost assuredly won't come in first place ;)

29 of 42

Some Tips

  • It's nice to have a team that can work together in the same location
  • Take 2-3 days off work to focus on your game
  • Take some time to think before coding
  • Pick your toolkit (including any frameworks) ahead of time
  • Practice, practice, practice!

30 of 42

TicTacToe3

31 of 42

Introduction

  • This was my first PyWeek entry
  • The theme was "Up, up, up!"
  • I built a 3D version of Tic-Tac-Toe
  • I did it on my own
  • I only used PyGame
  • Here's a video
  • Here's the code

32 of 42

Implementation

  • It was a lot like Pummel the Chimp
  • It was a single UI with a single state machine--because that's all I knew how to build
  • It built a nice model, separate of the UI
    • I even had a text-based version of the game
  • I built a little scheduler to coordinate animations
  • Obviously, my artwork skills are subpar

33 of 42

Hellacopy

34 of 42

Introduction

  • This was my second PyWeek entry
  • The theme was "Twisted"
  • I built a knockoff of the game 1942, but with a helicopter
  • My buddy, Adam Ulvi, and I did it as a team
  • I used this library named PGU (Phil's pyGame Utilities) which has an approach to building a world out of tiles
  • Here's a video
  • Here's the code

35 of 42

Implementation

  • Obviously, I made it too small
  • I made the animations a lot nicer:
    • Each sprite has an instance variable named animation
    • Each animation is built using a generator, which makes the code really pleasant
  • There's an intro, the main game, and two different endings
    • Each "scene" is like a video game of its own
    • It returns the next scene to show the user
    • This makes for more sophisticated, more complete games
  • I used a bit of trigonometry to get the turrets to face you:
    • SOHCAHTOA FTW!!!

36 of 42

Other Things

37 of 42

Scratch

I've had a lot of luck teaching kids how to write video games using Scratch

It's perfect for kids in the 7-12 age range

I brought three of my students ;)

There are some really nice tutorials

And of course, I encourage them to tweak things once they've made it through the tutorial

38 of 42

High School Sim

For high school kids, I teach them how to build a text-based high school simulation using just Python

And of course, tweaking the simulation and making it more complex and realistic is where all the fun lies

39 of 42

Raspberry Pi and Kano

Teaching kids on Raspberry Pi's makes everything better

I'm especially fond of Kano and Kano OS

Over the summer, I setup a lab at my house and teach groups of up to 10 kids

It really helps to have multiple helpers when doing this

40 of 42

Unity

One of these days, I'm going to take the time to learn a professional, 3D video game framework like Unity

I've heard there's a nice class on Udemy, and there's a Black Friday sale going on ;)

41 of 42

Phaser

I'm also tempted to try out Phaser which is "A fast, fun and free open source HTML5 game framework"

42 of 42

Closing

Questions?

Slides: http://bit.ly/pygame_talk

Shannon -jj Behrens�jjinux.com�@jjinux