I'm getting a keyerror for 'Item' and I can't figure out what I'm doing wrong. it's for the line. item = get_item(state) I'm a noob to coding and I've spent the last 5 hours and can not fix the issue.
NOT IMPORTANT
Scenario
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.
rooms = {
'Master Bedroom': {'South': 'Kitchen', 'North': 'Toy Room', 'East': 'Garage', 'West': 'Closet'},
'Kitchen': {'North': 'Master Bedroom', 'East': 'Bathroom', 'West': 'Backyard', 'Item': 'Cell Phone'},
'Gun Room': {'South': 'Closet', 'East': 'Toy room', 'Item': 'Pistol'},
'Backyard': {'East': 'Kitchen', 'Item': 'ZOMBIE'},
'Garage': {'West': 'Master Bedroom', 'South': 'Bath Room', 'Item': 'Body Armor'},
'Toy Room': {'South': 'Master Bedroom', 'West': 'Gun Room', 'Item': 'Baseball Bat'},
'Closet': {'East': 'Master Bedroom', 'North': 'Gun Room', 'Item': 'Flashlight'},
'Bathroom': {'North': 'Garage', 'West': 'Kitchen', 'Item': 'Bandages'},
}
state = 'Master Bedroom'
def get_new_state(state, direction):
new_state = state
for i in rooms:
if i == state:
if direction in rooms[i]:
new_state=rooms[i][direction]
return new_state
def get_item(state):
return rooms[state]['Item']
def show_instructions():
print('ZOMBIE run Adventure Game')
print('Collect 6 items to win the game, or be eaten by a ZONBIE.')
print('Move commands: go South, go North, go East, go West')
print("Add to Inventory: get 'Item_name'")
print("type quit to end the game")
show_instructions() #calling Function
Inventory = []
while (1):
print('You are in ', state) #printing state
print('Inventory:', Inventory) #printing inventory
item = get_item(state) #calling get_item function
print('You see a ', item) #print
print('--------------------')
if item == 'ZOMBIE':
print('NOM NOM...GAME OVER!')
exit(0)
direction = input('Enter your move:')
if direction == 'go East' or direction == 'go West' or direction == 'go North' or direction == 'go South': #if
direction = direction[3:]
new_state = get_new_state(state, direction) #calling function
if new_state == state: #if
print('The room has wall in that direction enter other direction!')
else:
state = new_state
elif direction == str('get ' + item):
if item in inventory:
print('Item already taken go to another room!!')
else:
inventory.append(item)
else:
print('Invalid direction!')
if len(Inventory) == 6:
print('Congratulations! You have collected all items and defeated the ZOMBIE!')
exit(0)
stop = "go"
while stop != 'quit':
show_instructions()
user_input = input("what would you like to do?")
if user_input == 'quit':
break
The error seems to be the fact that there is no item in the master bedroom. Hence it throws a KeyError. You just need to add an 'Item' value to the rooms['Master Bedroom']
Edit: The context seems to be that the Master Bedroom has no item. So it would be better if you just added a state validation:
def get_item(state):
if state!='Master Bedroom':
return ' a'+rooms[state]['Item']
else:
return 'Nothing'
And just for the text to make sense:
print('You see', item) #print
If you want to avoid KeyError, a useful method of dicts is get.
>>>rooms.get('item')
>>>
you can give a default value as 2nd argument in case the key does not exist:
>>>rooms.get('item', 'this room does not exist')
>>>'this room does not exist'
or in case of nested dicts
>>>rooms = {'kitchen': {'items': ['sink', 'oven']}}
>>>rooms.get('kitchen').get('items')
>>>['sink', 'oven']
Related
I am having real problems with getting my program to work. Every time I fix an error another one follows. The code below is what i have so far (only been coding for about 2 months so be nice :) ). I am stuck with my code note allowing me to advance to the next room. It keeps repeating the same room. I put the entire code here as i dont exactly know where my error is. Any suggestions?
I will gladly send what the exact instructions are for the project if needed.
rooms = {
'Stable': {'West': 'Foyer'},
'Foyer': {'South': 'Great Hall'},
'Great Hall': {'South': 'Dining Room', 'East': 'Study', 'West': 'Balcony’, ‘North’: ‘Foyer'},
'Study': {'North': 'Library', 'West': 'Great Hall'},
'Dining Room': {'North': 'Great Hall', 'East': 'Kitchen'},
'Library': {'South': 'Study'},
'Kitchen': {'West': 'Dining Room'},
'Balcony': {'East': 'Great Hall'},
}
items = {
'Foyer': {'Shield'},
'Great Hall': {'Sword'},
'Study': {'Armor'},
'Library': {'Spell Book'},
'Dining Room': {'Helmet'},
'Kitchen': {'Cooked Chicken'},
'Balcony': {'Dark Knight'},
}
# Dark Knight is the villain
# Main Title/Menu and Move Commands
print('Dark Knight and the Royal Palace Text Adventure Game')
print('Collect 6 items to win the game, or be beaten by the Dark Knight.')
print('Move Commands: North, South, East, West, Exit')
print('Add to Inventory: get ''')
# Start the player in the Great Hall
state = 'Stable'
# store the items collected so far
inventory = []
# function
def get_new_statement(state, direction):
new_statement = state # declaring
for i in rooms: # loop
if i == state: # if
if direction in rooms[i]: # if
new_statement = rooms[i][direction] # assigning new_statement
return new_statement # return
while True: # loop
print('----------------------------------------------')
print('You are in the', state) # printing state
# display inventory
print('Current inventory: ', inventory)
direction = input('Enter which direction you want to go or enter exit: ') # asking user for input
direction = direction.capitalize() # making first character capital remaining lower
if direction == 'Exit': # if
print('----------------------------------------------')
print('Thank you for playing! Challenge the Dark Knight again soon!')
exit(0) # exit function
if direction == 'East' or direction == 'West' or direction == 'North' or direction == 'South': # if
new_statement = get_new_statement(state, direction) # calling function
if new_statement == state: # if
print('That’s a wall! Try another direction.') # print
else:
state = new_statement # changing state value to new_statement
else:
print('Invalid Command!') # print
# ask to collect item in current room
if state in items.keys() and items[state] != None and items[state] != 'Balcony':
print('This room has ', items[state])
option = input('Do you want to collect it (y/n): ')
if option[0] == 'y' or option == 'Y':
inventory.append(items[state])
items[state] = None
# if we have reached a room then we either win or loose the game
if state in items.keys() and items[state] == 'Dark Knight':
if len(inventory) == 6:
print('Congratulations you have saved the Royal Family!!')
else:
print("You have been defeated!")
print('try again')
break
In my last assignment my code worked and i was able to move rooms. In the final project however my character isn't able to move rooms and the code looks exactly alike. Can someone share some light on why my character will not move rooms. My code is pasted below. I don't get any errors in Pycharm. But I keep getting invalid move message everytime i type a direction. After reviewing my code for hours I can't find the issue of why my character will not move rooms. ** Update issue was fixed but now i can not collect items in the room. My inventory_list.append code looks good but for some reason i can not collect the item in the room.
rooms = {
'Lobby': {'East': 'Kennel room','item': 'No items'},
'Kennel room': {'west': 'Lobby', 'south': 'Pet wash', 'east': 'Grooming room', 'north': 'Infirmary', 'item': 'Josh'},
'Infirmary': {'south': 'Kennel room', 'east': 'Play room', 'item': 'Chello'},
'Play room': {'west': 'Infirmary','item': 'Dog Catcher!'}, # The villain is in the Playroom
'Grooming room': {'west': 'Kennel room', 'north': 'Food storage', 'item': 'Taco'},
'Food storage': {'south': 'Grooming room', 'item': 'Therral'},
'Pet wash': {'north': 'Kennel room', 'east': 'Training room', 'Item': 'Dwan'},
'Training room': {'west': 'Pet Wash', 'item': 'Neisha'}
}
def player_status(): # indicate room and inventory
print("-" * 20)
print('You are in the {}'.format(current_room))
print('In this room you find {}'.format(rooms[current_room]['item']))
print('Inventory:', inventory_items)
print("-" * 20)
# Print main menu and commands
def player_instructions():
print("-" * 20)
print('Escape the pound!!')
print('You are Sam a lost pup trapped at the pound trying to escape to find your family.')
print('During your escape you and your six friends are separated when the alarm goes off.')
print('Before you escape to freedom you must find your six friends Neisha, Therral, Taco, Josh, Chello, and Dwan.')
print('Beware the dog catcher is out to get you and once he does its game over.')
print('Collect all six friends and escape before the dog catcher gets you.')
print('\nMove through the room using commands: "north, "south", "east", or "west"')
print('Once you enter the room with a friend to collect use the command: "(Get (friends name))"')
print('Type "exit" to escape the game at anytime')
print("-" * 20)
player_instructions()
inventory_items = [] # Inventory starts empty
current_room = 'Lobby' # Starting point
player_move = ''
while current_room != 'Exit':
player_status()
# Get user input
player_move = input('Enter your move:\n')
# Quit game
if player_move in ('Exit', 'exit'):
current_room = 'Exit'
print('Play again soon!')
break
# Lose game
if player_move in rooms[current_room]:
current_room = rooms[current_room][player_move]
if current_room == 'Play room':
print("SWIPE!! OH NO!! You were caught by the dog catcher"'\nGame Over')
break
else:
# Movement
if player_move in rooms[current_room]:
if player_move in rooms[current_room]['item']:
inventory_items.append(player_move)
print('You have found {}'.format['item'])
else:
current_room = rooms[current_room][player_move]
else:
print('Invalid command')
# Win game
if len(inventory_items) != 6:
pass
else:
print("Congratulations!! You helped Sam gather all of his friends and escape the dog catcher. \nYou Win")
def main():
inventory = [] # A list for the player to store their items
# Dictionary of the Rooms and which directions are to be taken for each room.
# This links one room to the other rooms.
rooms = {
'Lobby': {'East': 'Gym'},
'Gym': {'West': 'Lobby', 'South': 'Pool area', 'item': 'Dumbbell'},
'Pool area': {'North': 'Gym', 'East': 'Restaurant', 'West': 'Playroom', 'South': 'Your Room',
'item': 'Sunscreen'},
'Restaurant': {'West': 'Pool area', 'North': 'Bathrooms', 'item': 'Cloth Napkin'},
'Bathrooms': {'South': 'Restaurant', 'item': 'Toilet Roll'},
'Playroom': {'East': 'Pool area', 'South': 'Supply Closet', 'item': 'Deck of Cards'},
'Supply Closet': {'North': 'Playroom', 'item': 'Uniform'},
'Your Room': {'North': 'Pool area', 'East': 'Suite', 'item': 'Laptop'},
'Suite': {'West': 'Your Room'}}
current_room = 'Lobby' # Set the current room to begin the gameplay loop.
show_menu()
while current_room != 'Exit': # If the current room is not the exit the user can continue to the next room.
item = show_status(current_room, inventory, rooms) # Displays the current room and items in inventory.
moves = rooms[current_room]
# The player will be prompted for which move they want to make.
player_move = input("Enter 'go North, South, East or West' to move, or get Item, or 'Exit': ")
if player_move == 'Exit': # The user will exit the game.
current_room = 'exit'
break # Stops the game from continuing.
elif player_move.split()[-1] in rooms[current_room]: # Valid command from the user.
current_room = rooms[current_room][player_move.split()[-1]]
# The player will move from one room to the other.
elif player_move.split()[0].capitalize() == "Get": # Command to collect item to inventory.
if player_move == "get " + item:
get_item(item, inventory, rooms, current_room)
# The item in the current room will be put in the inventory.
print(item, "collected") # Tells the player that the item was collected.
else:
print("Invalid command")
else: # Set the invalid move command.
print("Invalid Move. There's no room to the {}".format(player_move))
print("^" * 20) # Set separating line.
if len(inventory) == 7: # Amount of items required to win the game.
print('Congratulations! You have collected all items and now can move to the Suite'
'to face off the politician!')
print('You have defeated the Corrupt Politician')
print('Thanks for playing')
break # The game will end after collecting all items.
main()
So I made this code for a class of a text based game where the player goes through different rooms and collects items. I want to help my player know which directions they can take whenever they enters the room. That way they are not guessing which way to go or a put a map.
I think your code is a bit messy, you should separate the "item" from the rooms dic so you could check if the "current_room" is in the "rooms" and find the room's choices you have to go ahead.
if current_room in rooms.keys():
print(list(rooms.get(current_room).keys())[0]) #print the direction you can go to
current_room = list(rooms.get(current_room).values())[0] #change the rooms
print(current_room)
According to the code above the player will go to the next room, but it always is the first room in the values.
For example - from "Gym" it will always go to the "Lobby", and from "Lobby" it will always go to the "Gym".
So it could stack in a loop.
You can play with the list index and randomize it so the rooms will change.
But before you change it you should remove the "item" from the dic, cause the code will consider "item" as a direction that can cause problems.
Good luck!
I am working on my final project for my intro to scripting class. we are using python. my code seems to be doing well except a a few lines of code, i cannot seem to define my item and state. The errors are traceback errors on lines 27 and 45.
Here is my code:
# declaration
rooms = {
'Town Square': {'North': 'Bookstore', 'South': 'Restaurant', 'East': 'Tailor', 'West': 'Jeweler'},
'Tailor': {'East': ' Town Square', 'item': 'Suit'},
'Restaurant': {'North': 'Town Square', 'East': 'Hair Dresser', 'item': 'salad'},
'Hair Dresser': {'West': 'Restaurant', 'item': 'Comb'},
'Book Store': {'South': 'Town Square', 'East': 'Shoemaker', 'item': 'Bible'},
'Shoemaker': {'West': 'Book Store', 'item': 'Shoes'},
'Jeweler': {'North': 'Chapel', 'West': 'Town Square', 'item': 'Ring'},
'Chapel': {'South': 'Chapel', 'item': 'Wife'}
}
state = 'Town Square'
# function
def get_new_state(state, direction):
new_state = state # declaraing
for i in rooms: # loop
if i == state: # if
if direction in rooms[i]: # if
new_state = rooms[i][direction] # assigning new_state
return new_state # return
# function
def get_item(state):
return rooms[state]['Item'] # returning Item value
# function
def show_instructions():
# print a main menu and the commands
print("Welcome to the Wedding Adventure!")
print("Collect all 6 items before you reach the chapel, so you will not die of embarrassment when you get left at "
"the altar")
print("Move commands: go South, go North, go East, go West")
print("Add to Inventory: get 'item name'")
show_instructions() # calling function
inventory = []
while (1): # gameplay loop
print('You are in ', state) # printing state
print('Inventory:', inventory) # printing inventory
item = get_item(state) # calling get_item function
print('You see a', item) # print
print('------------------------------')
if item == 'Wife': # if
print('SLAP ... GAME OVER!')
print('Thanks for playing! Hope you enjoyed it!')
exit(0)
direction = input('Enter your move: ') # asking user
if (direction == 'go East' or direction == 'go West' or direction == 'go North' or direction == 'go South'): # if
direction = direction[3:]
new_state = get_new_state(state, direction) # calling function
if new_state == state: # if
print('The room has wall in that direction enter other direction!') # print
else:
state = new_state # changing state value to new_state
elif direction == str('get '+item): # if
if item in inventory: # if item already present in inventory
print('Item already taken go to another room!!')
else:
print(f"{item} retrieved!\n")
inventory.append(item) # appending
else:
print('Invalid direction!!') # print
if len(inventory) == 6:
# print
print('Congratulations! You have collected all items and got married!')
print('Thanks for playing! Hope you enjoyed it!')
exit(0)
The code runs but has traceback errors on when initially run. I am not certain on how to trace the inventory for the items. Should I create a new dictionary for inventory?
I have two small problems, first I need help with the win condition, after collecting all the items I should go in the petting area and get the output 'You defeated the Killer Wolf so I hope you enjoyed playing.
other than this
I have the problem where I can add the same item to my inventory twice, this should not happen, I should get an output message saying 'You already have this item'.
can anyone please help me solve this?
this is the code I have so far.
def game_instructions():
# print a main menu and the commands
print("Killer Wolf Text Game")
print("---" * 20)
print("Collect 6 items to win the game, or be killed by the Wolf.")
print("---" * 20)
print('Move Commands: North , South , East , or West.')
print("---" * 20)
print("Add to Inventory: get 'item name'")
print("---" * 20)
game_instructions()
rooms = {
"Main fair ground": {'South': 'Food stand', 'North': 'Arcade', 'East': 'Corn field', 'West': 'Candy shop'},
"Food stand": {'North': 'Main fair ground', 'East': 'Security', 'item': 'meat'},
"Security": {'West': 'Food stand', 'item': 'armor'},
"Arcade": {'South': 'Main fair ground', 'East': 'Gift shop', 'item': 'sword'},
"Gift shop": {'West': 'Arcade', 'item': 'gloves'},
"Candy shop": {'item': 'candy', 'East': 'Main fair ground'},
"Corn field": {'West': 'Main fair ground', 'North': 'Petting area', 'item': 'repellent'},
"Petting area": {'South': 'Corn field', 'item': 'Killer Wolf'}
}
current_room = 'Main fair ground' # starts player in the Main fair ground
inventory = [] # Adds an inventory
def get_new_room(current_room, direction):
new_room = None
for i in rooms: # starts loop
if i == current_room: # if statement
if direction in rooms[i]: # if statement
new_room = rooms[i][direction] # Assigns new room.
else:
new_room = current_room #this assigns new room to current room if the mentioned direction is not valid
return new_room # returns new room
def get_item(current_room):
if 'item' in rooms[current_room]: # if statement
return rooms[current_room]['item'] # return statement
else:
return 'This room has no item!' # return statement
while (current_room): # gameplay loop
print('You are in the {}'.format(current_room)) # tells player what room they are in.
print('Inventory:', inventory) # shows player their inventory
item = get_item(current_room) # defines item as get item
print('You found the:', item) # tells the player what item they have found
if item == 'Killer Wolf' and len(inventory)<6: # if statement
print('NOM NOM, You did not collected all the necessary items to survive! The game has ended, I hope you '
'enjoyed!') # notifies player game has ended.
break # ends game
direction = input('Enter direction you would like to move. >>') # gets direction from player.
direction = direction.capitalize() # Capitalizes the players input to match what is in the dictionary.
if (direction == 'North' or direction == 'South' or direction == 'East' or direction == 'West'): # if statement
new_room = get_new_room(current_room, direction) # Calling function
if new_room == current_room: # if statement
print('That is a wall not an exit. Try Again!') # Print statement
else:
current_room = new_room # declares current room as new room
elif direction == str('get ' + item).capitalize(): # input statement to add item
if 'item' in inventory: # if statement
print('You have already collected this item. Move to another room!') # print statement
else:
inventory.append(item) # adds item to inventory
else:
print('Not a valid direction!') # Print statement
if len(inventory) == 6: # if statement
print("Congratulations!! You have collected all the necessary items to defeat the killer wolf")
If you could please fix and upload the code here for me I would really appreciate it.
Here's the code with all the bug fixes:
def game_instructions():
# print a main menu and the commands
print("Killer Wolf Text Game")
print("---" * 20)
print("Collect 6 items to win the game, or be killed by the Wolf.")
print("---" * 20)
print('Move Commands: North , South , East , or West.')
print("---" * 20)
print("Add to Inventory: get 'item name'")
print("---" * 20)
game_instructions()
rooms = {
"Main fair ground": {'South': 'Food stand', 'North': 'Arcade', 'East': 'Corn field', 'West': 'Candy shop'},
"Food stand": {'North': 'Main fair ground', 'East': 'Security', 'item': 'meat'},
"Security": {'West': 'Food stand', 'item': 'armor'},
"Arcade": {'South': 'Main fair ground', 'East': 'Gift shop', 'item': 'sword'},
"Gift shop": {'West': 'Arcade', 'item': 'gloves'},
"Candy shop": {'item': 'candy', 'East': 'Main fair ground'},
"Corn field": {'West': 'Main fair ground', 'North': 'Petting area', 'item': 'repellent'},
"Petting area": {'South': 'Corn field', 'item': 'Killer Wolf'}
}
current_room = 'Main fair ground' # starts player in the Main fair ground
inventory = [] # Adds an inventory
def get_new_room(current_room, direction):
new_room = None
for i in rooms: # starts loop
if i == current_room: # if statement
if direction in rooms[i]: # if statement
new_room = rooms[i][direction] # Assigns new room.
else:
new_room = current_room #this assigns new room to current room if the mentioned direction is not valid
return new_room # returns new room
def get_item(current_room):
if 'item' in rooms[current_room]: # if statement
return rooms[current_room]['item'] # return statement
else:
return 'This room has no item!' # return statement
while (current_room): # gameplay loop
print('You are in the {}'.format(current_room)) # tells player what room they are in.
print('Inventory:', inventory) # shows player their inventory
item = get_item(current_room) # defines item as get item
print('You found the:', item) # tells the player what item they have found
if item == 'Killer Wolf':
if len(inventory)<6:
print('NOM NOM, You did not collected all the necessary items to survive! The game has ended, I hope you '
'enjoyed!') # notifies player game has ended.
break
elif len(inventory)==6:
print("You defeated the Killer Wolf so I hope you enjoyed playing")
break
direction = input('Enter direction you would like to move. >>') # gets direction from player.
direction = direction.capitalize() # Capitalizes the players input to match what is in the dictionary.
if (direction == 'North' or direction == 'South' or direction == 'East' or direction == 'West'): # if statement
new_room = get_new_room(current_room, direction) # Calling function
if new_room == current_room: # if statement
print('That is a wall not an exit. Try Again!') # Print statement
else:
current_room = new_room # declares current room as new room
elif direction == str('get ' + item).capitalize(): # input statement to add item
if item in inventory: # if statement
print('You have already collected this item. Move to another room!') # print statement
else:
inventory.append(item) # adds item to inventory
else:
print('Not a valid direction!') # Print statement
if len(inventory) == 6: # if statement
print("Congratulations!! You have collected all the necessary items to defeat the killer wolf")
NOTE: Please copy the changes over properly, I made sure it all works