pycharm Python文本游戏项目

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

为了让代码运行良好,我在这个任务上非常努力,但我无法找出代码中的错误。我试过执行“get”命令,让玩家实际上能够拿起房间里的物品,但它不会将其添加到我为库存准备的空列表中,最重要的是,物品的输出只是“item”,而不是房间里的物品。由于时间限制,我被迫提交了非功能性的项目,但我会感谢任何和所有的反馈,让我学习我的错误。

main_menu = 'Move commands: North, East, South, West, Exit.'

def showinstructions():
    print('Death to the Lich')  # Name of game
    print('Collect all items in order to defeat the evil Lich in his spooky Mansion')  # Goal of game
    print(main_menu)  # Show move commands
    print("Add item to inventory: get 'item name'")  # Add item to inventory: get 'item name'

def player_status(inventory, location, rooms):
    print('Inventory:', inventory)
    print('YOu are in here:', location)
    if 'item' in rooms[location]:
        print('Ah, look what you have found!', rooms[location]['item'])

def main():
    inventory = []
    rooms = {
        'Living Room': {'South': 'Bedroom', 'North': 'Dungeon', 'East': 'Alchemy Room', 'West': 'Library'},
        'Bedroom': {'North': 'Living Room', 'East': 'Cellar', 'item': 'Shiny Armor'},
        'Cellar': {'West': 'Bedroom', 'item': 'Shiny Helmet'},
        'Dungeon': {'South': 'Living Room', 'East': 'Gallery', 'item': 'Silver Sword'},
        'Gallery': {'West': 'Dungeon', 'item': 'Magic Potion'},
        'Alchemy Room': {'West': 'Living Room', 'North': 'Dining Room', 'item': 'Silver Sword'},
        'Dining Room': {'South': 'Alchemy Room', 'item': 'Shiny Gloves'},
        'Library': {'East': 'Living Room', 'item': 'Lich'}
    }

    # The main function:
    location = 'Living Room'

    showinstructions()



    while True:
        print('\nYou are in the', location)

        move_options = rooms[location].keys()
        print('Move options:', *move_options)

        command = input('Which direction will you go?').strip()
        print('You entered:', command)

        if 'item' in 'location':
            print('You see this in the room:', rooms[location]['item'])
        if command == 'get':
            item = input()
            inventory.append(item)
        else:
            print('There is no item here')

        if location == 'Library':
            print('I am the Evil Lich! Prepare to die!')
            if len(inventory) >= 6:
                print('You are the hero of these Lands! YOU WON!')
            else:
                print('Sadly you werent not strong enough to defeat the Lich. YOU LOSE')
                break
        if command == "Exit":
            print('Thanks for playing!')
            break
        elif command in move_options:
            location = rooms[location][command]
        else:
            print('Wrong direction!')


main()
j8ag8udp

j8ag8udp1#

看起来您的代码中有几个问题可能会导致您所描述的问题。我将一步一步地检查代码并指出错误:
在if 'item' in 'location'中:条件,您应该检查rooms[location]中的'item',而不是'location'中的'item'。
当您检查'get'命令时,需要拆分输入以提取项名称。目前,您只是将整个输入作为一个项目附加到库存中。将item = input()替换为item = input('Which item will you get?').
对获胜和失败条件的检查(if location == 'Library':)应该在请求用户输入的循环之外。目前,它在循环中,所以它将在游戏循环中被多次检查。
以下是修复了这些问题的代码的更正版本:

def main():
inventory = []
rooms = {
    'Living Room': {'South': 'Bedroom', 'North': 'Dungeon', 'East': 'Alchemy Room', 'West': 'Library'},
    'Bedroom': {'North': 'Living Room', 'East': 'Cellar', 'item': 'Shiny Armor'},
    # ... other room definitions ...
    'Library': {'East': 'Living Room', 'item': 'Lich'}
}

location = 'Living Room'
showinstructions()

while True:
    print('\nYou are in the', location)

    move_options = rooms[location].keys()
    print('Move options:', *move_options)

    command = input('Which direction will you go? ').strip()
    print('You entered:', command)

    if 'item' in rooms[location]:
        print('You see this in the room:', rooms[location]['item'])
    if command.startswith('get '):
        item = command[4:]  # Extract item name from the command
        if 'item' in rooms[location] and rooms[location]['item'] == item:
            inventory.append(item)
            print(f'You picked up {item}')
        else:
            print('Item not found in this room')
    else:
        print('Invalid command')

    if location == 'Library':
        print('I am the Evil Lich! Prepare to die!')
        if len(inventory) >= 6:
            print('You are the hero of these Lands! YOU WON!')
        else:
            print('Sadly you were not strong enough to defeat the Lich. YOU LOSE')
            break

    if command == "Exit":
        print('Thanks for playing!')
        break
    elif command in move_options:
        location = rooms[location][command]
    else:
        print('Wrong direction!')

