import pygame
# 初始化 Pygame
pygame.init()
# 定义初始窗口大小
screen_width, screen_height = 800, 600
# 创建可调整大小的窗口
screen = pygame.display.set_mode((screen_width, screen_height), pygame.RESIZABLE)
pygame.display.set_caption("预渲染并缓存静态元素 - 支持窗口调整")
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 创建一个缓存 Surface,用于预渲染静态元素
def create_cache_surface(width, height):
cache_surface = pygame.Surface((width, height))
cache_surface.fill(BLACK)
pygame.draw.rect(cache_surface, RED, (50, 50, 200, 100)) # 绘制一个红色矩形
pygame.draw.circle(cache_surface, GREEN, (width // 2, height // 2), 50) # 绘制一个绿色圆形
pygame.draw.line(cache_surface, WHITE, (100, 100), (width - 100, height - 100), 5) # 绘制一条白色线段
return cache_surface
# 初始创建缓存 Surface
cache_surface = create_cache_surface(screen_width, screen_height)
# 主循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.VIDEORESIZE:
# 窗口大小改变时,更新窗口尺寸并重新创建缓存 Surface
screen_width, screen_height = event.size
screen = pygame.display.set_mode((screen_width, screen_height), pygame.RESIZABLE)
cache_surface = create_cache_surface(screen_width, screen_height)
# 每帧直接绘制缓存的 Surface
screen.blit(cache_surface, (0, 0))
# 更新屏幕
pygame.display.flip()
# 退出 Pygame
pygame.quit()
DeepSeek对预渲染的解读: