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

Python文本冒险游戏如何将核心玩法循环改写为要求的main()函数

修复后的实现代码

你之前报错的核心原因是player_stats函数依赖全局作用域的rooms、current_room、inventory变量,当你把这些变量和主循环放进main函数后,它们变成了main的局部变量,player_stats就无法访问到了。以下是符合要求的完整可运行代码:

def show_instructions():
    print('\nWelcome to Cat and Mouse Adventure Game!\n')
    print('Collect all 7 items to win the game, or else get eaten by the cat!')
    print('Move commands: go North, go South, go East, go West')
    print('Add item to Inventory: get \'item name\' ')

# 给player_stats增加入参,接收需要用到的变量,不再依赖全局变量
def player_stats(current_room, inventory, rooms):
    print('_' * 20)
    print('You are in the {}'.format(current_room))
    print('Inventory: ' + str(inventory))
    if 'item' in rooms[current_room]:
        print('You see ' + rooms[current_room]['item'])
    print('_' * 20)

def main():
    # 房间字典放在main函数内部,符合要求
    rooms = {
        'Living Room': {'South': 'Study', 'North': 'Kitchen', 'East': 'Bedroom', 'West': 'Bathroom'},
        'Bedroom': {'North': 'Dining Room', 'West': 'Living Room', 'South': 'Sunroom', 'item': 'Glasses'},
        'Dining Room': {'West': 'Kitchen', 'South': 'Bedroom', 'item': 'Napkin'},
        'Kitchen': {'South': 'Living Room', 'East': 'Dining Room', 'West': 'Basement', 'item': 'Cheese'},
        'Basement': {'East': 'Kitchen', 'South': 'Bathroom', 'item': 'Catnip'},
        'Bathroom': {'East': 'Living Room', 'North': 'Basement', 'South': 'Walk-in Closet', 'item': 'Water'},
        'Walk-in Closet': {'North': 'Bathroom', 'East': 'Study', 'item': 'Shoes'},
        'Study': {'North': 'Living Room', 'East': 'Sunroom', 'West': 'Walk-in Closet', 'item': 'Cotton'},
        'Sunroom': {'North': 'Bedroom', 'West': 'Study', 'item': 'Cat'}  # 反派所在房间
    }
    current_room = 'Living Room'
    inventory = []
    show_instructions()

    while True:
        # 调用player_stats的时候传入当前的三个局部变量
        player_stats(current_room, inventory, rooms)
        player_move = ''
        while player_move == '':
            player_move = input('Enter your move:\n').title()
        if player_move in ('Go North', 'Go South', 'Go East', 'Go West'):
            player_move = player_move[3:]
            if player_move not in rooms[current_room]:
                print('That is not a valid move, enter another.')
            else:
                current_room = rooms[current_room][player_move]
        elif player_move[0:3] == 'Get':
            if 'item' not in rooms[current_room] or player_move[4:] != rooms[current_room]['item']:
                print('Can\'t get {}!'.format(player_move[4:]))
            else:
                inventory.append(player_move[4:])
                print(player_move[4:] + ' retrieved!')
                del rooms[current_room]['item']
        elif player_move == 'Exit':
            print('Play again soon!')
            return

        if current_room == 'Sunroom':
            print('OH NO! The cat found you and ate you up!')
            print('GAME OVER!')
            return

        if len(inventory) == 7:
            print('\nCongratulations! You collected all 7 items to build a shelter and avoid the cat!')
            return

if __name__ == "__main__":
    main()

主要修改点

  • 为player_stats函数新增了3个入参,调用时直接传入main函数内的局部变量即可,彻底解决变量作用域报错问题
  • 所有游戏核心逻辑、房间字典、状态变量都封装在main函数内部,完全符合要求
  • 修复了原代码中Exit判断缩进错误、物品获取逻辑缩进错误的问题
  • 把全局终止的exit(0)替换成函数return,逻辑更规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:24:02