如何在Pygame中沿窗口边框在不同坐标blit多个相同图像
现有代码核心问题
- 坐标生成逻辑仅覆盖左右侧边,没有覆盖上下边框,且未考虑图像本身宽高,容易出现图像超出窗口的问题
- 图片加载、缩放逻辑写在循环调用的
PlaceElon函数里,会重复执行造成不必要的性能损耗 - 没有全局存储所有已生成的目标坐标,每次绘制都会被背景覆盖,无法实现多个图像同时存在的效果
- blit传参格式错误,你构造的
Elonlist是嵌套列表,不符合blit要求的二维元组/列表格式
修改后可运行代码
import pygame, sys from pygame.locals import * import random pygame.init() DisplayWidth = 700 DisplayHeight = 400 Display = pygame.display.set_mode((DisplayWidth, DisplayHeight)) Death = False # 全局只加载一次素材 elon = pygame.image.load('elon.png') elonbig = pygame.transform.smoothscale(elon, (50, 54)) elon_w, elon_h = elonbig.get_size() # 存储所有elon的坐标 elon_positions = [] # 你要生成的elon总数量,可自行调整 ELON_COUNT = 10 # 预生成所有边框位置的坐标 for _ in range(ELON_COUNT): # 随机选四条边的其中一条 side = random.choice(['top', 'bottom', 'left', 'right']) if side == 'top': x = random.randint(0, DisplayWidth - elon_w) y = 0 elif side == 'bottom': x = random.randint(0, DisplayWidth - elon_w) y = DisplayHeight - elon_h elif side == 'left': x = 0 y = random.randint(0, DisplayHeight - elon_h) else: # right x = DisplayWidth - elon_w y = random.randint(0, DisplayHeight - elon_h) elon_positions.append((x, y)) # 预加载背景素材,避免重复加载 background = pygame.image.load('background.png') BigBackground = pygame.transform.smoothscale(background, (DisplayWidth, DisplayHeight)) def PlaceElon(): # 遍历所有坐标批量绘制 for pos in elon_positions: Display.blit(elonbig, pos) pygame.display.update() def RunGame(): global Death while not Death: # 事件处理必须加,不然窗口会无响应 for event in pygame.event.get(): if event.type == QUIT: Death = True pygame.quit() sys.exit() Display.blit(BigBackground, (0,0)) PlaceElon() RunGame()
关键修改说明
- 提前在全局预加载所有素材,避免游戏主循环重复执行IO和缩放操作,大幅提升运行效率
- 增加了四条边框的随机选择逻辑,同时减去图像本身的宽高做边界校验,保证图像完整展示在边框位置
- 用全局列表
elon_positions存储所有预生成的坐标,批量绘制即可实现多个图像同时展示在边框的需求 - 补充了pygame必须的退出事件处理逻辑,避免运行时窗口无响应
- 如果你需要每次界面刷新都更换新的随机边框位置,只需把
elon_positions的生成逻辑移动到PlaceElon函数内部,每次绘制前重新生成坐标即可
内容的提问来源于stack exchange,提问作者Unexperienced dude 69
相关产品推荐
相关产品推荐

