Pygame计分函数显示函数地址而非计时分数问题求助
Pygame 计分显示异常问题修复
核心错误分析
- 你在
display_score函数里渲染文本时,错把函数本身display_score放进了字符串格式化语句中,导致显示的是函数对象的内存地址(也就是你看到的function display_score at 0x103e3ab90),而非实际的游戏耗时/分数。 display_score函数没有定义返回值,所以直接打印该函数的调用结果时,终端会输出None。
修复方案
- 替换渲染变量:把格式化字符串里的
display_score改成基于游戏耗时的变量(比如current_time)。 - 添加初始计时点:如果要计算游戏的实时运行时长,需要在游戏开始时记录初始时间,避免把Pygame启动到现在的总时间当成游戏耗时。
- 可选优化:如果后续需要复用分数数据,可以让函数返回计算后的分数值。
修正后的代码示例
1. 初始化计时变量
在游戏主循环外定义初始时间变量:
start_time = 0
2. 修正后的计分显示函数
def display_score(): # 计算游戏运行的耗时(转成秒数) current_time = (pygame.time.get_ticks() - start_time) // 1000 # 渲染分数文本,这里用耗时秒数作为分数 score_surf = myfont.render(f'Score: {current_time}', False, (64, 64, 64)) score_rect = score_surf.get_rect(center=(400, 50)) screen.blit(score_surf, score_rect) # 可选:返回分数值,方便后续逻辑调用 return current_time
3. 更新游戏激活逻辑
在游戏开始(或重新开始)时重置初始时间:
# 示例:按下空格键重新开始游戏 if not game_active and pygame.key.get_pressed()[pygame.K_SPACE]: game_active = True start_time = pygame.time.get_ticks() # 重置计时起点 if game_active: # Layouts screen.blit(sky,(0,0)) screen.blit(ground,(0,300)) # Player screen.blit(player,player_rect) gravity += 1 player_rect.y += gravity if player_rect.bottom >= 300: player_rect.bottom = 300 # Functions score = display_score() # 可接收返回的分数值,按需使用 # Snail screen.blit(snail,snail_rect) snail_rect.x -= 3 if snail_rect.right <= 0: snail_rect.left = 800 # collision if player_rect.colliderect(snail_rect): game_active = False else: screen.fill('Yellow')
额外说明
- 如果不需要复用分数,直接去掉
return current_time即可,不影响计分显示。 - 你可以根据需求调整计分规则,比如把秒数乘以10得到更高分数,或者结合其他游戏事件计算分数。
内容的提问来源于stack exchange,提问作者ıLikeJavaButİtsKindaMessy
相关产品推荐
相关产品推荐

