Pygame记忆游戏如何校验不同背景下击中的气球是否一致
问题原因分析
- 触发对比的时机错误:你当前在游戏主循环中只要
scene_1_balloons_popped和scene_2_balloons_popped都不为空就会触发对比,逻辑误判会直接触发错误的失败提示 - 击中索引添加逻辑顺序错误:你在
check_collisions函数中先翻转了bg_bool背景状态,再把当前击中的气球索引存入对应列表,导致第一背景的最后一个击中索引被错误存入第二背景的列表,直接触发两边都有值的对比逻辑 - 对比逻辑本身有冗余:不需要自己写循环逐位对比,Python原生支持列表直接用
==判断元素和顺序是否完全一致
修复方案
第一步:修正击中索引的添加顺序
修改check_collisions函数内的击中处理逻辑,先存储当前击中的索引,再判断是否需要切换背景:
if gun_mask.overlap(balloon_mask, offset): hit = True num_balloons -= 1 num_hits += 1 number_of_balloons_popped += 1 # 先存当前击中的气球索引到对应背景列表 if bg_bool == False: # bg_bool=False对应第一张背景 scene_1_balloons_popped.append(i) else: scene_2_balloons_popped.append(i) # 再判断是否需要切换背景 num_hits_needed = num_balloon_list[balloon_list_index] game_end = balloon_list_index == len(num_balloon_list) - 1 if num_hits == num_hits_needed and not game_end: num_balloons += num_hits num_hits = 0 balloon_list_index += 1 bg_bool = not bg_bool break
第二步:替换主循环中的对比逻辑
删掉你原来主循环里的错误对比代码,换成以下逻辑,仅当第二背景阶段击中数量和第一背景相等时才触发校验:
# 仅第二背景阶段、两边击中数量相等且不为空时才校验匹配结果 if bg_bool == True and len(scene_2_balloons_popped) == len(scene_1_balloons_popped) and len(scene_1_balloons_popped) > 0: if scene_1_balloons_popped == scene_2_balloons_popped: # 匹配成功得分+1,清空列表进入下一轮 score += 1 scene_1_balloons_popped.clear() scene_2_balloons_popped.clear() else: # 匹配失败触发结束逻辑 you_lost() pg.display.update() # 等待2秒展示失败提示后退出,可按需调整时长 pg.time.delay(2000) running = False
内容的提问来源于stack exchange,提问作者Krishay Rastogi
相关产品推荐
相关产品推荐

