这篇主要是介绍一个最简单的动画——猫在跑。
import pygame,sys,time
from pygame.locals import *
# 初始化 pygame 库
pygame.init()
# 设置一个 400*400 像素的窗口
d = pygame.display.set_mode((400,400))
# 设置窗口的顶部标题,名为"cat is running"
pygame.display.set_caption("cat is running")
# 初始化 pygame.time.Clock 对象可以帮助我们确保程序以一定的最大 FPS 运行。这个 Clock 对象可通过在下面的 while 每次循环中稍作停顿来确保我们的游戏程序不会运行得太快。如果没有这些暂停,这里的 while 循环的动画效果将以计算机可以运行的速度运行,用户完全跟不上。
c = pygame.time.Clock()
# 初始化背景颜色
COLOR = (255,255,255)
# 初始化猫的 x 坐标
catx = 0
# 初始化猫的 y 坐标
caty = 0
# 初始化猫的 x 方向的移动速度
speedx = 5
# 初始化猫的 y 方向的移动速度
speedy = 5
# 初始化猫移动方向
direction = 'r'
# 加载猫的图片
cat = pygame.image.load("/Users/wys/Desktop/cat.png")
# 初始化 FPS,即下面的 while 循环会每秒执行 30 次
FPS = 30
# 保证程序一直运行不退出
while True:
# 背景色设置为 COLOR
d.fill(COLOR)
# 方向为向右移动
if direction == 'r':
catx+=speedx
if catx==275:
direction = 'd'
# 方向为向下移动
if direction == 'd':
caty+=speedy
if caty==320:
direction = 'l'
# 方向为向左移动
if direction == 'l':
catx-=speedx
if catx==0:
direction = 'u'
# 方向为向上移动
if direction == 'u':
caty-=speedy
if caty==0:
direction = 'r'
# 窗口上在 (catx,caty) 坐标上绘制猫的图像
d.blit(cat,(catx,caty))
# 遍历刚发生的事件
for event in pygame.event.get():
# 判断事件是否为退出
if event.type == QUIT:
# 终止 pygame 库
pygame.quit()
# 终止程序
sys.exit()
# 刷新窗口效果
pygame.display.update()
# 为 Clock 对象 c 设置 FPS,即 while 每秒执行 FPS 次
c.tick(FPS)
这里使用到的小猫图片可以从这里获取,像素是 125 * 79 。效果图如下: