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

如何实现文本游戏中角色从Great Hall到Bedroom的房间移动?

实现文本游戏的房间移动功能

你的代码目前存在两个关键问题导致无法实现房间移动:

  • 方向判断逻辑错误:if direction == 'North' or 'South' or 'East' or 'West'的写法不成立,因为逻辑判断会把'South'这类字符串直接视为真值,所以无论输入什么都会进入这个分支。
  • 缺少移动逻辑:没有根据输入的方向,从rooms字典中获取目标房间并更新角色位置。

以下是修改后的完整代码:

rooms = {
        'Great Hall': {'South': 'Bedroom'},
        'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
        'Cellar': {'West': 'Bedroom'}
    }

directions = ['North', 'South', 'East', 'West']
location = 'Great Hall'
Inventory = []

print("Welcome to Trials of Harvest. You can go North, East, South, or West. Type 'Exit' to leave the game.")


while True: # gameplay loop
    print('You are in the ', location)
    print('------------------------------')
    direction = input("Type North, East, South, West, or Exit. ").strip()  # 去掉输入的首尾空格,避免误判
    
    if direction == "Exit":
        print('Thanks for playing!')
        break  # 用break退出循环比exit()更稳妥
    
    if direction in directions:
        # 检查当前房间是否能往该方向移动
        if direction in rooms[location]:
            # 更新位置为目标房间
            location = rooms[location][direction]
        else:
            print(f"You can't go {direction} from here!")
    else:
        print('Invalid Direction!!')

关键修改说明:

  1. 修正方向判断:改用direction in directions来判断输入是否为有效方向,逻辑更简洁准确。
  2. 添加移动逻辑:
    • 先检查当前房间的可用方向中是否包含输入的方向
    • 如果包含,就从rooms字典中取出对应的目标房间,更新location变量
    • 如果不包含,提示玩家无法往该方向移动
  3. 优化退出逻辑:用break代替exit(),更符合Python循环的常规退出方式
  4. 输入处理:给input()结果加上.strip(),避免玩家输入前后空格导致的误判

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 10:08:22