0

I'm completing my final project for my first programming course in python using the code below. The majority of this already works. The idea is a text based adventure game where you are meant to collect 6 items before you get to the "boss room." The only thing giving me an issue is in the status function, it's meant to print the players inventory. However, when the player goes to collect the first item it isn't printing Inventory: [Self Portrait] but rather Inventory: ['S', 'e', 'l', 'f', ' ', 'P', 'o', 'r', 't', 'r', 'a', 'i', 't']. Not sure how to fix this even though it might seem like a stupid question, haha, but I'm a beginner so! My full code is below.

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!')
001
  • 13,291
  • 5
  • 35
  • 66
kls1022
  • 1
  • 1
  • 2
    `inventory += str(rooms[current_room]['item'])` If `inventory` is a list, shouldn't you be using [`append()`](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists) here? – 001 Oct 14 '21 at 19:19
  • 1
    Also, if `rooms[current_room]['item']` is already a string, there's no need to convert it with `str()`. – 001 Oct 14 '21 at 19:21
  • 1
    `elif move == 'North' or 'South' or 'East' or 'West':` [How to test multiple variables against a single value?](https://stackoverflow.com/a/15112149) – 001 Oct 14 '21 at 19:29
  • first you should use `print()` to see what you have in variables in different moments - this way you could see in which moment you create `['S', 'e', 'l', 'f', ' ', 'P', 'o', 'r', 't', 'r', 'a', 'i', 't']`. – furas Oct 14 '21 at 22:42

1 Answers1

0

First you could use print() to see what you have in variables in different moments - this way you could see in which moment you create ['S', 'e', 'l', 'f', ' ', 'P', 'o', 'r', 't', 'r', 'a', 'i', 't']


You add new item using

inventory += ...

but this is shortcut for

inventory.extend( other_list )

and it expects list as argument but you have string Self Portrait which Python can treat as list of chars.

You should use .append()

inventory.append( item )

or you should use list with item

inventory.extend( [item] )

inventory += [item]

I see other problem.

It should be

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

or

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

Because I don't like to write long words and use shift so I would do

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

and now player can use Quit, quit, QUIT, QuIt, etc. or simply q or Q. And the same is for Collect.

I would do the same for 'North', 'South', 'East', 'West' but you use it in dictionary rooms so I would use other dictionary to convert short e to long East, etc.

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

while True:

    # ... code ...

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

    # ... code ...

if it finds move.lower() in shortcuts - ie. e - then it get full name - ie. East. But of it doesn't find lower text in shortcuts then it keep original value from move (second argument in get())


Full working code.

To make code more readable I put all function at the beginning.

# --- 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!')
furas
  • 134,197
  • 12
  • 106
  • 148