pygame
本身并不直接支持将动画保存为 GIF,但可以用 Pillow
将截图的图像合成一个 GIF。
import pygame
import sys
from PIL import Image, ImageSequence
import os
# 初始化 pygame
pygame.init()
# 设置窗口大小
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# 设置窗口标题
pygame.display.set_caption("移动的小球")
# 定义颜色
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 小球的初始位置和速度
ball_x, ball_y = WIDTH // 2, HEIGHT // 2
ball_speed_x, ball_speed_y = 5, 5
ball_radius = 20
# 帧数和帧率
frame_count = 0
max_frames = 100 # 总帧数
frame_rate = 60 # 每秒帧数
# 创建一个临时文件夹来保存帧
os.makedirs("frames", exist_ok=True)
# 游戏主循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 更新小球的位置
ball_x += ball_speed_x
ball_y += ball_speed_y
# 检测边界碰撞
if ball_x - ball_radius <= 0 or ball_x + ball_radius >= WIDTH:
ball_speed_x = -ball_speed_x
if ball_y - ball_radius <= 0 or ball_y + ball_radius >= HEIGHT:
ball_speed_y = -ball_speed_y
# 绘制背景
screen.fill(WHITE)
# 绘制小球
pygame.draw.circle(screen, RED, (ball_x, ball_y), ball_radius)
# 保存当前帧为图像
if frame_count < max_frames:
frame_filename = f"frames/frame_{frame_count:04d}.png"
pygame.image.save(screen, frame_filename)
frame_count += 1
# 更新屏幕显示
pygame.display.flip()
# 控制帧率
pygame.time.Clock().tick(frame_rate)
# 如果达到最大帧数,退出循环
if frame_count >= max_frames:
running = False
# 退出 pygame
pygame.quit()
# 使用 Pillow 将帧合成 GIF
frames = [Image.open(f"frames/frame_{i:04d}.png") for i in range(max_frames)]
frames[0].save("animation.gif", save_all=True, append_images=frames[1:], duration=1000 // frame_rate, loop=0)
# 删除临时文件夹
import shutil
shutil.rmtree("frames")
print("动画已保存为 animation.gif")