I find the best way to understand a new library is to jump straight into an example.
前面我们已经学习了python的基础知识,那么现在需要进行 实践。
我们从 pygame 出发,通过游戏来激发 使用 python的 乐趣
pip 命令
pip是用来方便地管理Python的第三方包的,安装python的时候就已经安装了这些东西
如果没有pip,可以使用 easy_install.exe 来进行安装
easy_install.exe pip
安装Pygame库
使用 pip 命令进行下载
pip --version
pip install pygame
Pygame更多内容
这里有比较丰富的内容,包括介绍我们如何安装 pygame
说明了安装 pygame 最好的方式就是 使用 pip,
当然还有其他各种安装方式可以参考:https://www.pygame.org/wiki/GettingStarted#Pygame%20Installation
也告诉我们使用 --user flag 之后 是安装到了 home directory
python -m pip install -U pygame --user
测试一下 pygame是起总用了 没
python -m pygame.examples.aliens
pygame介绍
继续从 https://www.pygame.org/docs/tut/PygameIntro.html
这里有一个简单的例子供我们参考一下
关于一个移动球的游戏,之前学过 swing 的时候我们知道如何进行动画的绘制
在死循环中,每次增加偏移量然后重新绘制
这里有几个用法
初始化
pygame.init()
得到一个图片显示窗口
screen = pygame.display.set_mode(size)
加载图片
ball = pygame.image.load("intro_ball.gif")
得到图片的矩形坐标
ballrect = ball.get_rect()
(Rect是用于存储矩形坐标的pygame对象)
通过 rect对象可以操作我们的图片移动
ballrect.move(speed) 其中 speed是一个列表
得到pygame的事件
pygame.event.get()
重新绘制
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
我们看看给出的例子:
import sys, pygame
pygame.init()
size = width, height = 320, 240
speed = [2, 2]
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load("intro_ball.gif")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
然后将图片 intro_ball.gif 放到我们程序的目录文件夹下面
运行程序
pygame 的模块
上面的例子就是使用 display模块
cdrom | playback |
cursors | load cursor images, includes standard cursors |
display | control the display window or screen |
draw | draw simple shapes onto a Surface |
event | manage events and the event queue |
font | create and render TrueType fonts |
image | save and load images |
joystick | manage joystick devices |
key | manage the keyboard |
mouse | manage the mouse |
sndarray | manipulate sounds with numpy |
surfarray | manipulate images with numpy |
time | control timing |
transform | scale, rotate, and flip images |
pygame使用
导入
import pygame
from pygame.locals import *
第一行是符合我们前面 模块的用法的
第二行呢,将一些 常量和函数导入到我们当前脚本的 全局命名空间之内
初始化
pygame.init()
pygame.font.init()
第一行对所有的pygame module 进行初始化
第二行可以 指定某个 pygame的模块 进行初始化 这里是对 font 进行了初始化
加载资源
加载图片 pygame.image
image = pygame.image.load(fullname)
image.set_colorkey(colorkey, RLEACCEL)
imagerect = image.get_rect()
图片通过 get_rect() 方法得到矩形对象
加载音频文件
sound = pygame.mixer.Sound(fullname)
鼠标点击位置
pos = pygame.mouse.get_pos()
rect.midtop = pos
更多的仔细研读下
上的内容