Getting started with pygame on a Mac

There are a lot of pygame tutorials out there, but I haven’t yet found a simple, step-by-step how-to on how to just get pygame installed on a Mac, and then actually use it. So, hopefully, this will work for you. This example was done using Macs running OS X 10.10 (Yosemite). Your mileage may vary.

Installing pygame

Go to the pygame downloads page and scroll down to the Mac section.

Find the download titled Lion apple supplied python: pygame-1.9.2pre-py2.7-macosx10.7.mpkg.zip and download and install it.

It says Lion, but it will work with Yosemite.

Creating a short sample pygame

Just so you can see how it works basically (and then later on, you can create/tweak your own games), here’s one you can start with.

Open up a text editor (e.g., a terminal editor like nano or a graphical one like TextWrangler—avoid TextEdit, unless you know the difference between plain text and rich text).

Paste into the text editor the following:

import sys, pygame
pygame.init()

size = width, height = 320, 240
speed = [2, 2]
black = 0, 0, 0

screen = pygame.display.set_mode(size)

ball = pygame.image.load("ball.gif")
ballrect = ball.get_rect()

while 1:
        for event in pygame.event.get():
                if event.type == pygame.QUIT: sys.exit()

        ballrect = ballrect.move(speed)
        if ballrect.left < 0 or ballrect.right > width:
                speed[0] = -speed[0]
        if ballrect.top < 0 or ballrect.bottom > height:
                speed[1] = -speed[1]

        screen.fill(black)
        screen.blit(ball, ballrect)
        pygame.display.flip()

Save it to your desktop as pygametest.py

Then, save this beach ball image file to your desktop as well.

In Terminal.app (which you can find in /Applications/Utilities or using Spotlight), paste in this command:

cd ~/Desktop

This will change focus to your desktop directory (that’s where you saved your Python script and your beach ball image).

Paste this command in next to run your script:

python pygametest.py


If it worked, you should see a beach ball bouncing around a black background.

Credit where credit’s due

I didn’t make up this tutorial out of thin air. This is a synthesis of a couple of online resources I found.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *