pythontext-based

Cant figure out how to get the code to display the item in the room


I am creating a text-based game for my Python class and I can't get it to display the item when entering the room. I can collect it, and the inventory gets displayed. Just not the item that is in the room. I have put in the code I am using currently, I have tried adjusting it but then I get errors thrown at me.

# Welcome message to the player
def prompt():
    print("\t\t\tWelcome to professional wrestling!\n\nVance McMan has locked all wrestlers into an evil "
          "contract.\n\n"
          "You must collect all 6 items and defeat Vance to free all the wrestlers.\n\n"
          f"To move:\t'go {direction}' \n\
          \t 'get item name' \n\n")

    input('Press any key to continue...')


# clear the screen after the welcome message
def clear():
    os.system('cls' if os.name == 'nt' else 'clear')


# dictionary
rooms = {
    'Ring': {'North': 'Gym', 'South': 'Steel Cage', 'East': 'Dressing Room', 'West': 'Office', 'Item': 'Chair'},
    'Office': {'West': 'Ring', 'Boss': 'Vance McMan'},  # villain
    'Gym': {'South': 'Ring', 'East': 'Garage', 'Item': 'RKO Promo Video'},
    'Garage': {'West': 'Gym', 'Item': 'Blueprint'},
    'Steel Cage': {'North': 'Ring', 'East': 'Greenroom', 'Item': 'Mr.Socko'},
    'Green Room': {'West': 'Steel Cage', 'Item': 'StoneCold Beer'},
    'Dressing Room': {'East': 'Ring', 'North': 'Locker Room', 'Item': 'Rics Robe'},
    'Locker Room': {'South': 'Dressing Room'}  # starting room
}

# list of vowels
vowels = ['a', 'e', 'i', 'o', 'u']

# directions
direction = ['north', 'south', 'east', 'west']

# track inventory
inventory = []

# track the current room
current_room = 'Locker Room'

item = rooms[current_room].get('Item')
# results of the players previous move
msg = ''

clear()
prompt()

# gameplay loop until exit
while True:
    clear()
    # display info to player
    print(f"You are in the {current_room}\nInventory : {inventory}\n{' - ' * 27}")

    # display the msg
    print(msg)

    # indicate items
    if 'item' in rooms[current_room].keys():
        nearby_item = rooms[current_room]["item"]

        if nearby_item not in inventory:

            if nearby_item[-1] == 's':
                print(f'You see {nearby_item}')

            elif nearby_item[0] in vowels:
                print(f'You see an {nearby_item}')

            else:
                print(f'You see a {nearby_item}')

    # boss encounter
    if 'Boss' in rooms[current_room].keys():
        # lose
        if len(inventory) < 6:
            print(f"Game over! You lost a fight with {rooms[current_room]['Boss']}")

        # win
        else:
            print(f"You beat {rooms[current_room]['Boss']}")

    # accept the player move as input
    move = input('Which direction will you go?\n')

    # split the move into words
    next_move = move.split(' ')

    # the first word is an action
    action = next_move[0].title()

    if len(next_move) > 1:
        item = next_move[1:]
        direction = next_move[1].title()

        item = ' '.join(item).title()

    # move in between rooms
    if action == 'Go':
        try:
            current_room = rooms[current_room][direction]
            msg = f'You go {direction}.'

        except:
            msg = f'You cannot go that way.'

    # picking up items
    elif action == "Get":
        if item == rooms[current_room]['item']:

            if item not in inventory:
                inventory.append(rooms[current_room]['item'])
                msg = f"{item} retrieved!"

            else:
                msg = f"You already have the {item} in your inventory."

        else:
            msg = f"Cannot find the {item}"

    # exit the game
    if move == 'Exit':
        current_room = 'exit'
        print('Game over. Thank you for playing!')
        break