ifname==“main":主要()
请注意,我已经做了必要的更正,以解决您提到的问题。这段代码现在应该允许您拾取物品,将它们添加到库存中,并根据您定义的条件赢得或输掉游戏。

uklbhaso

uklbhaso2#

这个游戏的大修版本将导致已经可玩。

main_menu = 'Move commands: North, East, South, West, Exit.'

def showinstructions():
    print('Death to the Lich')  # Name of game
    print('=================')
    print('Collect all items in order to defeat the evil Lich in his spooky Mansion')  # Goal of game
    print(main_menu)  # Show move commands
    print("Add item to inventory: get 'item name'")  # Add item to inventory: get 'item name'
    print('-----------------')

def player_status(inventory, location, rooms):
    print('Inventory:', inventory)
    print('YOu are in here:', location)
    if 'item' in rooms[location]:
        print('Ah, look what you have found!', rooms[location]['item'])

def main():
    inventory = []
    rooms = {
        'Living Room': {'directions': {'South': 'Bedroom', 'North': 'Dungeon', 'East': 'Alchemy Room', 'West': 'Library'}},
        'Bedroom': {'directions':{'North': 'Living Room', 'East': 'Cellar'}, 'item': 'Shiny Armor'},
        'Cellar': {'directions':{'West': 'Bedroom'}, 'item': 'Shiny Helmet'},
        'Dungeon': {'directions':{'South': 'Living Room', 'East': 'Gallery'}, 'item': 'Silver Sword'},
        'Gallery': {'directions':{'West': 'Dungeon'}, 'item': 'Magic Potion'},
        'Alchemy Room': {'directions':{'West': 'Living Room', 'North': 'Dining Room'}, 'item': 'Silver Sword'},
        'Dining Room': {'directions':{'South': 'Alchemy Room'}, 'item': 'Shiny Gloves'},
        'Library': {'directions':{'East': 'Living Room'}, 'item': 'The Lich'}
    }

    # The main function:
    location = 'Living Room'

    showinstructions()

    while True:
        print('\nYou are in the', location)

        if 'item' in rooms[location]:
            print('You see this in the room:', rooms[location]['item'])

        move_options = rooms[location]['directions'].keys()
        print('Move options:', *move_options)

        command = input("Which direction will you go? Write 'get' to pick up an item: ").strip()
        print('You entered:', command)

        if 'item' in rooms[location]:
            if command == 'get':
                item = input("Write '{}' to pick up the item: ".format(rooms[location]['item'])).strip()
                
                if item in rooms[location]['item']:
                    print("You picked up the item: '{}'".format(item))
                    inventory.append(item)
                    del rooms[location]['item']
                else:                    
                    print(format("Item '{}' is not here!", item))

        if location == 'Library':
            print('I am the Evil Lich! Prepare to die!')
            if len(inventory) >= 6:
                print('You are the hero of these Lands! YOU WON!')
            else:
                print('Sadly you werent not strong enough to defeat the Lich. YOU LOSE')
                break
        if command == "Exit":
            print('Thanks for playing!')
            break
        elif command in move_options:
            location = rooms[location]['directions'][command]
            print('You enter the', location)
        else:
            print('Wrong direction!')

main()

代码导航流程数据结构中存在多个问题。
1.原始结构将显示item作为移动选项。这将产生一个key lookup异常

You are in the Bedroom
Move options: North East item
Which direction will you go?item
You entered: item
There is no item here

You are in the Shiny Armor
Traceback (most recent call last):
  File "/path/to/project/lich.py", line 72, in <module>
    main()
  File "/path/to/project/lich.py", line 41, in main
    move_options = rooms[location].keys()
KeyError: 'Shiny Armor'

因此,该项目必须与方向分开,如:

'Bedroom': {'directions':{'North': 'Living Room', 'East': 'Cellar'}, 'item': 'Shiny Armor'}

1.玩家不能拾取该项目,因为它仅在他已经写入他的command之后显示
1.关键字item必须与 dictionary 进行比较,而不是与如下字符串进行比较:

if 'item' in rooms[location]:

1.变量item可能与字典键item”冲突,因此需要在引号中进行查找,如:

if item in rooms[location]['item']:

此外,物品必须在拾取后从rooms结构中移除,这样玩家就不会多次拾取同一物品。

if 'item' in rooms[location]:
            if command == 'get':
                item = input("Write '{}' to pick up the item: ".format(rooms[location]['item'])).strip()
                
                if item in rooms[location]['item']:
                    print("You picked up the item: '{}'".format(item))
                    inventory.append(item)
                    del rooms[location]['item']
                else:                    
                    print(format("Item '{}' is not here!", item))

我想这会让你提前结束比赛。

相关问题