I am creating a text based adventure game for a class and having trouble getting my inventory system to work

huangapple go评论125阅读模式
英文:

I am creating a text based adventure game for a class and having trouble getting my inventory system to work

问题

以下是您要翻译的内容:

"对于上一周在我的课堂上的作业,我们必须创建一个简单的工作游戏,允许移动房间。 我已经将该代码调整到我的游戏代码中,似乎可以正常工作,甚至将'Item'添加到我的字典中也没有问题。 但是,一旦我尝试将物品添加到库存并引用库存列表到字典键,就会出现'不可散列'错误。 我查了一下,但唯一清除错误的方法是使用元组,但元组是不可变的,所以我无法像我理解的那样将物品添加到库存。 任何指导或建议都将不胜感激!

这是迄今为止的整个代码,一切都正常工作,直到我尝试添加一个单独的玩家库存。 我还没有添加游戏结束代码,所以我意识到我有一个无限循环,但我想在添加结束之前使库存工作,因为库存必须包括所有物品才能获胜。"

英文:

For the previous week's assignment in my class we had to create a simple, working game that allowed moving rooms. I have adjusted that code into my game code and it seems to work fine, even with the addition of 'Item' into my dictionary. Once I try to add to the inventory and reference the inventory list to the dictionary keys I get an 'unhashable' error. I looked this up but the only way to clear the error is to use a tuple, but a tuple is immutable so I wouldn't be able to add to the inventory, at least as I understand it. Any guidance or suggestions is much appreciated!

def player_instructions():
    # main menu and game commands
    print('Move Commands: go North, go South, go West, go East')
    print("Add to inventory: get 'item name'.")
    print('-' * 50)


print('A Paladin Adventure Game.')  # game opening greeting
print('Collect 7 items to win the game,')
print('or be destroyed by the Vampire Lord.')
print('-' * 50)

# dictionary for rooms and movement between
castle_rooms = {'Entry Hall': {'East': 'Great Hall', 'South': 'Solar', 'Item': ''},
                'Great Hall': {'West': 'Entry Hall', 'South': 'Boudoir',
                               'North': 'Kitchen', 'East': 'Cabinet', 'Item': 'Silver Mail'},
                'Solar': {'North': 'Entry Hall', 'East': 'Boudoir', 'Item': 'Stake'},
                'Boudoir': {'North': 'Great Hall', 'West': 'Solar', 'Item': 'Holy Water'},
                'Kitchen': {'East': 'Larder', 'South': 'Great Hall', 'Item': 'Mallet'},
                'Larder': {'West': 'Kitchen', 'Item': 'Potion of Cleansing'},
                'Cabinet': {'West': 'Great Hall', 'North': 'Garderobe', 'South': 'Bedchamber',
                            'Item': 'Blessed Sword'},
                'Garderobe': {'South': 'Cabinet', 'Item': 'Torch'}
                }

current_room = 'Entry Hall'  # define starting room
inventory = []  # define string for inventory


def player_commands(command, direction):  # function for moving rooms
    global current_room  # declare current room as global
    global inventory  # declare inventory as global
    if command == 'go':
        if direction in castle_rooms[current_room]:  # establishing valid direction
            current_room = castle_rooms[current_room][direction]
        elif direction not in castle_rooms[current_room]:  # error message for invalid direction
            print("You can't go that way")
            current_room = current_room

    elif command == 'get':
        if direction in current_room:
            inventory.append(direction)
        current_room = current_room
    else:
        print('Invalid command')  # error message for invalid command
        current_room = current_room
    return current_room, inventory


while current_room != 'Bedchamber':  # while loop for gameplay
    player_instructions()
    print('You are in the {}.'.format(current_room))

    if castle_rooms[current_room]['Item'] not in inventory:
        print('You see {} in the room.'.format(castle_rooms[current_room]['Item']))
    else:
        pass
    user_input = input('What will you do next?').split()
    command = user_input[0]
    direction = user_input[1] if len(user_input) > 1 else ''
    current_room = player_commands(command, direction)

This is the entire code so far, everything worked until I tried adding a separate player inventory. I haven't added the game end code yet so I realize I have an infinite loop but I was trying to make the inventory work before I added the ending since the inventory has to include all items to win.

答案1

得分: 1

以下是翻译好的代码部分:

当你拿取一个物品时你想要将其添加到你的物品清单中并从房间中移除它

尝试类似这样的操作

```python
    elif command == '拿取':
        current_item = castle_rooms[current_room_id]['物品']
        if current_item not in inventory:
            inventory.append(current_item)
            castle_rooms[current_room_id]['物品'] = None
            return current_room_id

如果你在大约第 56 行周围遇到错误(根据你的原始代码),可能是这样的:

    if castle_rooms[current_room]['物品'] not in inventory:
        print('你在房间里看到了{}。'.format(castle_rooms[current_room]['物品']))
    else:
        pass

如果一个房间没有物品,那么这将引发一个键错误。尝试将该代码替换为:

    current_room_item = castle_rooms[current_room].get('物品')
    if current_room_item not in inventory:
        print('你在房间里看到了{}。'.format(current_room_item))

这是一个更完整的示例:

import time

def player_instructions():
    # 主菜单和游戏命令
    print('移动命令:\n\t向北走, 向南走, 向西走, 向东走')
    print("物品命令:\n\t显示, 拿取")

def player_commands(command, direction):  # 用于移动房间的函数
    global current_room_id  # 声明当前房间为全局变量
    global inventory  # 声明物品清单为全局变量

    if command == '显示':
        if not inventory:
            print("你的背包是空的。")
            return current_room_id
        
        print("你有以下物品:")
        for item in inventory:
            print(f"    - {item}")
        return current_room_id

    if command == '拿取':
        current_item = castle_rooms[current_room_id]['物品']

        if not current_item:
            print("这里没有东西可拿")
            return current_room_id

        if current_item in inventory:
            print(f"你已经有了{current_item}")
            return current_room_id

        print(f"你贪婪地拿起了{current_item}")
        inventory.append(current_item)
        castle_rooms[current_room_id]['物品'] = None
        return current_room_id

    if command == '走':
        if direction not in castle_rooms[current_room_id]:
            print("你不能那样走")
            return current_room_id

        print(f"你向{direction}离开了{current_room_id}。")
        return castle_rooms[current_room_id][direction]

    print('无效的命令')  # 无效命令的错误消息
    return current_room_id

## -----------------------
# 房间和移动之间的字典
## -----------------------
castle_rooms = {
    '入口大厅': {'东': '大礼堂', '南': '太阳能房', '物品': None},
    '大礼堂': {'西': '入口大厅', '南': '闺房', '北': '厨房', '东': '橱柜', '物品': '银制盔甲'},
    '太阳能房': {'北': '入口大厅', '东': '闺房', '物品': '木桩'},
    '闺房': {'北': '大礼堂', '西': '太阳能房', '物品': '圣水'},
    '厨房': {'东': '食品储藏室', '南': '大礼堂', '物品': '木槌'},
    '食品储藏室': {'西': '厨房', '物品': '净化药剂'},
    '橱柜': {'西': '大礼堂', '北': '抽水马桶', '南': '卧室', '物品': '神圣之剑'},
    '抽水马桶': {'南': '橱柜', '物品': '火把'}
}
## -----------------------

current_room_id = '入口大厅'  # 定义起始房间
inventory = []  # 定义物品清单的字符串

print('-' * 50)
print('一场圣骑士的冒险游戏。')  # 游戏开场问候语
print('收集7个物品以赢得游戏,')
print('或被吸血鬼领主摧毁。')

while current_room_id != '卧室':  # 游戏玩法的循环
    current_room = castle_rooms[current_room_id]
    current_room_item = current_room['物品']
    current_room_exits = [key for key in current_room if key != "物品"]

    print('-' * 50)
    print(f'你在{current_room_id}。')
    print(f'可见的出口有:{current_room_exits}')
    if current_room_item:
        print(f'你看到了房间里的{current_room_item}。')
    player_instructions()

    command = input('你要做什么? ')
    direction = None
    if " " in command:
        command, direction = command.split()

    current_room_id = player_commands(command, direction)
    time.sleep(2)

print("恭喜,你到达了卧室!")
英文:

When you "get" an item, you want to append it to your inventory and remove it from the room.

Try something like:

    elif command == 'get':
        current_item = castle_rooms[current_room_id]['Item']
        if current_item not in inventory:
            inventory.append(current_item)
            castle_rooms[current_room_id]['Item'] = None
            return current_room_id

If you are getting an error around line 56 of so that is (based on your original code) likely:

    if castle_rooms[current_room]['Item'] not in inventory:
        print('You see {} in the room.'.format(castle_rooms[current_room]['Item']))
    else:
        pass

If a room does not have an item, then this will throw a key error. Try replacing that code with:

    current_room_item = castle_rooms[current_room].get('Item')
    if current_room_item not in inventory:
        print('You see {} in the room.'.format(current_room_item ))

Here is a more complete example:

import time

def player_instructions():
    # main menu and game commands
    print('Move Commands:\n\tgo North, go South, go West, go East')
    print("Inventory Commands:\n\tshow, take")

def player_commands(command, direction):  # function for moving rooms
    global current_room_id  # declare current room as global
    global inventory  # declare inventory as global

    if command == 'show':
        if not inventory:
            print("Your backpack is empty.")
            return current_room_id
        
        print("You have the following items:")
        for item in inventory:
            print(f"    - {item}")
        return current_room_id

    if command == 'take':
        current_item = castle_rooms[current_room_id]['Item']

        if not current_item:
            print(f"There is nothing here to take")
            return current_room_id

        if current_item in inventory:
            print(f"You already have the {current_item}")
            return current_room_id

        print(f"You greedily take the {current_item}")
        inventory.append(current_item)
        castle_rooms[current_room_id]['Item'] = None
        return current_room_id

    if command == 'go':
        if direction not in castle_rooms[current_room_id]:
            print("You can't go that way")
            return current_room_id

        print(f"You head {direction} out of the {current_room_id}.")
        return castle_rooms[current_room_id][direction]

    print('Invalid command')  # error message for invalid command
    return current_room_id

## -----------------------
# dictionary for rooms and movement between
## -----------------------
castle_rooms = {
    'Entry Hall': {'East': 'Great Hall', 'South': 'Solar', 'Item': None},
    'Great Hall': {'West': 'Entry Hall', 'South': 'Boudoir', 'North': 'Kitchen', 'East': 'Cabinet', 'Item': 'Silver Mail'},
    'Solar': {'North': 'Entry Hall', 'East': 'Boudoir', 'Item': 'Stake'},
    'Boudoir': {'North': 'Great Hall', 'West': 'Solar', 'Item': 'Holy Water'},
    'Kitchen': {'East': 'Larder', 'South': 'Great Hall', 'Item': 'Mallet'},
    'Larder': {'West': 'Kitchen', 'Item': 'Potion of Cleansing'},
    'Cabinet': {'West': 'Great Hall', 'North': 'Garderobe', 'South': 'Bedchamber', 'Item': 'Blessed Sword'},
    'Garderobe': {'South': 'Cabinet', 'Item': 'Torch'}
}
## -----------------------

current_room_id = 'Entry Hall'  # define starting room
inventory = []  # define string for inventory

print('-' * 50)
print('A Paladin Adventure Game.')  # game opening greeting
print('Collect 7 items to win the game,')
print('or be destroyed by the Vampire Lord.')

while current_room_id != 'Bedchamber':  # while loop for gameplay
    current_room = castle_rooms[current_room_id]
    current_room_item = current_room['Item']
    current_room_exits = [key for key in current_room if key != "Item"]

    print('-' * 50)
    print(f'You are in the {current_room_id}.')
    print(f'The following exits are visible: {current_room_exits}')
    if current_room_item:
        print(f'You see the {current_room_item} in the room.')
    player_instructions()

    command = input('What will you do next? ')
    direction = None
    if " " in command:
        command, direction = command.split()

    current_room_id = player_commands(command, direction)
    time.sleep(2)

print("Congrats, you reached the Bedchamber!")

答案2

得分: 0

以下是您提供的代码的中文翻译:

所以我和一个懂Python的朋友一起工作他教了我一些很有趣的新东西给代码添加颜色还帮我解决了库存问题我认为内联注释大部分都解释了代码的运作方式我对它能够正常工作感到非常兴奋

类 TextColor:
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    BLUE = '\033[94m'
    DARK_PURPLE = '\033[38;5;127m'
    CYAN = '\033[96m'
    VIOLET = '\033[95m'
    RESET = '\033[0m'

def player_instructions():
    # 主菜单和游戏命令
    print(f"{TextColor.GREEN}移动命令{TextColor.RESET}:向北走,向南走,向西走,向东走")
    print(f"{TextColor.YELLOW}添加到库存{TextColor.RESET}:获取物品名称")
    print(f"{TextColor.BLUE}查看库存{TextColor.RESET}:库存")
    print('-' * 50)

print('一场圣骑士的冒险游戏。')  # 游戏开场问候
print(f"收集{TextColor.RED}7{TextColor.RESET}个物品以赢得游戏,")
print('或者被吸血鬼领主摧毁。')
print('-' * 50)

# 房间和移动、物品和库存的字典
castle_rooms = {
    '入口大厅': {
        '东': '大宴会厅',
        '南': '阳光房',
        '物品': '无'
    },
    '大宴会厅': {
        '西': '入口大厅',
        '南': '卧室',
        '北': '厨房',
        '东': '橱柜',
        '物品': '银质铠甲'
    },
    '阳光房': {
        '北': '入口大厅',
        '东': '卧室',
        '物品': '木桩'
    },
    '卧室': {
        '北': '大宴会厅',
        '西': '阳光房',
        '物品': '圣水'
    },
    '厨房': {
        '东': '食品储藏室',
        '南': '大宴会厅',
        '物品': '木槌'
    },
    '食品储藏室': {
        '西': '厨房',
        '物品': '火把'
    },
    '橱柜': {
        '西': '大宴会厅',
        '北': '衣帽间',
        '南': '卧室',
        '物品': '祝福之剑'
    },
    '衣帽间': {
        '南': '橱柜',
        '物品': '净化药水'
    }
}

current_room = '入口大厅'  # 定义起始房间
inventory = []  # 定义库存的字符串

def display_inventory(current_inventory):
    if not current_inventory:
        print("你的库存是空的。")
    else:
        print("你的库存:")
        for item in inventory:
            print(f"- {TextColor.VIOLET}{item}{TextColor.RESET}")

def player_commands(cmd, dir_value):
    global current_room
    global inventory

    # 设置默认值
    new_current_room = current_room
    new_inventory = inventory

    if cmd == '走':
        # 处理移动逻辑
        if dir_value in castle_rooms[current_room]:
            new_current_room = castle_rooms[current_room][dir_value]
        else:
            print("你不能那样走")

    elif cmd == '获取':
        # 处理库存和与字典的交互
        cleaned_dir = dir_value.strip("''")
        if cleaned_dir == castle_rooms[current_room]['物品']:
            item_name = castle_rooms[current_room]['物品']
            if item_name != '无':
                new_inventory.append(item_name)
                castle_rooms[current_room]['物品'] = '无'
                print(f"你已将{TextColor.VIOLET}{item_name}{TextColor.RESET}添加到你的库存中。")
            else:
                print("这里没有物品可获取。")
        else:
            print("你不能在这里获取它。")

    else:
        print('无效命令')

    return new_current_room, new_inventory

while current_room != '卧室':  # 游戏进行中的循环
    player_instructions()

    player_room = castle_rooms[current_room]  # 使当前出口可见
    current_room_exits = [key for key in player_room if key != '物品']

    print(f'你在{TextColor.DARK_PURPLE}{current_room}{TextColor.RESET}。')
    print(f'以下出口可见:{TextColor.CYAN}{current_room_exits}{TextColor.RESET}')
    if castle_rooms[current_room]['物品'] != '无':  # 通知玩家房间里的物品
        item_name = castle_rooms[current_room]['物品']
        print(f'你看到{TextColor.VIOLET}{item_name}{TextColor.RESET}在房间里。')

    user_input = input('接下来你要做什么? ').split(maxsplit=1)
    command = user_input[0]
    direction = user_input[1] if len(user_input) > 1 else ''
    direction = direction.strip("''")  # 从方向中移除单引号

    if command == '库存':   # 用于显示库存
        display_inventory(inventory)
    else:
        current_room, inventory = player_commands(command, direction)

if current_room == '卧室':
    # 游戏结束条件

    if len(inventory) == 7:  # 胜利条件
        print('恭喜!')
        print('你已经打败了吸血鬼领主并保留了你的人类身份。')
        print('你赢了!')
        print('-' * 50)
        exit()
    elif len(inventory) == 6:
        if '净化

<details>
<summary>英文:</summary>

So I worked with a friend that knows python and he taught me some really neat new things, adding color to the code and he also helped me fix my inventory problems  I think the inline comments explain most of what is going on with it, I&#39;m so excited to have it working well.
```class TextColor:
    RED = &#39;\033[91m&#39;
    GREEN = &#39;\033[92m&#39;
    YELLOW = &#39;\033[93m&#39;
    BLUE = &#39;\033[94m&#39;
    DARK_PURPLE = &#39;\033[38;5;127m&#39;
    CYAN = &#39;\033[96m&#39;
    VIOLET = &#39;\033[95m&#39;
    RESET = &#39;\033[0m&#39;

