Pygame Tutorials
Import and Initialize
导入与初始化
by Pete Shinners
pete@shinners.org
Revision 1.0, January 28th, 2002
Getting pygame imported and initialized is a very simple process. It is also flexible enough to give you control over what is happening. Pygame is a collection of different modules in a single python package. Some of the modules are written in C, and some are written in python. Some modules are also optional, and might not always be present.
import和初始化pygame的步骤是十分简单的。整个过程也极其容易控制。pygame是由若干单独的python包构成的一组模块。一些是由c编写,一些是用python。有些模块是可选的,也许不总是可用的。
This is just a quick introduction on what is going on when you import pygame. For a clearer explanation definitely see the pygame examples.
这只是一个关于import pygame时会发生什么的简介。直接看pygame的事例会得到更清楚的解释。
Import
导入
First we must import the pygame package. Since pygame version 1.4 this has been updated to be much easier. Most games will import all of pygame like this. 首先我们要导入pygame的包。从pygame 1.4版本开始,这一切变得更简便了。几乎大多数游戏会像这样导入pygame:
import pygame from pygame.locals import *
只有第一行是必要的。它将所有可用的pygame模块导入pygame包之中。第二行是可选的。它将一些特殊常量和函数暴露于全局名字空间之中。
An important thing to keep in mind is that several pygame modules are optional. For example, one of these is the font module. When you "import pygame", pygame will check to see if the font module is available. If the font module is available it will be imported as "pygame.font". If the module is not available, "pygame.font" will be set to None. This makes it fairly easy to later on test if the font module is available.
必须知道的是,有些pygame模块是可选的。例如,字体模块。当你导入pygame时,pygame会检查字体模块是否存在。如果确定存在,它将被视作“pygame.font”导入。如果不存在,“pygame.font”会被设置为None。这样之后就很容易知道字体模块是否可用了。
Init
初始化
Before you can do much with pygame, you will need to initialize it. The most common way to do this is just make one call. 在用pygame开始其他工作前,你必须先去初始化它。通常这样调用一个函数就可以了。
pygame.init()
这样会尝试为你去初始化所有pygame模块。并不是所有pygame模块都需要被初始化,但这样做会自动的初始化那些必要的模块。当然,你也可以手动的去初始化每个pygame模块。例如,你可以像这样去初始化字体模块:
pygame.font.init()
需要注意的是,当你初始化pygame时如果发生了错误,程序会崩溃掉。当处理像这样的初始化时,出现错误会抛出一个异常的。任何一个需要被初始化的模块都有一个叫“get_init()”的函数。通过它可以知道这个模块是否已经完成了初始化。
safe to call the init() function for any module more than once.
多次调用任何模块的init()函数不会导致任何问题。
Quit
退出
Modules that are initialized also usually have a quit() function that will clean up. There is no need to explicitly call these, as pygame will cleanly quit all the initilized modules when python finishes. 需要被初始化的模块通常也有一个叫作“quit()”的函数用于善后事宜。它不需要主动地被调用,因为pygame在python结束清理时会自动清理初始化过的模块。