如何清除screen.blit()绘制内容?实现通知弹窗自动清除功能
解决Pygame通知弹窗自动清除的问题
首先别用time.sleep(),这玩意儿会卡住整个游戏循环,界面直接僵住,用户体验烂得一批。正确的思路是记录弹窗的显示时长,在主循环里判断是否到时间,到了就不再绘制弹窗。
具体步骤:
- 初始化弹窗相关变量:比如
show_notification = False,notification_start_time = 0,notification_duration = 3000(毫秒,也就是3秒) - 触发通知时,把
show_notification设为True,同时用pygame.time.get_ticks()记录当前时间 - 主循环里先绘制游戏基础内容(背景、其他元素),如果
show_notification为True,计算当前时间与开始时间的差值:差值小于时长就绘制弹窗,超过时长就把show_notification设为False,停止绘制
给你个简单的代码示例:
import pygame pygame.init() screen = pygame.display.set_mode((800, 600)) clock = pygame.time.Clock() bg_color = (255, 255, 255) # 创建通知表面 notification_surf = pygame.Surface((200, 100)) notification_surf.fill((200, 0, 0)) # 添加通知文本 font = pygame.font.SysFont(None, 36) text_surf = font.render("通知内容", True, (255, 255, 255)) notification_surf.blit(text_surf, (20, 30)) show_notification = False notification_start = 0 notify_duration = 3000 # 显示3秒 running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 按下空格键触发通知 if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: show_notification = True notification_start = pygame.time.get_ticks() # 先绘制背景,覆盖之前的画面 screen.fill(bg_color) # 处理通知显示逻辑 if show_notification: current_time = pygame.time.get_ticks() if current_time - notification_start < notify_duration: screen.blit(notification_surf, (300, 250)) else: show_notification = False pygame.display.flip() clock.tick(60) pygame.quit()
核心逻辑就是:每次循环先画背景覆盖旧画面,通知在有效期内就叠加绘制,超时就停止绘制,自然就消失了。
如果不想全量重绘背景,也可以在显示弹窗前保存弹窗区域的背景,超时后再把保存的背景画回去,但这种方法复杂度高,一般小游戏直接全量重绘就够用。
内容的提问来源于stack exchange,提问作者HIpex
相关产品推荐
相关产品推荐