def player_instructions():
    # main menu and game commands
    print(f&quot;{TextColor.GREEN}Move Commands{TextColor.RESET}: go North, go South, go West, go East&quot;)
    print(f&quot;{TextColor.YELLOW}Add to inventory{TextColor.RESET}: get item name&quot;)
    print(f&quot;{TextColor.BLUE}View inventory{TextColor.RESET}: inventory&quot;)
    print(&#39;-&#39; * 50)


print(&#39;A Paladin Adventure Game.&#39;)  # game opening greeting
print(f&quot;Collect {TextColor.RED}7{TextColor.RESET} items to win the game,&quot;)
print(&#39;or be destroyed by the Vampire Lord.&#39;)
print(&#39;-&#39; * 50)

# dictionary for rooms and movement, and items and inventory
castle_rooms = {
    &#39;Entry Hall&#39;: {
        &#39;East&#39;: &#39;Great Hall&#39;,
        &#39;South&#39;: &#39;Solar&#39;,
        &#39;Item&#39;: &#39;None&#39;
    },
    &#39;Great Hall&#39;: {
        &#39;West&#39;: &#39;Entry Hall&#39;,
        &#39;South&#39;: &#39;Boudoir&#39;,
        &#39;North&#39;: &#39;Kitchen&#39;,
        &#39;East&#39;: &#39;Cabinet&#39;,
        &#39;Item&#39;: &#39;Silver Mail&#39;
    },
    &#39;Solar&#39;: {
        &#39;North&#39;: &#39;Entry Hall&#39;,
        &#39;East&#39;: &#39;Boudoir&#39;,
        &#39;Item&#39;: &#39;Stake&#39;
    },
    &#39;Boudoir&#39;: {
        &#39;North&#39;: &#39;Great Hall&#39;,
        &#39;West&#39;: &#39;Solar&#39;,
        &#39;Item&#39;: &#39;Holy Water&#39;
    },
    &#39;Kitchen&#39;: {
        &#39;East&#39;: &#39;Larder&#39;,
        &#39;South&#39;: &#39;Great Hall&#39;,
        &#39;Item&#39;: &#39;Mallet&#39;
    },
    &#39;Larder&#39;: {
        &#39;West&#39;: &#39;Kitchen&#39;,
        &#39;Item&#39;: &#39;Torch&#39;
    },
    &#39;Cabinet&#39;: {
        &#39;West&#39;: &#39;Great Hall&#39;,
        &#39;North&#39;: &#39;Garderobe&#39;,
        &#39;South&#39;: &#39;Bedchamber&#39;,
        &#39;Item&#39;: &#39;Blessed Sword&#39;
    },
    &#39;Garderobe&#39;: {
        &#39;South&#39;: &#39;Cabinet&#39;,
        &#39;Item&#39;: &#39;Potion of Cleansing&#39;
    }
}


current_room = &#39;Entry Hall&#39;  # define starting room
inventory = []  # define string for inventory


def display_inventory(current_inventory):
    if not current_inventory:
        print(&quot;Your inventory is empty.&quot;)
    else:
        print(&quot;Your inventory:&quot;)
        for item in inventory:
            print(&quot;- {}{}{}&quot;.format(TextColor.VIOLET, item, TextColor.RESET))


def player_commands(cmd, dir_value):
    global current_room
    global inventory

    # Set default values
    new_current_room = current_room
    new_inventory = inventory

    if cmd == &#39;go&#39;:
        # Handle movement logic
        if dir_value in castle_rooms[current_room]:
            new_current_room = castle_rooms[current_room][dir_value]
        else:
            print(&quot;You can&#39;t go that way&quot;)

    elif cmd == &#39;get&#39;:
        # handle inventory and working with the dictionary
        cleaned_dir = dir_value.strip(&quot;&#39;&quot;)
        if cleaned_dir == castle_rooms[current_room][&#39;Item&#39;]:
            item_name = castle_rooms[current_room][&#39;Item&#39;]
            if item_name != &#39;None&#39;:
                new_inventory.append(item_name)
                castle_rooms[current_room][&#39;Item&#39;] = &#39;None&#39;
                print(&quot;You&#39;ve added {}{}{} to your inventory.&quot;.format(TextColor.VIOLET, item_name, TextColor.RESET))
            else:
                print(&quot;There&#39;s no item here to get.&quot;)
        else:
            print(&quot;You can&#39;t get that here.&quot;)

    else:
        print(&#39;Invalid command&#39;)

    return new_current_room, new_inventory


while current_room != &#39;Bedchamber&#39;:  # while loop for gameplay
    player_instructions()

    player_room = castle_rooms[current_room]  # make current exits visible
    current_room_exits = [key for key in player_room if key != &#39;Item&#39;]

    print(&#39;You are in the {}{}{}.&#39;.format(TextColor.DARK_PURPLE, current_room, TextColor.RESET))
    print(&#39;The following exits are visible: {}{}{}&#39;.format(TextColor.CYAN, current_room_exits, TextColor.RESET))
    if castle_rooms[current_room][&#39;Item&#39;] != &#39;None&#39;:  # inform player of item in room
        item_name = castle_rooms[current_room][&#39;Item&#39;]
        print(&#39;You see {}{}{} in the room.&#39;.format(TextColor.VIOLET, item_name, TextColor.RESET))

    user_input = input(&#39;What will you do next? &#39;).split(maxsplit=1)
    command = user_input[0]
    direction = user_input[1] if len(user_input) &gt; 1 else &#39;&#39;
    direction = direction.strip(&quot;&#39;&quot;)  # Remove single quotes from direction

    if command == &#39;inventory&#39;:   # for inventory display
        display_inventory(inventory)
    else:
        current_room, inventory = player_commands(command, direction)

if current_room == &#39;Bedchamber&#39;:
    # game ending conditions

    if len(inventory) == 7:  # winning ending
        print(&#39;Congratulations!&#39;)
        print(&#39;You have defeated the Vampire Lord and retained your humanity.&#39;)
        print(&#39;You win!&#39;)
        print(&#39;-&#39; * 50)
        exit()
    elif len(inventory) == 6:
        if &#39;Potion of Cleansing&#39; not in inventory:  # alternate win/lose ending
            print(&#39;Congratulations!&#39;)
            print(&#39;You have defeated the Vampire Lord!&#39;)
            print(&#39;However, you did not find the Potion of Cleansing.&#39;)
            print(&#39;You are doomed to become the next Lord of the Castle.&#39;)
            print(&#39;-&#39; * 50)
            exit()
        else:
            print(&#39;You did not collect all of the items needed&#39;)  # loss
            print(&#39;to defeat the Vampire Lord.&#39;)
            print(&#39;You lose.&#39;)
            print(&#39;-&#39; * 50)
            exit()
    else:
        print(&#39;You did not collect all of the items needed&#39;)  # loss
        print(&#39;to defeat the Vampire Lord.&#39;)
        print(&#39;You lose.&#39;)
        print(&#39;-&#39; * 50)
        exit()

huangapple
  • 本文由 发表于 2023年8月11日 02:44:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76878549.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定