I have been assigned to create a text-based game. I can go in all directions no problem, but when I go to "get" the item or contents of the room, it displays my "Else" message: "I don't see that here."
How can I correct this and be sure it is added to my Inventory?
Below is what I have so far:
#Start
rooms = {
'Entrance': {'name': 'Entrance', 'North': 'Food Area', 'East': 'Carousel', 'West': 'Game Area',
'content': 'none', 'text': 'The Entrance'},
'Carousel': {'name': 'Carousel', 'West': 'Entrance', 'contents': ['balloon animal'],
'text': 'This is the Carousel. Grab the Balloon Animal.'},
'Game Area': {'name': 'Game Area', 'North': 'FunHouse', 'East': 'Entrance', 'contents': ['big red shoes'],
'text': 'This is the Game Area. Grab the Big Red Shoes.'},
'Food Area': {'name': 'Food Area', 'South': 'Entrance', 'East': 'Tilt-O-Whirl', 'North': 'Ferris Wheel',
'contents': ['red nose'], 'text': 'This is the Food Area. Grab the Red Nose.'},
'Ferris Wheel': {'name': 'Ferris Wheel', 'South': 'Food Area', 'contents': ['clown suit'],
'text': 'This is the Ferris Wheel. Grab the Clown Suit.'},
'Roller Coaster': {'name': 'Roller Coaster', 'South': 'Tilt-O-Whirl', 'contents': ['blow torch'],
'text': 'This is the Roller Coaster. Grab the Blow Torch.'},
'Tilt-O-Whirl': {'name': 'Tilt-O-Whirl', 'North': 'Roller Coaster', 'West': 'Food Area',
'contents': ['rainbow wig'], 'text': 'This is the Tilt-O-Whirl. Grab the Rainbow Wig.'},
'FunHouse': {'name': 'FunHouse', 'South': 'Game Area', 'contents': ['clown'],
'text': 'This is the FunHouse. Beat the Clown!'}
}
directions = ['North', 'South', 'East', 'West']
currentRoom = rooms['Entrance']
Inventory = []
def show_instructions():
# print a main menu and the commands
print('-------------------------------------------------------')
print("Welcome to A Day at the Fair")
print("Collect all 6 items while avoiding the clown or be captured by Nickel Knowing")
print("Move commands: South, North, East, West")
print("Add to Inventory: get 'contents'")
print('-------------------------------------------------------')
show_instructions()
while True:
# display current location
print('You are in {}.'.format(currentRoom['text']))
# get user input
command = input('\nWhat do you do? ').strip()
# movement
if command in directions:
if command in currentRoom:
currentRoom = rooms[currentRoom[command]]
else:
# bad movement
print("You cant go that way.")
# quit game
elif command.lower() in ('q', 'quit'):
break
# bad command
elif command.lower().split()[0] == 'get':
item = command.lower().split()[1]
if item in [x.lower() for x in currentRoom['contents']]:
Inventory.append(item)
print('You grabbed {}.'.format(currentRoom['contents']))
else:
print("I don't see that here.")
while currentRoom in ['FunHouse']:
if len(Inventory) == 6:
print('You collected all of the items, and defeated Nickel Knowing the Clown!')
else:
print('It looks like you have not found everything, you lose!')
break
So the problem was that when you check for [x.lower() for x in currentRoom['contents']], you end up searching for a list instead of a string (i.e. checking for '[big red shoes]' instead of just 'big red shoes'). Replace that line with just currentRoom['contents']. Also replace item = command.lower().split()[1] with item = " ".join(command.lower().split()[1:]) because you want not just the first word after "get", but the rest of the phrase itself.
Full code:
rooms = {
'Entrance': {'name': 'Entrance', 'North': 'Food Area', 'East': 'Carousel', 'West': 'Game Area',
'content': 'none', 'text': 'The Entrance'},
'Carousel': {'name': 'Carousel', 'West': 'Entrance', 'contents': ['balloon animal'],
'text': 'This is the Carousel. Grab the Balloon Animal.'},
'Game Area': {'name': 'Game Area', 'North': 'FunHouse', 'East': 'Entrance', 'contents': ['big red shoes'],
'text': 'This is the Game Area. Grab the Big Red Shoes.'},
'Food Area': {'name': 'Food Area', 'South': 'Entrance', 'East': 'Tilt-O-Whirl', 'North': 'Ferris Wheel',
'contents': ['red nose'], 'text': 'This is the Food Area. Grab the Red Nose.'},
'Ferris Wheel': {'name': 'Ferris Wheel', 'South': 'Food Area', 'contents': ['clown suit'],
'text': 'This is the Ferris Wheel. Grab the Clown Suit.'},
'Roller Coaster': {'name': 'Roller Coaster', 'South': 'Tilt-O-Whirl', 'contents': ['blow torch'],
'text': 'This is the Roller Coaster. Grab the Blow Torch.'},
'Tilt-O-Whirl': {'name': 'Tilt-O-Whirl', 'North': 'Roller Coaster', 'West': 'Food Area',
'contents': ['rainbow wig'], 'text': 'This is the Tilt-O-Whirl. Grab the Rainbow Wig.'},
'FunHouse': {'name': 'FunHouse', 'South': 'Game Area', 'contents': ['clown'],
'text': 'This is the FunHouse. Beat the Clown!'}
}
directions = ['North', 'South', 'East', 'West']
currentRoom = rooms['Entrance']
Inventory = []
def show_instructions():
# print a main menu and the commands
print('-------------------------------------------------------')
print("Welcome to A Day at the Fair")
print("Collect all 6 items while avoiding the clown or be captured by Nickel Knowing")
print("Move commands: South, North, East, West")
print("Add to Inventory: get 'contents'")
print('-------------------------------------------------------')
show_instructions()
while True:
# display current location
print('You are in {}.'.format(currentRoom['text']))
# get user input
command = input('\nWhat do you do? ').strip()
# movement
if command in directions:
if command in currentRoom:
currentRoom = rooms[currentRoom[command]]
else:
# bad movement
print("You cant go that way.")
# quit game
elif command.lower() in ('q', 'quit'):
break
# bad command
elif command.lower().split()[0] == 'get':
item = " ".join(command.lower().split()[1:])
if item in currentRoom['contents']:
Inventory.append(item)
print('You grabbed {}.'.format(currentRoom['contents']))
else:
print("I don't see that here.")
while currentRoom in ['FunHouse']:
if len(Inventory) == 6:
print('You collected all of the items, and defeated Nickel Knowing the Clown!')
else:
print('It looks like you have not found everything, you lose!')
break
Related
I've never posted on here so I'll do my best to format everything correctly. I am writing a text-based Python game for school that involves collecting items and a villain. The villain is designed to end the game if encountered. I wanted to randomize the villain's location between a 'window' and 'front door' option, making the end random chance if you win or lose. (see FIXME) Secondly, I was having trouble separating the text that displays when you enter a room and the text regarding collectibles. I was trying to make it so that once an item is collected the collectible text no longer displays as that item is no longer in the room after it is collected. I was having a lot of trouble with this under the comment #look around. Thank you in advance for the help :P
rooms = {
'Outside': {'name': 'Outside', 'North': 'Dining Room',
'text': 'You are outside and stare at the back door to the house.'},
'Dining Room': {'name': 'Dining Room', 'North': 'Living Room', 'contents': ['vase'],
'West': 'Kitchen', 'text': 'You are in the dining room.', 'item_get': 'There is a vase in this room... It looks valuable.'},
'Kitchen': {'name': 'Kitchen', 'East': 'Dining Room', 'contents': 'Blender',
'text': 'You are in the kitchen. There is a blender on the counter.'},
'Living Room': {'name': 'Living Room', 'South': 'Dining Room', 'East': 'Stairs', 'West': 'Bathroom', 'contents': ['TV'],
'text': 'You are in the Living room. There is a TV on the wall.'},
'Bathroom': {'name': 'Bathroom', 'East': 'Living Room', 'contents': ['Candle'],
'text': 'You are in the Bathroom. There is a candle on the counter.'},
'Stairs': {'name': 'Stairs', 'North': 'Hallway', 'West': 'Living Room',
'text': 'You are in the stairway. There is a hallway at the top.'},
'Hallway': {'name': 'Hallway', 'East': 'Bedroom', 'West': 'Kids Bedroom',
'text': 'You are in the hallway. There are bedrooms on either side of you.'},
'Bedroom': {'name': 'Bedroom', 'West': 'Hallway', 'contents': ['Jewelry'],
'text': 'You are in the bedroom. There is jewelry on the dresser.'},
'Kids Bedroom': {'name': 'Kids Bedroom', 'East': 'Hallway', 'contents': ['Music box'],
'text': 'You are in a kids bedroom. There is a music box on a shelf.'},
#FIXME: ESCAPE ROUTES
#is there a way to randomize where the villain will be between two exit options?
}
directions = ['North', 'South', 'East', 'West']
items = ['look around']
look_around = ['item_get']
currentRoom = rooms['Outside']
carrying = []
print('Hello. You are outside')
while True:
# display current location
print()
print(format(currentRoom['text']))
# get input
command = input('\nWhat next? ').strip()
# movement
if command in directions:
if command in currentRoom:
currentRoom = rooms[currentRoom[command]]
else:
print("You can't go that way.")
#look around
if command in items:
if command in look_around:
look_around = rooms[items[command]]
else:
print("There is nothing to see.")
# quit game
elif command.lower() in ('e', 'exit'):
break
elif command.lower().split()[0] == 'get':
item = command.lower().split()[1]
if item in currentRoom['contents']:
carrying.append(item)
print('You stole the {}!'.format(currentRoom['contents']))
else:
print("That object is not in this room.")
I'm creating a room exploration game with Python but am having issues with item collection and the win condition being met (collecting all items to 'win' and losing if not all items are collected). Room movement, help and quitting function but I'm confused where to begin with items. I created an elif for 'get' to collect items but it didn't work. If I could get help with getting items from my dictionary would help a lot. Thank you.
rooms = {'Start room': {'name': 'Start room', 'west': 'West room', 'east': 'East room', 'north': 'Hallway',
'text': 'You are in the Start room.'},
'Hallway': {'name': 'Hallway', 'north': 'Hallway2', 'item': 'chips',
'text': 'You are in the Hallway.'},
'Hallway2': {'name': 'Hallway2', 'north': 'Hallway3', 'item': 'soda',
'text': 'You are in the Hallway2.'},
'Hallway3': {'name': 'Hallway3', 'north': 'Final room', 'item': 'stick',
'text': 'You are in the Hallway #3.'},
'Side room': {'name': 'Side room', 'east': 'Hallway3', 'item': 'cookie bug',
'text': 'You are in the Side room.'},
'Final room': {'name': 'Final room', 'south': 'Hallway3',
'text': 'You are in the Final room.'}, # boss room
'West room': {'name': 'West room', 'east': 'Start room', 'item': 'crown',
'text': 'You are in the West room.'},
'East room': {'name': 'East room', 'west': 'Start room', 'item': 'cape',
'text': 'You are in East room.'}}
def get_item(item_wants, current_room, inventory):
if 'item' in rooms[current_room]:
item_can_get = rooms[current_room]['item']
if item_wants != item_can_get.lower():
print(f'There is no {item_can_get} in this room')
else:
print(f'You just picked up {item_wants}')
inventory.append(item_wants)
return item_wants
def help_file(DIRECTIONS):
print(f"Use {DIRECTIONS} to move! If you would like to quit, type 'quit'.")
def get_input():
arg = '' # default if no arg
input_list = input('Enter move, get or exit:').split()
command = input_list[0]
if len(input_list) > 1:
arg = input_list[1]
return command, arg
def main():
inventory = []
DIRECTIONS = ['north', 'south', 'east', 'west']
current_room = 'Start room'
while True:
# location
print('You are in {}.'.format(current_room))
print("Inventory:", inventory)
# get user input
c, direction = get_input()
# moving
if c == 'move' and direction in DIRECTIONS:
if direction in rooms[current_room]:
current_room = rooms[current_room][direction]
else:
print(f'You cannot go {direction} from this room')
elif c == 'get':
pass
elif c == 'help':
help_file(DIRECTIONS)
elif c == 'quit':
print('Game quitting...')
break
else:
print('Invalid statement')
if current_room == 'Final room' and len(inventory) < 6:
print('You lost ! You forgot to collect all the items! GAME OVER...')
break
if current_room == 'Final room' and len(inventory) >= 6:
print('You did it! You collected all the items and are with your cool new friend! The end!')
break
print()
main()
In testing out your code it appeared where you were getting stuck was with the "getting" of items within a room. With that, I focused on tweaking the "get_item" function. Following is a copy of your code with some tweaks to the dictionary so that one could move about rooms a little easier and a refined "get_item" function.
rooms = {'Start room': {'name': 'Start room', 'west': 'West room', 'east': 'East room', 'north': 'Hallway',
'text': 'You are in the Start room.'},
'Hallway': {'name': 'Hallway', 'north': 'Hallway2', 'south': 'Start room', 'item': 'chips',
'text': 'You are in the Hallway.'},
'Hallway2': {'name': 'Hallway2', 'north': 'Hallway3', 'south': 'Hallway', 'item': 'soda',
'text': 'You are in the Hallway2.'},
'Hallway3': {'name': 'Hallway3', 'north': 'Final room', 'south': 'Hallway2', 'west': 'Side room', 'item': 'stick',
'text': 'You are in the Hallway #3.'},
'Side room': {'name': 'Side room', 'east': 'Hallway3', 'item': 'cookie',
'text': 'You are in the Side room.'},
'Final room': {'name': 'Final room', 'south': 'Hallway3',
'text': 'You are in the Final room.'}, # boss room
'West room': {'name': 'West room', 'east': 'Start room', 'item': 'crown',
'text': 'You are in the West room.'},
'East room': {'name': 'East room', 'west': 'Start room', 'item': 'cape',
'text': 'You are in East room.'}}
item_list = ['chips', 'soda', 'stick', 'cookie', 'crown', 'cape'] # Added this for a simplified check of what items have been acquired
def get_item(item_wants, current_room, inventory): # Enhanced this function.
if 'item' in rooms[current_room]:
item_can_get = rooms[current_room]['item']
if item_wants != item_can_get.lower():
print(f'There is no {item_wants} in this room')
else:
got_item = False
for i in range(len(inventory)):
if (inventory[i] == item_wants):
print("you already have this item")
got_item = True
if (got_item == False):
print(f'You just picked up {item_wants}')
inventory.append(item_wants)
got_all = True
for i in range(len(item_list)):
if (item_list[i] not in inventory):
got_all = False
print("You need to find", item_list[i])
return item_wants
def help_file(DIRECTIONS):
print(f"Use {DIRECTIONS} to move! If you would like to quit, type 'quit'.")
def get_input():
arg = '' # default if no arg
input_list = input('Enter move, get or quit:').split()
command = input_list[0]
if len(input_list) > 1:
arg = input_list[1]
return command, arg
def main():
inventory = []
DIRECTIONS = ['north', 'south', 'east', 'west']
current_room = 'Start room'
while True:
# location
print('You are in {}.'.format(current_room))
print("Inventory:", inventory)
# get user input
c, direction = get_input()
# moving
if c == 'move' and direction in DIRECTIONS:
if direction in rooms[current_room]:
current_room = rooms[current_room][direction]
else:
print(f'You cannot go {direction} from this room')
elif c == 'get':
get_item(direction, current_room, inventory)
elif c == 'help':
help_file(DIRECTIONS)
elif c == 'quit':
print('Game quitting...')
break
else:
print('Invalid statement')
if current_room == 'Final room' and len(inventory) < 6:
print('You lost ! You forgot to collect all the items! GAME OVER...')
break
if current_room == 'Final room' and len(inventory) >= 6:
print('You did it! You collected all the items and are with your cool new friend! The end!')
break
print()
main()
Give that a try.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 months ago.
Improve this question
I am making a text-based game, and when I tried to debug it, my game loop was not executing. It just continues to allow me to move threw rooms when I wanted it to lead to a game over or to the end of the game. I'm unsure what I did wrong and was hoping someone could explain and help me fix it. Thank you!
def status():
print('-' * 20)
print('You are in the {}'.format(current_room['name']))
print('Your current inventory: {}\n'.format(inventory))
if current_room['item']:
print('Item in room: {}'.format(', '.join(current_room['item'])))
print('')
# data setup
rooms = {'Great Hall': {'name': 'Great Hall', 'item': ['none'], 'south': 'Vendetta Room', 'east': 'Kitchen',
'north': 'Potion Lab', 'west': 'Armory',
'text': 'You are in the Great Hall.'},
'Armory': {'name': 'the Armory', 'item': ['fire Sword'], 'east': 'Great Hall', 'north': 'Treasure Room',
'text': 'You are in the Armory.'},
'Treasure Room': {'name': 'the Treasure Room', 'item': ['Magic Ring'], 'south': 'Armory',
'text': 'You are in the Treasure Room.'},
'Potion Lab': {'name': 'the Potion Lab', 'item': ['Healing Potion'], 'east': 'Bedroom', 'south': 'Great Hall',
'text': 'You are in the Potion Lab.'},
'Bedroom': {'name': 'the Bedroom', 'item': ['Magic Key'], 'west': 'Potion Lab',
'text': 'You are in the Bedroom.'},
'Kitchen': {'name': 'the Kitchen', 'item': ['Sandwich'], 'south': 'Storage', 'west': 'Great Hall',
'text': 'You are in the Kitchen.'},
'Storage': {'name': 'Storage', 'item': ['Shield'], 'east': 'Mystery Room',
'text': 'You are in Storage.'},
'Mystery Room': {'name': 'the Mystery Room', 'item': ['none'], 'west': 'Storage', 'north': 'Kitchen',
'text': 'You are in the Mystery Room.'},
# villain
'Vendetta Room': {'name': 'the Vendetta Room', 'item': ['none'], 'west': 'Dungeon', 'north': 'Great Hall',
'text': 'You are in the Vendetta Room.'},
# Princess
'Dungeon': {'name': 'the Dungeon', 'item': ['none'], 'east': 'Vendetta Room',
'text': 'You are in the Dungeon.'}
}
directions = ['north', 'south', 'east', 'west']
add_items = ['get item']
current_room = rooms['Great Hall']
inventory = []
# game loop
while True:
if current_room['name'] == 'Mystery Room':
if current_room['Magic Key'] not in inventory:
print("Oh No! As soon as you entered, the doors locked behind you.")
print("You don't have the Magic Key to open the door and end up trapped forever.")
print("GAME OVER")
break
elif current_room['Magic Key'] not in inventory:
print("Oh No! As soon as you entered, the doors locked behind you.")
print("Luckily you found the Magic Key and could unlock the doors to continue your journey.")
if current_room['name'] == 'the Vendetta Room' and len(inventory) > 5:
print("You used all your items to defeat King Nox! Proceed to the next room to save the Princess.")
elif current_room['name'] == 'the Vendetta Room' and len(inventory) < 6:
print("You have found the Demon King but have no weapons.")
print("You have been defeated and the Princess has perished.")
print("GAME OVER")
break
elif current_room['name'] == 'the Dungeon':
print('Congratulations! You have reached the Dungeon and saved the Princess!')
print("You gave the Princess your healing potion and escorted her to the castle.")
print("Thank you for playing!")
break
command = input('Enter Move:')
# movement
if command in directions:
if command in current_room:
current_room = rooms[current_room[command]]
elif command != rooms[current_room[command]] and command != add_items:
# bad movement
print('Invalid entry. Try again.')
# quit game
elif command == 'quit':
print('Thanks for playing!')
break
# adding inventory
if command in add_items:
if command in add_items:
if command == 'get item':
if current_room['item'] != 'none':
inventory.append(current_room['item'])
print("You acquired : ", current_room['item'])
elif current_room['item'] == 'none':
print("No items to collect in this room")
elif command != add_items:
print('Invalid entry. Try again.')
Now that you included the entry of your commands, I gave the program a try. The program failed on one occasion when an improper directional command was entered. After testing it out, I made some minor corrections to allow the program to function in the spirit of the game.
# data setup
rooms = {'Great Hall': {'name': 'Great Hall', 'item': ['none'], 'south': 'Vendetta Room', 'east': 'Kitchen',
'north': 'Potion Lab', 'west': 'Armory',
'text': 'You are in the Great Hall.'},
'Armory': {'name': 'the Armory', 'item': ['Fire Sword'], 'east': 'Great Hall', 'north': 'Treasure Room',
'text': 'You are in the Armory.'},
'Treasure Room': {'name': 'the Treasure Room', 'item': ['Magic Ring'], 'south': 'Armory',
'text': 'You are in the Treasure Room.'},
'Potion Lab': {'name': 'the Potion Lab', 'item': ['Healing Potion'], 'east': 'Bedroom', 'south': 'Great Hall',
'text': 'You are in the Potion Lab.'},
'Bedroom': {'name': 'the Bedroom', 'item': ['Magic Key'], 'west': 'Potion Lab',
'text': 'You are in the Bedroom.'},
'Kitchen': {'name': 'the Kitchen', 'item': ['Sandwich'], 'south': 'Storage', 'west': 'Great Hall',
'text': 'You are in the Kitchen.'},
'Storage': {'name': 'Storage', 'item': ['Shield'], 'east': 'Mystery Room',
'text': 'You are in Storage.'},
'Mystery Room': {'name': 'The Mystery Room', 'item': ['none'], 'west': 'Storage', 'north': 'Kitchen',
'text': 'You are in the Mystery Room.'},
# villain
'Vendetta Room': {'name': 'the Vendetta Room', 'item': ['none'], 'west': 'Dungeon', 'north': 'Great Hall',
'text': 'You are in the Vendetta Room.'},
# Princess
'Dungeon': {'name': 'the Dungeon', 'item': ['none'], 'east': 'Vendetta Room',
'text': 'You are in the Dungeon.'}
}
directions = ['north', 'south', 'east', 'west']
add_items = ['get item']
current_room = rooms['Great Hall']
inventory = []
def status():
print('-' * 20)
print('You are in the {}'.format(current_room['name']))
print('Your current inventory: {}\n'.format(inventory))
if current_room['item']:
print('Item in room: {}'.format(', '.join(current_room['item'])))
print('')
# game loop
while True:
status()
if current_room['name'] == 'The Mystery Room':
if ['Magic Key'] not in inventory:
print("Oh No! As soon as you entered, the doors locked behind you.")
print("You don't have the Magic Key to open the door and end up trapped forever.")
print("GAME OVER")
break
elif ['Magic Key'] in inventory:
print("Oh No! As soon as you entered, the doors locked behind you.")
print("Luckily you found the Magic Key and could unlock the doors to continue your journey.")
if current_room['name'] == 'the Vendetta Room' and len(inventory) > 5:
print("You used all your items to defeat King Nox! Proceed to the next room to save the Princess.")
elif current_room['name'] == 'the Vendetta Room' and len(inventory) < 6:
print("You have found the Demon King but have no weapons.")
print("You have been defeated and the Princess has perished.")
print("GAME OVER")
break
elif current_room['name'] == 'the Dungeon':
print('Congratulations! You have reached the Dungeon and saved the Princess!')
print("You gave the Princess your healing potion and escorted her to the castle.")
print("Thank you for playing!")
break
command = input('Enter Move:')
# movement
if command == 'quit': # Moved this ahead of the directional and acquisition commands
print('Thanks for playing')
break
if command in directions:
if command in current_room:
current_room = rooms[current_room[command]]
elif command != add_items:
# bad movement
print('Invalid entry. Try again.')
# adding inventory
elif command in add_items:
if current_room['item'] != ['none']:
if current_room['item'] in inventory: # No need to acquire an item a second time
print("You already have this item")
else:
inventory.append(current_room['item'])
print("You acquired : ", current_room['item'])
elif current_room['item'] == ['none']:
print("No items to collect in this room")
else:
print('Invalid entry. Try again.')
I did a little rearranging of the code so that all of the data initialization appeared first, added in a call to the "status()" function in the "while" loop, moved the test for quitting before the directional and acquisition tests, and corrected the command check that was failing. Also, I don't know if the game is supposed to allow for acquiring multiple quantities of any item (e.g. having 4 shields), so I added in a test for that. If multiple quantities are allowed, you can remove that extra test.
Anyway, with that, I was able to save the princess. Give that a try.
I'm having trouble trying to get my code to run properly. When I run the code it works fine. Moving between rooms isn't an issue and when it comes to collecting the items there's no problem. The problem comes when I get to where the boss is and I enter the command in order to complete the game. However, it doesn't seem to work correctly. I've tried to rearrange it, but when I did, the problem then became that I couldn't collect the items but could then execute the command to fight the boss. Here is the code down below:
# data setup
rooms = {
'Entry': {'name': 'Entry', 'go south': 'Great Hall'},
'Great Hall': {'name': 'Great Hall', 'go north': 'Entry', 'go south': 'Bedroom',
'go east': 'Dining Room', 'go west': 'Cellar', 'item': 'helmet'},
'Bedroom': {'name': 'Bedroom', 'go north': 'Great Hall', 'item': 'shield'},
'Dining Room': {'name': 'Dining Room', 'go north': 'Kitchen', 'go south': 'Library',
'go west': 'Great Hall', 'item': 'boots'},
'Kitchen': {'name': 'Kitchen', 'go south': 'Dining Room', 'item': 'wrist guard'},
'Library': {'name': 'Library', 'go north': 'Dining Room', 'item': 'sword'},
'Cellar': {'name': 'Cellar', 'go south': 'Dungeon', 'go east': 'Great Hall', 'item': 'breast plate'},
'Dungeon': {'name': 'Dungeon', 'boss': 'sorcerer'}
}
directions = ['go north', 'go south', 'go east', 'go west']
current_room = rooms['Entry']
player_inv = []
# game instructions
def game_instruction():
print('Welcome to the Text Adventure Game')
print('Collect all 6 items before reaching the Dungeon in order to defeat the Sorcerer')
print('Movement: go north, go south, go east, go west')
print('Collecting Items: collect + "item name"')
print('Fighting Boss: fight + "boss name"')
# print game instruction
game_instruction()
# game loop
while True:
# display current location
print('You are in the {}'.format(current_room['name']))
# display current inventory
print('Inventory: {}'.format(player_inv))
# get user input
command = input('What do you want to do? ')
# movement
if command in directions:
if command in current_room:
current_room = rooms[current_room[command]]
# display current room item
if 'item' in current_room:
print('You see a', current_room['item'] + '.')
# display boss in Dungeon
if 'boss' in current_room:
print('You see the', current_room['boss'] + '.')
# bad movement
else:
print("You can't go in that direction.")
# quit game
elif command == 'quit':
print('Thanks for playing!')
break
# collect items
elif command == ('collect ' + current_room['item']):
if 'item' in current_room:
print(current_room['item'], 'collected.')
player_inv.append(current_room['item'])
del current_room['item']
else:
print('There are no items in this room.')
# game win/lose conditions
elif command == ('fight ' + current_room['boss']):
if 'boss' in current_room:
if len(player_inv) == 5:
print('CONGRATULATIONS!\nYou have successfully defeated the Sorcerer.')
break
else:
print('GAME OVER!\nYou failed to collect all the items need to defeat the Sorcerer.')
break
# bad command
else:
print('Invalid Command')
It gives me the error message:
Traceback (most recent call last):
File "C:\Users\-----\Documents\TextBasedGame\TextBasedGame.py", line 59, in <module>
elif command == ('collect ' + current_room['item']):
KeyError: 'item'
Any ideas on how I can fix this?
Hey guys im doing the Python texted based game and i can't figure out how to get an item from the room and add it to the inventory. i have the rooms defined and the inventory defined, but i cant write a proper call or command to get and add the items from specific rooms to the inventory. let me know if you can see something im missing or can add please!
rooms = {'Vestibule': {'name': 'the Vestibule', 'go East': 'Great Hall', 'item': 'none'},
'Great Hall': {'name': 'the Great Hall', 'go North': 'Common Room', 'go East': 'Study',
'go South': 'Kitchen', 'go West': 'Vestibule', 'item': 'Wand'},
'Common Room': {'name': 'the Common Room', 'go East': 'Laboratory', 'go South': 'Great Hall', 'item': 'Map'},
'Laboratory': {'name': 'the Laboratory', 'go West': 'Common Room', 'item': 'Potion'},
'Kitchen': {'name': 'the Kitchen', 'go North': 'Great Hall', 'go East': 'Dungeon', 'item': 'Chocolate Frog'},
'Dungeon': {'name': 'the Dungeon', 'go West': 'Kitchen', 'item': 'Slug Repellent'},
'Study': {'name': 'the Study', 'go North': 'Observation Tower',
'go West': 'Great Hall', 'item': 'Invisibility Cloak'},
'Observation Tower': {'name': 'the Observation Tower', 'go South': 'Study', 'item': 'Evil Wizard'}}
print('Wizard Text Adventure Game\n')
print('Collect 6 items to win the game, or be defeated by the Evil Wizard.')
print('Move commands: go South, go North, go East, go West')
print('Add to Inventory: get item')
current_room = rooms['Vestibule']
directions = ['go North', 'go South', 'go East', 'go West']
Item = ['Wand', 'Map', 'Potion', 'Chocolate Frog', 'Slug Repellent', 'Invisibility Cloak']
Inventory = {}
while True:
print('-' * 30)
print('You are in the {}'.format(current_room['name']))
print('Your current inventory: {}\n'.format(Inventory))
if current_room['item']:
print('Item in room: {}'.format(''.join(current_room['item'])))
print('')
command = input('Enter your move: \n')
if command in directions:
if command in current_room:
current_room = rooms[current_room[command]]
if current_room['name'] == 'Observation Tower':
print('Congratulations! You have reached the Observation Tower and defeated the Evil Wizard!')
break
else:
print('\nChoose another path.')
elif command == 'quit':
print('Thanks for playing!')
break
else:
print('Invalid input')
Check the code and see if this is what you are looking for(Does it solve your problem? PS: the code might break due to formating errors when copying from the idle to stack overflow.. be sure to fix the indentations if any errors come up): I also suggest creating classes for each room to hold individual data as it makes the program logic much more clearer...
rooms = {'Vestibule': {'name': 'the Vestibule', 'go East': 'Great Hall', 'item': 'none'},
'Great Hall': {'name': 'the Great Hall', 'go North': 'Common Room', 'go East': 'Study',
'go South': 'Kitchen', 'go West': 'Vestibule', 'item': 'Wand'},
'Common Room': {'name': 'the Common Room', 'go East': 'Laboratory', 'go South': 'Great Hall', 'item': 'Map'},
'Laboratory': {'name': 'the Laboratory', 'go West': 'Common Room', 'item': 'Potion'},
'Kitchen': {'name': 'the Kitchen', 'go North': 'Great Hall', 'go East': 'Dungeon', 'item': 'Chocolate Frog'},
'Dungeon': {'name': 'the Dungeon', 'go West': 'Kitchen', 'item': 'Slug Repellent'},
'Study': {'name': 'the Study', 'go North': 'Observation Tower',
'go West': 'Great Hall', 'item': 'Invisibility Cloak'},
'Observation Tower': {'name': 'the Observation Tower', 'go South': 'Study', 'item': 'Evil Wizard'}}
print('Wizard Text Adventure Game\n')
print('Collect 6 items to win the game, or be defeated by the Evil Wizard.')
print('Move commands: go South, go North, go East, go West')
print('Add to Inventory: get item')
current_room = rooms['Vestibule']
directions = ['go North', 'go South', 'go East', 'go West']
Item = ['Wand', 'Map', 'Potion', 'Chocolate Frog', 'Slug Repellent', 'Invisibility Cloak']
Inventory = {}
#Inventory = []
while True:
print('-' * 30)
print('You are in the {}'.format(current_room['name']))
print('Your current inventory: {}\n'.format(Inventory))
if current_room['item']:
print('Item in room: {}'.format(''.join(current_room['item'])))
print('')
command = input('Enter your move: \n')
if command in directions:
if command in current_room:
current_room = rooms[current_room[command]]
if current_room['name'] == 'Observation Tower':
print('Congratulations! You have reached the Observation Tower and defeated the Evil Wizard!')
break
else:
print('\nChoose another path.')
elif command == 'get item':
if current_room['item'] != 'none':
Inventory['Item' + str(len(Inventory.keys()) + 1)] = current_room['item']
#Inventory.append(current_room['item'])
print("You aquired : " ,current_room['item'] )
print(Inventory)
current_room['item'] = 'none'
else:
print("No items to collect in this room")
elif command == 'quit':
print('Thanks for playing!')
break
else:
print('Invalid input')