Pygame是一个开源的跨平台的Python多媒体库,用于开发2D游戏和多媒体应用程序。它基于Simple DirectMedia Layer(SDL)库,提供了一系列用于图形、音频和输入处理的函数和类。Pygame能够使用硬件加速,使得游戏开发更加高效和快速。
import pygame
# 初始化模块
pygame.init()
# 构建窗体
screen = pygame.display.set_mode((500, 500))
# 填充背景色
screen_color = pygame.Color(125, 125, 125)
# 构建面填充色
surface1 = pygame.Surface((300, 300))
surface1_color = pygame.Color(125, 255, 125)
surface1_speed = 3
surface1_y = -300
# 引入时钟模块
clock = pygame.time.Clock()
# 绘制一个角色
surface2 = pygame.Surface((50, 50))
surface2_color = pygame.Color(125, 125, 255)
surface2.fill(surface2_color)
surface2_speed = 5
surface2_x = 0
# 主循环
while True:
clock.tick(20)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# 每一帧都是先刷背景
screen.fill(screen_color)
# 更新surface1的背景色
surface1.fill(surface1_color)
surface2_x += surface2_speed
if surface2_x > 300:
surface2_x = -50
surface1.blit(surface2, (surface2_x, 250))
surface1_y += surface1_speed
if surface1_y >= 500:
surface1_y = -300
# 绘制面(在某一个位置刷一个矩形)
screen.blit(surface1, (100, surface1_y))
# 更新绘制
pygame.display.flip()