Home > Mobile >  Receiving a KeyError, not sure how to void it
Receiving a KeyError, not sure how to void it

Time:10-09

You work for a small company that creates text-based games. You recently pitched your design ideas for a text-based adventure game to your team. Your team was impressed by all of your designs, and would like you to develop the game! You will be able to use the map and the pseudocode or flowcharts from your designs to help you develop the code for the game. In your code, you have been asked to include clear naming conventions for functions, variables, and so on, along with in-line comments. Not only will these help you keep track as you develop, but they will help your team read and understand your code. This will make it easier to adapt for other games in the future. Recall that the game requires players to type in a command line prompt to move through the different rooms and get items from each room. The goal of the game is for the player to get all of the items before encountering the room that contains the villain. Each step of the game will require a text output to let the player know where they are in the game, and an option of whether or not to obtain the item in each room.

The other responses to this question the code does not meet the requirements for the assignment. For example, theres needs to be show instructions and show status functions. Also, there is only suppose to be 1 dictionary with items included.

Currently having trouble understanding why I'm getting a traceback error, any type of help would be amazing. I also noticed none of the previous prints / instructions I coded aren't being displayed.

Error Image

Full code:

Function to display game instructions

def show_instructions():
    # System displays a menu and commands for the user
    print("You're waking up...")
    print("*Apple Watch Alarm Starts Blasting*")
    print("You look down to check why the watch is going off, you then see an amber alert.")
    print("*WARNING: STATE-WIDE PANDEMIC VIRUS, PLEASE SEEK SHELTER AND AVOID CONTACT WITH THE INFECTED!*")
    print("While gaining your consciousness back bit by bit, you notice your self in the middle of a Hollywood Hills "
          "mansion's bathroom, with nothing but a distant echo of grunting and moaning you soon realize a zombie "
          "outbreak has occurred!")
    print("In order to make it out successfully from the infected mansion you must collect 5 items and your friend "
          "David who have all been scattered across the mansion during the party.")
    print("Move Commands: go South, go North, go East, go West")
    print("Add to Inventory/Grab: get 'item name'\n")


# Main function
def main():
    # Calling function to display instructions
   show_instructions()

    # A dictionary for the zombie survival text game
    # This dictionary links all 8 rooms to one another
    rooms = {'Bathroom' : { 'West' : 'Hallway'}, # First Room
            'Hallway': { 'East': 'Bathroom', 'South': 'Living Room', 'item' : 'Backpack'},
            'Living Room': { 'North': 'Hallway', 'West': 'Backyard', 'South': 'Office', 'East': 'Kitchen', 'item': 'Gun'},
            'Backyard': { 'East': 'Living Room', 'item': 'Map'}, # Exit room
            'Office': { 'North': 'Living Room', 'East': 'Garage', 'item': 'Ammo'},
            'Garage': { 'West': 'Office', 'item': 'David'},
            'Kitchen': { 'West': 'Living Room', 'North': 'Basement', 'item': 'Long steak knife'},
            'Basement': { 'South': 'Kitchen', 'item': 'Zombies'}, # Avoid
            }
        
    # Displays games starting room
    current_room = 'Bathroom'
    # System creates an empty list called "inventory"
    inventory = []
    
    # A loop to simulate the player moving between rooms
    while True:
        # If current_room is Backyard then break the loop
        if current_room == 'Backyard':
            print("\nYou are in the", current_room)
            print("You see the Exit!",)
            if len(inventory) == 6:
                print("\nCongrats! You have collected all the items and your friend David and have made your way out the infected mansion!")
            else:
                print("\nYou don't have everything you need, you won't survive out there... GAME RESTARTING!")
            break
    
        # Printing the current_room
        print("\nYou are in the", current_room)
    
        # Prompts user to pickup the item within the room
        if rooms[current_room]['item'] != None:
            print("You see a", rooms[current_room]['item'])
            opinion = input("get " rooms[current_room]['item'] "?(Y/N:").upper()
            # Validating the users input
            while opinion not in ['Y','N']:
                print ("Invalid input. Try again")
                opinion = input("Get " rooms[current_room]['item'] "?(Y/N): ").upper()
            if opinion == 'Y':
                inventory.append(rooms[current_room]['item'])
                rooms[current_room]['item'] = None
    
        else:
            print("The item in this room has already been grabbed or there was nothing in here")
    
        # System prints inventory
        print("Inventory:", inventory)
    
        # System grabs users input for move directions
        direction = input("Direction to move?(South,North,East,West): ").title()
        directions = list(rooms[current_room].keys())
        directions.remove('item')
        # Confirming users direction
        while direction not in directions:
            print("Invalid direction from " current_room ". Try another move")
            direction = input("Direction to move?(East,West,North,South): ").title()
    
        # System develops the next_room
        next_room = rooms[current_room][direction]
        print("You have now moved to",next_room)
        print("-------------------------------------------")
    
        # Updating current_room
        current_room = next_room

# Printing the games end message
print("\nThank you for playing Zombie Mansion Survival!")

# Calling main function
main()

CodePudding user response:

You can use get(<>, None) to avoid key error

if rooms[current_room].get('item', None) != None:
    pass

CodePudding user response:

You can use __contains__ to check the key existence.

if rooms[current_room].__contains__('item'):

or use in more python way:

if 'item' in rooms[current_room]:
  • Related