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

Python文本游戏current_room更新后显示未同步问题求助

房间移动游戏显示不同步问题解决

你写的房间移动游戏里,current_room变量更新后,显示的当前房间位置却没跟着变化——初始在'Great Hall'时显示正常,但玩家输入方向移动后,显示的位置还是初始值。

原代码

#A dictionary for the simplified dragon text game
#The dictionary links a room to other rooms.
rooms = {
        'Great Hall': {'South': 'Bedroom'},
        'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
        'Cellar': {'West': 'Bedroom'}
    }

player_move = '' # set player direction at blank value
current_room = 'Great Hall' # set starting room

# variables for text displays
direction_prompt = "Enter the direction you would like to go or " \
            "\nYou can type 'Exit' to end the game\n > "
error_prompt = "Not a valid entry!"
location_prompt = f'You are in the {current_room}\nThe directions you can go are:'



while player_move != 'Exit': # set game loop to continue until player enters 'exit'
    # display available directions
    available_directions = rooms[current_room].keys() 
    print(f'\n{location_prompt}\n', *available_directions) 

    # prompt a player to enter a direction (or quit game)
    player_move = input(direction_prompt).capitalize()  

    if player_move in available_directions:
        current_room = rooms[current_room][player_move]
    
    elif player_move != 'Exit':
        print(error_prompt)

    else:
        break
    
print('Game Over')

问题原因

问题出在location_prompt的定义时机上:这个变量是在循环外部用f-string定义的,它只会在程序启动时,用当时的current_room初始值生成一次固定字符串。之后哪怕current_room随着玩家移动更新了,location_prompt的内容也不会自动刷新。

解决方法

把location_prompt的赋值语句移到while循环内部,让它每次循环都重新生成,这样就能获取最新的current_room值。同时把提示文本和注释翻译成中文,更符合使用习惯:

# 简化版龙文本游戏的房间字典
# 字典存储每个房间可通往的其他房间
rooms = {
        'Great Hall': {'South': 'Bedroom'},
        'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
        'Cellar': {'West': 'Bedroom'}
    }

player_move = '' # 初始化玩家移动指令为空
current_room = 'Great Hall' # 设置初始房间为大厅

# 文本提示变量
direction_prompt = "请输入你要前往的方向,或者\n输入'Exit'结束游戏\n > "
error_prompt = "输入无效!"


while player_move != 'Exit': # 游戏循环,直到玩家输入Exit结束
    # 每次循环重新生成位置提示,确保使用最新的当前房间
    location_prompt = f'你现在在{current_room}\n可前往的方向有:'
    # 获取当前房间的可用方向
    available_directions = rooms[current_room].keys() 
    print(f'\n{location_prompt}\n', *available_directions) 

    # 提示玩家输入方向或退出
    player_move = input(direction_prompt).capitalize()  

    if player_move in available_directions:
        current_room = rooms[current_room][player_move]
    
    elif player_move != 'Exit':
        print(error_prompt)

    else:
        break
    
print('游戏结束')

效果说明

修改后,每次循环开始都会根据最新的current_room生成位置提示,玩家移动后,下一次循环显示的当前房间就会同步更新,不会再出现显示和实际位置不符的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 14:03:23