Michelle Chen 技術雜談:How To Install Pygame for Python 3 on Mac

Facebook Twitter LinkedIn LINE Skype EverNote GMail Yahoo Email

If you need to develop Python 3 application in Pygame on Mac, you should have noticed that there is no official installer of Pygame for Python 3 on Mac. However, you can still install Pygame for Python 3, just via Pygame repository.

If you do not want bother the details, you may use my modified Pygame formula for Homebrew to install Pygame. Remember to install HEAD version or Python 3 will not be supported.

$ mv pygame.rb /usr/local/Library/Formula
# With modified Pygame formula...
$ brew install pygame --with-python3 --with-HEAD
{{< / highlight >}}

If you want to install Pygame with `pip`, I still suggest Homebrew to install dependencies for Pygame.  To install Homebrew, follow [Homebrew official site](http://brew.sh/) or [my article]({{ site.url }}osx/2014/08/05/homebrew/).  After installation of Homebrew, you can install other software.

Install Mercurial, a version control software.  We will use Mercurial to download Pygame source code later.

$ brew install mercurial
{{< / highlight >}}

Install Python 3, since there is no Python 3 on Mac.  Installing Python 3 with Homebrew is suggested because Homebrewed Python 3 modules are placed in the subdirectories of */usr/local* and root priviledge is not needed.

$ brew install python3
{{< / highlight >}}

Install some dependencies including *jpeg*, *libpng*, *portmidi*, *smpeg* and *numpy*.  *smpeg* is in "head-only", meaning that there is no stable version tarballs.  You have to `brew tap homebrew/headonly` before installing *smpeg*.  Besides, remember to add Python 3 support for *numpy*.

# Install smpeg
$ brew tap homebrew/headonly
$ brew install smpeg

# Install numpy with Python 3 support
$ brew install numpy --with-python3

# Install jpeg, libpng and portmidi
$ brew install jpeg libpng portmidi
{{< / highlight >}}

Install SDL (Simple DirectMedia Layer), a cross-platform library for multimedia and game.  You need to install *sdl*, *sdl_image*, *sdl_mixer* and *sdl_ttf*.

$ brew install sdl sdl_image sdl_mixer sdl_ttf
{{< / highlight >}}

Install Pygame with `pip3`.  Be not confused with `pip`, which is for Python 2.

$ pip3 install hg+https://bitbucket.org/pygame/pygame
{{< / highlight >}}

Finally, test Pygame with a small code snippet:

import pygame, sys

from pygame.locals import *

DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
{{< / highlight >}}