Python如何判断列表全部元素存在于另一列表,解决游戏获胜判定异常问题
小游戏逻辑问题修复方案
问题根源
你写的获胜判定逻辑顺序错误:遍历必要道具列表时,只要第一个道具wallet存在于背包中,就会直接触发获胜判定并退出程序,完全不会继续校验剩余的两个道具card和ring,所以只集齐wallet和ring就会被判赢。
直接修复版本(仅改判定逻辑)
把mall函数里的判定代码改成如下即可:
def mall(): endgame = {"wallet", "card", "ring"} print('you are about to get a taxi to the pawn shop. do you have everything you need?') answer = input() print(inventory) if answer == 'yes': # 用集合对比直接判断是否集齐全部道具,代码更简洁不会出错 if set(inventory) >= endgame: print("you won") sys.exit() else: print("you lose") sys.exit() else: print("you lose") sys.exit()
更优的整体重构方案
原来的代码里有大量重复的房间逻辑,还有很多没用的死循环(每个房间里的while pickup永远不会循环,因为代码直接跳转下一个房间了),可以简化成如下版本:
import sys inventory = set() # 用集合存道具,判断包含关系效率更高 # 把所有房间配置抽成列表,不用重复写几乎一样的函数 room_config = [ ("living room", "card"), ("bedroom", "wallet"), ("bathroom", "ring") ] def run_room(room_name, item): print(f'you are in a {room_name}, you see a {item}. Pick it up?') pickup = input().strip().lower() if pickup == 'yes': inventory.add(item) else: print(f"you didnt pick up the {item}") def mall(): required_items = {"wallet", "card", "ring"} print('you are about to get a taxi to the pawn shop. do you have everything you need?') answer = input().strip().lower() print(f"your inventory: {list(inventory)}") if answer == 'yes' and inventory >= required_items: print("you won") else: print("you lose") sys.exit() # 游戏主流程 for room_info in room_config: run_room(*room_info) mall()
这个版本的优势:
- 没有冗余重复代码,新增房间只要在
room_config里加一行配置就行 - 用集合存道具,判定集齐的逻辑一行就写完,不会出现遍历顺序错误的问题
- 删掉了所有没用的死循环代码,逻辑更清晰
内容的提问来源于stack exchange,提问作者BlueberryWine
相关产品推荐
相关产品推荐

