我们通过使用pygame模块,创建一些带有图形和声音的、更有趣的高级游戏。
目录
主要内容
以下是主要内容
- 安装pygame
- pygame中的颜色和字体
- 锯齿图像和抗锯齿图像
- 属性
- 数据类型pygame.font.Font、pygame.Surface、pygame.Rect和pygame.PixelArray
- 构造函数
- pygame的绘制函数
- Surface对象的blit()方法
- 事件
pygame
Pygame是一个利用SDL(Simple DirectMedia Layer)库编写的游戏库,SDL是一位叫做Sam Lantinga的大牛写的,据说他为了让Loki(致力于向Linux上移植Windows的游戏的一家大好人公司,可惜已经倒闭)更有效的工作,创造了这个东东。
SDL是用C写的,不过它也可以使用C++进行开发,当然还有很多其它的语言,Pygame就是Python中使用它的一个库。Pygame已经存在很多时间了,许多优秀的程序员加入其中,把Pygame做得越来越好。
pygame官网提供了不同系统下面安装的相关命令,都是免费的。笔者选择的是Windows。当然,在安装pygame之前,你的Windows里需要安装好Python以及配置好环境变量。注意版本要对应上,笔者电脑里的是64位的Python3.7。
Windows安装pygame
因为笔者之前有安装过anaconda,所以这里使用anaconda进行安装。
- 进入https://anaconda.org/,在Search Anaconda Cloud中搜索pygame
2.回车进入页面后,一般选择下载最多的打开
3.复制命令行,进入CMD终端运行。
4.完成安装。可以通过编译环境检测是否安装成功,这里以IDLE为例,输入命令import pygame,出现以下信息,则证明导入成功。
>>> import pygame
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
这里仅以anaconda为例,当然还有其他的安装方法,pip也是可以的。
使用pygame
pygame有很多的模块,下面是一些常用的模块
name | function |
pygame.Color | color representations |
pygame.display | control the display window and screen |
pygame.draw | draw shapes |
pygame.event | interacting with events and queues |
pygame.font | loading and rendering fonts |
pygame.image | image transfer |
pygame.key | work with the keyboard |
pygame.locals | various constants |
pygame.mixer | load and play sounds |
pygame.mouse | pygame.mouse |
pygame.Rect | storing rectangular coordinates |
pygame.surface | representing images |
pygame.time | monitoring time |
pygame.mixer.music | control streamed audio |
有些模块可能在某些平台上不存在,你可以用None来测试一下。
import pygame
if pygame.Color is None:
print('This module is None')
else:
print('This module is in the module')
如果存在的话会有以下运行结果
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
This module is in the module
接下来我们将会用pygame写第一个Hello World程序。
pygame Hello World
我们将分析pygame Hello World程序的代码,看看它们做些什么事情。
(一)导入模块
import pygame
import sys
from pygame.locals import *