位元詩人 技術雜談: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.

```console
$ 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.

```console
$ 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*.

```console
# 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*.

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

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

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

Finally, test Pygame with a small code snippet:

```python
import pygame, sys

from pygame.locals import *

pygame.init()
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:
            pygame.quit()
            sys.exit()
    pygame.display.update()
{{< / highlight >}}
關於作者

身為資訊領域碩士,位元詩人 (ByteBard) 認為開發應用程式的目的是為社會帶來價值。如果在這個過程中該軟體能成為永續經營的項目,那就是開發者和使用者雙贏的局面。

位元詩人喜歡用開源技術來解決各式各樣的問題,但必要時對專有技術也不排斥。閒暇之餘,位元詩人將所學寫成文章,放在這個網站上和大家分享。