# any other commands invalid
else:
    msg = f"Invalid command"`

Solution

  • Among several other issues, when you're splitting on the user's input command, you need to add a maxsplit so that the second portion of the string can contain spaces unmodified.

    rooms: dict[str, dict[str, str]] = {
        'Ring': {'north': 'Gym', 'south': 'Steel Cage', 'east': 'Dressing Room', 'west': 'Office', 'item': 'Chair'},
        'Office': {'west': 'Ring', 'boss': 'Vance McMan'},
        'Gym': {'south': 'Ring', 'east': 'Garage', 'item': 'RKO Promo Video'},
        'Garage': {'west': 'Gym', 'item': 'Blueprint'},
        'Steel Cage': {'north': 'Ring', 'east': 'Green Room', 'item': 'Mr.Socko'},
        'Green Room': {'west': 'Steel Cage', 'item': 'StoneCold Beer'},
        'Dressing Room': {'east': 'Ring', 'north': 'Locker Room', 'item': 'Rics Robe'},
        'Locker Room': {'south': 'Dressing Room'},
    }
    
    
    def prompt() -> None:
        print(
            '\t\t\tWelcome to professional wrestling!'
            '\n'
            '\nVance McMan has locked all wrestlers into an evil contract.'
            '\n'
            '\nYou must collect all 6 items and defeat Vance to free all the wrestlers.'
            '\n'
            f"\nTo move:\t'go [north | south | east | west]'"
            "\n\t 'get item name'"
        )
    
    
    def indicate_item(room: dict[str, str], inventory: set[str]) -> None:
        nearby_item = room.get('item')
        if nearby_item is not None and nearby_item not in inventory:
            vowels = {'a', 'e', 'i', 'o', 'u'}
            if nearby_item[-1] == 's':
                print('You see', nearby_item)
            elif nearby_item[0] in vowels:
                print('You see an', nearby_item)
            else:
                print('You see a', nearby_item)
    
    
    def encounter_boss(room: dict[str, str], inventory: set[str]) -> bool:
        boss = room.get('boss')
        if boss is None:
            return False
        
        if len(inventory) < 6:
            print('Game over! You lost a fight with', boss)
        else:
            print('You beat', boss)
        return True
    
    
    def describe_turn(room_name: str, inventory: set[str]) -> None:
        print(
            f'\n{" - " * 27}'
            f'\nYou are in the {room_name}'
        )
        if inventory:
            print('Inventory:', ', '.join(inventory))
    
    
    def go(room: dict[str, str], direction: str) -> str | None:
        next_room = room.get(direction)
        if next_room is None:
            print('You cannot go that way.')
            return None
    
        print(f'You go {direction}.')
        return next_room
    
    
    def get_item(item: str, inventory: set[str], room: dict[str, str]) -> None:
        if item in inventory:
            print('You already have the', item, 'in your inventory.')
        else:
            if room.get('item') == item:
                print(item, 'retrieved!')
                inventory.add(item)
                del room['item']
            else:
                print('Cannot find the', item)
    
    
    def main() -> None:
        prompt()
        inventory = set()
        room_name = 'Locker Room'
        
        while True:
            room = rooms[room_name]
            describe_turn(room_name, inventory)
            indicate_item(room, inventory)
    
            if encounter_boss(room, inventory):
                break
    
            match input('Which direction will you go? ').split(maxsplit=1):
                case 'go', direction:
                    room_name = go(room, direction.lower()) or room_name
    
                case 'get', item:
                    get_item(item, inventory, room)
    
                case 'exit', :
                    print('Game over. Thank you for playing!')
                    break
    
                case _:
                    print('Invalid command')
    
    
    if __name__ == '__main__':
        main()
    
                Welcome to professional wrestling!
    
    Vance McMan has locked all wrestlers into an evil contract.
    
    You must collect all 6 items and defeat Vance to free all the wrestlers.
    
    To move:    'go [north | south | east | west]'
         'get item name'
    
     -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  - 
    You are in the Locker Room
    Which direction will you go? go south
    You go south.
    
     -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  - 
    You are in the Dressing Room
    You see a Rics Robe
    Which direction will you go? get Rics Robe
    Rics Robe retrieved!
    
    ...
    
    -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  - 
    You are in the Office
    Inventory: StoneCold Beer, Blueprint, RKO Promo Video, Mr.Socko, Rics Robe, Chair
    You beat Vance McMan