位元詩人 技術雜談: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) 是資訊領域碩士,專注於從探索到產品的開發過程,並以工具驅動的方式改善專案。喜歡以開源專案作為成果,回饋社群。

主要方向包括:自用工具的打磨 (dogfooding)、編譯器前端在工具開發中的應用,以及將研究轉化為可維護的開源成果。

除了技術之外,也喜歡日本料理和黑咖啡,偶爾自助旅行,將生活中的靈感融入技術隨筆。