Python编写房间移动功能时无法按输入方向跳转问题求助
问题原因
- 核心错误:
while True内部嵌套了for current_room in rooms遍历循环,这个循环会强制把current_room按字典键的顺序依次赋值,完全覆盖了移动逻辑的修改,是房间按固定顺序跳转的根本原因。 - 初始值错误:初始
current_room赋值错误,你赋值的是rooms['Great Hall']也就是大礼堂对应的方向字典,实际上应该存储房间名称字符串,初始值应为current_room = 'Great Hall'。 - 返回值未接收:调用
move_rooms函数后没有接收返回值,函数返回的新房间名称没有赋值给current_room,移动操作不会生效。 - 函数逻辑冗余:
move_rooms函数内部第一行current_room = rooms[current_room]属于重复取值,容易搞混变量语义。
修正后可运行代码
rooms = { 'Great Hall': {'South': 'Bedroom'}, 'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'}, 'Cellar': {'West': 'Bedroom'} } # 初始赋值为房间名称字符串,而非方向字典 current_room = 'Great Hall' def move_rooms(current_room, direction): # 直接返回当前房间对应方向的目标房间即可 return rooms[current_room][direction] while True: print('You are in the', current_room) direction = input('Which way would you like to go: North, South, East, or West?') if direction in rooms[current_room]: # 接收函数返回的新房间名称,更新当前房间变量 current_room = move_rooms(current_room, direction) else: print('You cannot go that way.')
内容的提问来源于stack exchange,提问作者Nerdygirl8787
相关产品推荐
相关产品推荐

