首页 > 解决方案 > 如何让单词打印为整个单词?

问题描述

我正在使用下面的代码完成我的第一个 Python 编程课程的最终项目。其中大部分已经有效。这个想法是一个基于文本的冒险游戏,在你到达“老板房间”之前,你需要收集 6 件物品。唯一给我的问题是状态功能,它旨在打印玩家库存。然而,当玩家去收集第一个物品时,它不是打印 Inventory: [Self Portrait] 而是 Inventory: ['S', 'e', 'l', 'f', ' ', 'P', 'o'、'r'、't'、'r'、'a'、'i'、't']。不知道如何解决这个问题,尽管这似乎是一个愚蠢的问题,哈哈,但我是初学者!我的完整代码如下。

def instructions():
    print('You are taking part in a museum heist!')
    print("Collect all 6 paintings before you find your mafia boss, or you will get fired!")
    print("To move, type: North, South, East, or West.")
    print("To collect an item, type: Collect")
    print('To quit, type Quit')

instructions()
print('----------------------')


def status():

    print('You are in the', current_room, 'Room')
    print('Inventory:', str(inventory))
    if 'item' in rooms[current_room]:
        print('You see an artwork called', str(rooms[current_room]['item']))


print('----------------------')

inventory = []#placeholders
item = ' '

def main():

    inventory = []


rooms = {
    'Foyer': {'East': 'Contemporary'},
    'Contemporary': {'North': 'Impressionist', 'East': 'Abstract', 'West': 'Foyer', 'South': 'Surrealist', 'item': 'Self Portrait'},
    'Abstract': {'North': 'Pop Art', 'West': 'Contemporary', 'item': 'Convergence'},
    'Pop Art': {'South': 'Abstract', 'item': 'Shot Marilyns'},
    'Surrealist': {'North': 'Contemporary', 'East': 'Realist', 'item':  'The Persistence of Memory'},
    'Impressionist': {'South': 'Contemporary', 'East': 'Expressionist', 'item': 'Poppies'},
    'Expressionist': {'West': 'Impressionist', 'item': 'Starry Night'},
    'Realist': {'West': 'Surrealist', 'item': 'Mafia Boss'}
}

current_room = 'Foyer'

while True:
    status()
    if rooms[current_room] == rooms['Realist']:
        print('Oh no! Your boss is angry you did not steal all the paintings! You have been fired. GAME OVER.')
        break
    if len(inventory) == 6:
        print('Congratulations! You got all the paintings. You Win!!')
        break
    print('----------------------')
    print('Which way?')
    move = input()
    if move == 'Quit':
        print('Sorry to see you go!')
        break
    elif move == 'Collect':
        if 'item' in rooms[current_room]:
            inventory += str(rooms[current_room]['item'])
            print("You collected", str(rooms[current_room]['item']))
            del rooms[current_room]['item']
        else:
            print('There is no item here.')
    elif move == 'North' or 'South' or 'East' or 'West':
        if move in rooms[current_room]:
            current_room = rooms[current_room][move]
        else:
            print("Sorry, you can't go that way.")
            move = input()
            current_room = current_room
    else:
        print('Invalid move!')

标签: pythonformatting

解决方案


首先,您可以使用print()查看不同时刻变量中的内容 - 这样您就可以看到您在哪个时刻创建['S', 'e', 'l', 'f', ' ', 'P', 'o', 'r', 't', 'r', 'a', 'i', 't']


您使用添加新项目

inventory += ...

但这是捷径

inventory.extend( other_list )

它期望列表作为参数,但你有Self PortraitPython 可以将其视为字符列表的字符串。

你应该使用.append()

inventory.append( item )

或者你应该使用列表item

inventory.extend( [item] )

inventory += [item]

我看到其他问题。

它应该是

elif move == 'North' or move == 'South' or move == 'East' or move == 'West':

或者

elif move in ('North', 'South', 'East', 'West'):

因为我不喜欢写长词和使用shift所以我会这样做

    if move.lower() in ('quit', 'q'):
        #...code...     
    elif move.lower() in ('collect', 'c'):
        #...code...     

现在玩家可以使用Quit, quit, QUIT,QuIt等或简单地使用qor Q。对于Collect.

我会这样做,'North', 'South', 'East', 'West'但你在字典中使用它,rooms所以我会使用其他字典将 short 转换e为 longEast等。

shortcuts = {
    'n': 'North',
    's': 'South',
    'e': 'East',
    'w': 'West',
}

while True:

    # ... code ...

    move = input()
    
    move = shortcuts.get(move.lower(), move)

    # ... code ...

如果它move.lower()在快捷方式中找到 - 即。e- 然后它得到全名 - 即。East. 但是它没有找到较低的文本,shortcuts然后它保留原始值move(中的第二个参数get()


完整的工作代码。

为了使代码更具可读性,我将所有功能都放在了开头。

# --- functions ---

def instructions():
    print('You are taking part in a museum heist!')
    print("Collect all 6 paintings before you find your mafia boss, or you will get fired!")
    print("To move, type: North, South, East, or West.")
    print("To collect an item, type: Collect")
    print('To quit, type Quit')

def status():
    print('You are in the', current_room, 'Room')
    #print('Inventory:', inventory)
    print('Inventory:', ', '.join(inventory))

    if 'item' in rooms[current_room]:
        print('You see an artwork called', rooms[current_room]['item'])

def main():
    global inventory
    
    inventory = []

# --- main ---

# - variables -

inventory = []#placeholders
item = ' '

rooms = {
    'Foyer': {'East': 'Contemporary'},
    'Contemporary': {'North': 'Impressionist', 'East': 'Abstract', 'West': 'Foyer', 'South': 'Surrealist', 'item': 'Self Portrait'},
    'Abstract': {'North': 'Pop Art', 'West': 'Contemporary', 'item': 'Convergence'},
    'Pop Art': {'South': 'Abstract', 'item': 'Shot Marilyns'},
    'Surrealist': {'North': 'Contemporary', 'East': 'Realist', 'item':  'The Persistence of Memory'},
    'Impressionist': {'South': 'Contemporary', 'East': 'Expressionist', 'item': 'Poppies'},
    'Expressionist': {'West': 'Impressionist', 'item': 'Starry Night'},
    'Realist': {'West': 'Surrealist', 'item': 'Mafia Boss'}
}

shortcuts = {
    'n': 'North',
    's': 'South',
    'e': 'East',
    'w': 'West',
}

current_room = 'Foyer'

# - code -

instructions()
print('----------------------')

while True:
    status()
    if rooms[current_room] == rooms['Realist']:
        print('Oh no! Your boss is angry you did not steal all the paintings! You have been fired. GAME OVER.')
        break
    if len(inventory) == 6:
        print('Congratulations! You got all the paintings. You Win!!')
        break
    print('----------------------')

    print('Which way?')
    move = input()
    
    move = shortcuts.get(move.lower(), move)
    print('[DEBUG] move:', move)
    
    if move.lower() in ('quit', 'q'):
        print('Sorry to see you go!')
        break
    
    elif move.lower() in ('collect', 'c'):
        if 'item' in rooms[current_room]:
            inventory.append(rooms[current_room]['item'])
            print("You collected", rooms[current_room]['item'])
            del rooms[current_room]['item']
        else:
            print('There is no item here.')

    elif move.lower() in ('north', 'south', 'east', 'west'):
        if move in rooms[current_room]:
            current_room = rooms[current_room][move]
        else:
            print("Sorry, you can't go that way.")
            #move = input()
            #current_room = current_room
    else:
        print('Invalid move!')

推荐阅读