pycharm 我正在为一个班级创建一个基于文本的冒险游戏,并且在让我的库存系统工作时遇到了麻烦

xam8gpfp  于 2023-10-20  发布在  PyCharm
关注(0)|答案(2)|浏览(191)

在上周的作业中,我们要做一个简单的游戏,可以移动房间。我已经调整到我的游戏代码的代码,它似乎工作正常,即使与‘项目‘添加到我的字典。一旦我尝试添加到库存并引用库存列表到字典键,我就会得到一个“不可散列”错误。我查了一下,但唯一的方法来清 debugging 误是使用一个元组,但一个元组是不可变的,所以我不能添加到库存,至少在我的理解。任何指导或建议都非常感谢!

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)

这是到目前为止的全部代码,一切正常,直到我尝试添加一个单独的播放器库存。我还没有添加游戏结束代码,所以我意识到我有一个无限循环,但我试图使库存工作之前,我添加了结束,因为库存必须包括所有项目赢得。

f4t66c6m

f4t66c6m1#

当你“得到”一个物品时,你想把它附加到你的物品清单上,并把它从房间里移走。
尝试以下操作:

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

如果你在第56行附近得到一个错误,那么(基于你的原始代码)可能是:

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

如果一个房间没有一个项目,那么这将抛出一个关键字错误。尝试将该代码替换为:

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 ))

下面是一个更完整的示例:

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!")
n53p2ov0

n53p2ov02#

所以我和一个懂python的朋友一起工作,他教了我一些非常好的新东西,给代码添加颜色,他还帮助我解决了我的库存问题,我认为内联注解解释了它的大部分内容,我很高兴它能运行得很好。

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():
    # main menu and game commands
    print(f"{TextColor.GREEN}Move Commands{TextColor.RESET}: go North, go South, go West, go East")
    print(f"{TextColor.YELLOW}Add to inventory{TextColor.RESET}: get item name")
    print(f"{TextColor.BLUE}View inventory{TextColor.RESET}: inventory")
    print('-' * 50)

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

# dictionary for rooms and movement, and items and inventory
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': 'Torch'
    },
    'Cabinet': {
        'West': 'Great Hall',
        'North': 'Garderobe',
        'South': 'Bedchamber',
        'Item': 'Blessed Sword'
    },
    'Garderobe': {
        'South': 'Cabinet',
        'Item': 'Potion of Cleansing'
    }
}

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

def display_inventory(current_inventory):
    if not current_inventory:
        print("Your inventory is empty.")
    else:
        print("Your inventory:")
        for item in inventory:
            print("- {}{}{}".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 == 'go':
        # Handle movement logic
        if dir_value in castle_rooms[current_room]:
            new_current_room = castle_rooms[current_room][dir_value]
        else:
            print("You can't go that way")

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

    else:
        print('Invalid command')

    return new_current_room, new_inventory

while current_room != 'Bedchamber':  # 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 != 'Item']

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

    user_input = input('What will you do next? ').split(maxsplit=1)
    command = user_input[0]
    direction = user_input[1] if len(user_input) > 1 else ''
    direction = direction.strip("'")  # Remove single quotes from direction

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

if current_room == 'Bedchamber':
    # game ending conditions

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

相关问题