Pygame点击J键加分时旧分数残留无法覆盖如何解决?
问题核心原因
- 你在J键的触发逻辑中,调用完
score_increase()绘制了最新分数后,额外执行了一行screen.blit(surface, (0, 0)),此处的surface是代码最开始初始化时渲染的初始0分文本,相当于刚画完新分数又被旧分数覆盖,导致看起来旧文本残留。 - 事件判断逻辑层级错误,QUIT退出事件和ESC按键的判断被写在了KEYDOWN事件的分支内,导致关闭窗口、按ESC退出的功能失效。
- 重复创建字体对象没有必要,字体只需要全局初始化一次即可,不需要每次加分、渲染文本都重新创建。
修正方案
首先删掉J键触发逻辑里多余的screen.blit(surface, (0, 0))行,再调整事件判断的层级,优化重复创建字体的逻辑即可。
修正后完整代码
import pygame, sys, random from pygame.locals import * pygame.init() pygame.display.set_caption("waht da dog doin") screen = pygame.display.set_mode((800, 600)) bg_color = (35, 140, 120) text_color = (130, 46, 75) # 全局提前创建字体,不用重复生成 score_font = pygame.font.SysFont("Comic Sans", 50, True, False) troll_font = pygame.font.SysFont("Comic Sans", 30, True, True) tip_font = pygame.font.SysFont("Comic Sans", 50, True, False) screen.fill(bg_color) dog = pygame.image.load("resources/dog.jpg").convert() score = 0 # 初始分数渲染 surface = score_font.render(str(score), True, text_color) screen.blit(surface, (0, 0)) troll = ["corned", "balled", "chimkened", "torkelled", "kanaquined", "khazaqed", "bo burnam'd", "talal'd", "chammaked", "australiad", "lotto pie'd", "tetrised", "caca'd", "scrutinized", "bulbasaured"] troll_item = random.choice(troll) dog_y = random.randint(0, 400) dog_x = random.randint(0, 500) text_y = random.randint(0, 400) text_x = random.randint(0, 500) def score_increase(): global score score += 1 surface = score_font.render(str(score), True, text_color) pygame.draw.rect(screen, bg_color, (0, 0, 100, 75)) # 加宽覆盖区域,避免分数到两位数后覆盖不全 screen.blit(surface, (0, 0)) def print_trolled(): screen.fill(bg_color) screen.blit(dog, (dog_x, dog_y)) surface_text = troll_font.render("u have been" + " " + troll_item, True, text_color) screen.blit(surface_text, (text_x, text_y)) def start_print(): surface = tip_font.render("press 'j' plsz", True, text_color) screen.blit(surface, (250, 250)) start_print() while True: for event in pygame.event.get(): # 退出事件判断放到最外层,不要嵌套在KEYDOWN里 if event.type == QUIT: sys.exit() if event.type == KEYDOWN: if event.key == K_j: print_trolled() score_increase() # 删掉多余的旧surface绘制逻辑 dog_y = random.randint(0, 400) dog_x = random.randint(0, 500) text_y = random.randint(0, 400) text_x = random.randint(0, 500) troll_item = random.choice(troll) if event.key == K_ESCAPE: sys.exit() pygame.display.update()
额外优化说明
- 覆盖分数的矩形宽度从50调整到100,避免分数到两位数之后,文本宽度超过覆盖范围,还是出现残留
- 把重复用到的颜色、字体都提前提取成全局变量,减少冗余代码,运行效率更高
- 修正了
sys.exit后面漏加括号的问题,原来的写法不会触发退出
内容的提问来源于stack exchange,提问作者Annsh
相关产品推荐
相关产品推荐

