You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python文本冒险游戏:rooms字典移入main函数及代码优化求助

Python文本冒险游戏问题解决与优化方案

一、解决rooms字典移入main函数的报错问题

当你将全局rooms字典移到main函数内部后,其他依赖该字典的函数(如show_status)无法直接访问它,这是报错的核心原因。解决思路是通过函数参数传递rooms及相关游戏状态变量,或者用类封装状态(更推荐的方式)。

基础修复示例(参数传递)

def show_status(current_room, rooms, inventory):
    # 完善后的状态展示逻辑
    print(f"=== 当前状态 ===")
    # 显示当前房间名称
    print(f"当前房间: {rooms[current_room]['name']}")
    # 显示房间物品(处理空物品情况)
    room_items = rooms[current_room]['items']
    print(f"房间物品: {', '.join(room_items) if room_items else '无'}")
    # 显示背包(处理空背包情况)
    print(f"背包: {', '.join(inventory) if inventory else '空'}")
    # 显示可移动方向
    print(f"可移动方向: {', '.join(rooms[current_room]['directions'].keys())}")
    print("===============")

def main():
    # 在main内部定义rooms字典
    rooms = {
        'hall': {
            'name': '大厅',
            'items': ['青铜钥匙'],
            'directions': {'north': 'bedroom', 'east': 'kitchen'}
        },
        'bedroom': {
            'name': '卧室',
            'items': ['手电筒'],
            'directions': {'south': 'hall', 'west': 'balcony'}
        },
        'kitchen': {
            'name': '厨房',
            'items': [],
            'directions': {'west': 'hall'}
        },
        'balcony': {
            'name': '阳台',
            'items': ['生锈的小刀'],
            'directions': {'east': 'bedroom'}
        }
    }
    current_room = 'hall'
    inventory = []
    
    while True:
        # 调用show_status时传入所需参数
        show_status(current_room, rooms, inventory)
        action = input("输入指令(go 方向/take 物品/quit): ").strip().lower()
        
        if action.startswith('go '):
            parts = action.split()
            if len(parts) < 2:
                print("请输入正确格式:go 方向(如 go north)")
                continue
            direction = parts[1]
            if direction in rooms[current_room]['directions']:
                current_room = rooms[current_room]['directions'][direction]
                print(f"你向{direction}走去...")
            else:
                print("这个方向走不通!")
        elif action.startswith('take '):
            parts = action.split()
            if len(parts) < 2:
                print("请输入正确格式:take 物品(如 take 钥匙)")
                continue
            item = parts[1]
            if item in rooms[current_room]['items']:
                inventory.append(item)
                rooms[current_room]['items'].remove(item)
                print(f"你拿起了{item}")
            else:
                print("房间里没有这个物品!")
        elif action == 'quit':
            print("游戏结束,再见!")
            break
        else:
            print("无效指令,请重新输入!")

if __name__ == "__main__":
    main()

二、代码优化建议

1. 用类封装游戏状态(更易维护扩展)

把rooms、current_room、inventory等状态封装成类的实例属性,避免频繁传递参数,代码结构更清晰:

class AdventureGame:
    def __init__(self):
        self.rooms = {
            'hall': {'name': '大厅', 'items': ['青铜钥匙'], 'directions': {'north': 'bedroom', 'east': 'kitchen'}},
            'bedroom': {'name': '卧室', 'items': ['手电筒'], 'directions': {'south': 'hall', 'west': 'balcony'}},
            'kitchen': {'name': '厨房', 'items': [], 'directions': {'west': 'hall'}},
            'balcony': {'name': '阳台', 'items': ['生锈的小刀'], 'directions': {'east': 'bedroom'}}
        }
        self.current_room = 'hall'
        self.inventory = []
    
    def show_status(self):
        print(f"=== 当前状态 ===")
        print(f"当前房间: {self.rooms[self.current_room]['name']}")
        room_items = self.rooms[self.current_room]['items']
        print(f"房间物品: {', '.join(room_items) if room_items else '无'}")
        print(f"背包: {', '.join(self.inventory) if self.inventory else '空'}")
        print(f"可移动方向: {', '.join(self.rooms[self.current_room]['directions'].keys())}")
        print("===============")
    
    def run(self):
        while True:
            self.show_status()
            action = input("输入指令(go 方向/take 物品/quit): ").strip().lower()
            if action.startswith('go '):
                parts = action.split()
                if len(parts) < 2:
                    print("格式错误:请输入 go + 方向(如 go north)")
                    continue
                direction = parts[1]
                if direction in self.rooms[self.current_room]['directions']:
                    self.current_room = self.rooms[self.current_room]['directions'][direction]
                    print(f"你向{direction}移动了")
                else:
                    print("此路不通!")
            elif action.startswith('take '):
                parts = action.split()
                if len(parts) < 2:
                    print("格式错误:请输入 take + 物品(如 take 钥匙)")
                    continue
                item = parts[1]
                if item in self.rooms[self.current_room]['items']:
                    self.inventory.append(item)
                    self.rooms[self.current_room]['items'].remove(item)
                    print(f"你获得了{item}")
                else:
                    print("该物品不存在!")
            elif action == 'quit':
                print("游戏结束!")
                break
            else:
                print("指令无效,请重新输入")

if __name__ == "__main__":
    game = AdventureGame()
    game.run()

2. 其他优化点

  • 外置房间数据:把rooms字典保存为JSON文件,通过json.load()读取,方便修改房间配置而无需改动代码。
  • 增加指令提示:当用户输入错误时,显示可用指令列表,提升体验。
  • 物品使用功能:扩展use指令,允许玩家使用背包中的物品(如用钥匙打开门)。
  • 状态持久化:通过文件保存玩家进度,下次启动可继续游戏。

内容的提问来源于stack exchange,提问作者angiemarie1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 17:01:18