I am trying to combine my two dictionaries to read easier and simplify my code but every time I merge them I keep getting errors or the items not properly reading.
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',
}
{'South': 'Dining Room', 'item': 'Helmet', 'East': 'Study', 'item': 'Armor', 'West': 'Balcony’, 'item': 'Dark Knight', ‘North’: ‘Foyer'}
the structure suggested in your comment is not valid (as others have already pointed out), but there are still many ways to combine the two dictionaries.
Suggestion 1: room -> direction -> (room, item)
rooms_items = {rk: {
dk: (drv, items.get(drv)) for dk, drv in rv.items()
} for rk, rv in rooms.items()}
will have rooms_items as
{ 'Stable': {'West': ('Foyer', 'Shield')},
'Foyer': {'South': ('Great Hall', 'Sword')},
'Great Hall': {'South': ('Dining Room', 'Helmet'),
'East': ('Study', 'Armor'),
'West': ('Balcony', 'Dark Knight'),
'North': ('Foyer', 'Shield')},
'Study': {'North': ('Library', 'Spell Book'),
'West': ('Great Hall', 'Sword')},
'Dining Room': {'North': ('Great Hall', 'Sword'),
'East': ('Kitchen', 'Cooked Chicken')},
'Library': {'South': ('Study', 'Armor')},
'Kitchen': {'West': ('Dining Room', 'Helmet')},
'Balcony': {'East': ('Great Hall', 'Sword')}}
Suggestion 2: room -> {item, direction_room, direction_item}
{rk: dict(sorted([
*[(f'{dk}_room', drv) for dk, drv in rv.items()],
*[(f'{dk}_item', items.get(drv)) for dk, drv in rv.items()],
('item', items.get(rk))
], reverse=True)) for rk, rv in rooms.items()}
would return
{ 'Stable': {'item': None, 'West_room': 'Foyer', 'West_item': 'Shield'},
'Foyer': { 'item': 'Shield',
'South_room': 'Great Hall', 'South_item': 'Sword' },
'Great Hall': { 'item': 'Sword',
'West_room': 'Balcony', 'West_item': 'Dark Knight',
'South_room': 'Dining Room', 'South_item': 'Helmet',
'North_room': 'Foyer', 'North_item': 'Shield',
'East_room': 'Study', 'East_item': 'Armor' },
'Study': { 'item': 'Armor',
'West_room': 'Great Hall', 'West_item': 'Sword',
'North_room': 'Library', 'North_item': 'Spell Book' },
'Dining Room': { 'item': 'Helmet',
'North_room': 'Great Hall', 'North_item': 'Sword',
'East_room': 'Kitchen', 'East_item': 'Cooked Chicken' },
'Library': { 'item': 'Spell Book',
'South_room': 'Study', 'South_item': 'Armor' },
'Kitchen': { 'item': 'Cooked Chicken',
'West_room': 'Dining Room', 'West_item': 'Helmet' },
'Balcony': { 'item': 'Dark Knight',
'East_room': 'Great Hall', 'East_item': 'Sword' } }
Suggestion 3: room -> {item, direction -> {room, item}}
{rk: {'item': items.get(rk), **{dk: {
'room': drv, 'item': items.get(drv)
} for dk, drv in rv.items()}} for rk, rv in rooms.items()}
returns
{ 'Stable': {'item': None, 'West': {'room': 'Foyer', 'item': 'Shield'}},
'Foyer': { 'item': 'Shield',
'South': {'room': 'Great Hall', 'item': 'Sword'} },
'Great Hall': { 'item': 'Sword',
'South': {'room': 'Dining Room', 'item': 'Helmet'},
'East': {'room': 'Study', 'item': 'Armor'},
'West': {'room': 'Balcony', 'item': 'Dark Knight'},
'North': {'room': 'Foyer', 'item': 'Shield'} },
'Study': { 'item': 'Armor',
'North': {'room': 'Library', 'item': 'Spell Book'},
'West': {'room': 'Great Hall', 'item': 'Sword'} },
'Dining Room': { 'item': 'Helmet',
'North': {'room': 'Great Hall', 'item': 'Sword'},
'East': {'room': 'Kitchen', 'item': 'Cooked Chicken'} },
'Library': { 'item': 'Spell Book',
'South': {'room': 'Study', 'item': 'Armor'} },
'Kitchen': { 'item': 'Cooked Chicken',
'West': {'room': 'Dining Room', 'item': 'Helmet'} },
'Balcony': { 'item': 'Dark Knight',
'East': {'room': 'Great Hall', 'item': 'Sword'} } }
Once you decide on a [valid] structure for the combined data, you can figure out how to build it.
You said you were told you "needed to combine the two dictionaries for easier readability". Apparently, they'd find it easier to read if each room's whole data were in one place instead of spread over multiple dicts. So instead of
'Foyer': {'South': 'Great Hall'},
in one dict and
'Foyer': 'Shield',
in another, just combine that:
'Foyer': {'item': 'Shield', 'South': 'Great Hall'},
You could combine your dicts like that with this code:
for k, v in items.items():
rooms[k]['item'] = v
del items
But really that would be missing the point. You should write that combined dict instead of your two dicts. Then you have that better readability.
If your code would somehow benefit from your two dicts, you can easily compute them from that one dict containing the whole game configuration. You don't necessarily need to use that game configuration directly.
Related
I'm a total python newbie in a beginner programming class, and I'm stuck on one of our assignments. I'm supposed to be creating the bare bones start of a text game in which I move around rooms. I've managed to get the movement to work, but the "invalid command" and "exit game" commands aren't working.
rooms = {
'Foyer': {'name': 'Foyer', 'South': 'Dining Hall', 'North': 'Hallway', 'West': 'Courtyard', 'East': 'Grand Hall'},
'Dining Hall': {'name': 'Dining Hall', 'South': 'Servants Quarters', 'East': 'Kitchen', 'North': 'Foyer',
'West': 'Drawing Room'},
'Servants Quarters': {'name': 'Servants Quarters', 'North': 'Dining Hall'},
'Drawing Room': {'name': 'Drawing Room', 'East': 'Dining Hall'},
'Kitchen': {'name': 'Kitchen', 'West': 'Dining Hall'},
'Courtyard': {'name': 'Courtyard', 'East': 'Foyer'},
'Grand Hall': {'name': 'Grand Hall'},
'Hallway': {'name': 'Hallway', 'South': 'Foyer', 'East': 'Private Library'},
'Private Library': {'name': 'Private Library', 'West': 'Hallway', 'East': 'Master Bedroom'},
'Master Bedroom': {'name': 'Master Bedroom', 'West': 'Private Library'}
}
directions = ['North', 'South', 'East', 'West']
player_room = rooms['Foyer']
# turn below into definition that can be called on later
while True:
print()
print('You have entered the {}.'.format(player_room['name']))
command = input('\nEnter a direction: North, South, East, or West')
if command in directions:
if command in player_room:
player_room = rooms[player_room[command]]
else:
print("You face a wall. There is no doorway here.")
elif command == "Exit" or "exit":
print("Play again soon.")
break
else:
print("Type a cardinal direction to move. Directions are case-sensitive.")
This is my code so far. Whenever I test inputting an invalid command, like a number or a random word, it just gives me the 'exit' text and ends the program. I thought the problem was the order of the commands, so I swapped them around and messed with the statements a little, but then it would just repeatedly give me the error text even if I typed "exit". How do I stop one from always taking priority over the other?
The issue is with the condition in your elif statement: command == "Exit" or "exit". What this actually does is always evaluate to True because the string "exit" is always considered a true value.
You can fix this by changing the condition to command == "Exit" or command == "exit". This way, the condition will only be True if the input is either "Exit" or "exit".
You can also store the command inside a list and use the lower() method to convert the user's input to lowercase so that it is not case-sensitive.
change your elif as below
rooms = {
'Foyer': {'name': 'Foyer', 'South': 'Dining Hall', 'North': 'Hallway', 'West': 'Courtyard', 'East': 'Grand Hall'},
'Dining Hall': {'name': 'Dining Hall', 'South': 'Servants Quarters', 'East': 'Kitchen', 'North': 'Foyer',
'West': 'Drawing Room'},
'Servants Quarters': {'name': 'Servants Quarters', 'North': 'Dining Hall'},
'Drawing Room': {'name': 'Drawing Room', 'East': 'Dining Hall'},
'Kitchen': {'name': 'Kitchen', 'West': 'Dining Hall'},
'Courtyard': {'name': 'Courtyard', 'East': 'Foyer'},
'Grand Hall': {'name': 'Grand Hall'},
'Hallway': {'name': 'Hallway', 'South': 'Foyer', 'East': 'Private Library'},
'Private Library': {'name': 'Private Library', 'West': 'Hallway', 'East': 'Master Bedroom'},
'Master Bedroom': {'name': 'Master Bedroom', 'West': 'Private Library'}
}
directions = ['North', 'South', 'East', 'West']
player_room = rooms['Foyer']
# turn below into definition that can be called on later
while True:
print()
print('You have entered the {}.'.format(player_room['name']))
command = input('\nEnter a direction: North, South, East, or West').title()
if command in directions:
if command in player_room:
player_room = rooms[player_room[command]]
else:
print("You face a wall. There is no doorway here.")
elif command == "Exit" or command == "exit":
print("Play again soon.")
break
else:
print("Type a cardinal direction to move. Directions are case-sensitive.")
So below is my current code for a text based game that I have to finish for a school project:
# The dictionary links a room to other rooms as well as listing the item in the room
rooms = {
"Crew Quarters": {'East': 'Ship Storage', 'South': 'Operations Deck'},
"Ship Storage": {'West': 'Crew Quarters', 'South': 'Power and Oxygen Control', 'Item': 'Spare O2 Tank'},
"Operations Deck": {'North': 'Crew Quarters', 'East': 'Power and Oxygen Control',
'South': 'Crew Training Chamber', 'West': 'Captain Quarters', 'Item': 'Head Lamp'},
"Power and Oxygen Control": {'North': 'Ship Storage', 'West': 'Operations Deck',
'South': 'Infirmary'},
"Captains Quarters": {'East': 'Operations Deck', 'South': 'Armory', 'Item': 'Key to POC'},
"Armory": {'North': 'Captains Quarters', 'East': 'Crew Training Chamber', 'Item': 'Laser Rifle'},
"Crew Training Chamber": {'North': 'Operations Deck', 'East': 'Infirmary',
'West': 'Armory', 'Item': 'Space Suit'},
"Infirmary": {'North': 'Power and Oxygen Control', 'West': 'Crew Training Chamber', 'Item': 'Med-kit'}
}
# List of commands for movement or to exit the game
directions = ['North', 'South', 'East', 'West']
exit_game = ['e', 'exit']
inv = ['inv']
inv_list = []
# Current / starting room
c_room = 'Crew Quarters'
# print the game name, commands, and objectives.
print("Spaceship Text Adventure")
print("There's been a breach in the Power and Oxygen Control room on the ship!",
"Take care of the threat!")
print("Collect 6 items to defeat the anomaly or let the ship be taken over!")
print("Move commands: go South, go North, go East, go West")
print("Add to Inventory: get 'item name'")
print("To check your inventory: 'inv'")
print("To exit the game: 'e' or 'exit'")
# Game Loop
while True:
print('\nYou are in the', c_room)
command = input("\nWhere would you like to go? ")
if command in directions:
if command in rooms[c_room]:
c_room = rooms[c_room][command]
print(c_room)
# 1
else:
print('You cannot go that way')
elif command in inv:
print(inv_list)
elif command in exit_game:
print('You have exited the game. Thank you for playing!')
break
else:
print('Invalid command, try again!')
So what I want/need to do is whenever the player enters a room with an item in it, I need it to display the item that is in that room. If the player already has the item in the inventory, and they go back into the room, i need it to display "You've already taken the item from this room."
Where I placed my #1 is where I feel like the code should go, but I honestly have no idea. Any help would be appreciated as I'm struggling with calling upon lists and printing different statements. TYIA!
In helping out someone else with a similar room navigation game, I had added an inventory list that acquired a copy of the items selected in the various rooms. Following is the sample code.
# 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 probably did not need to copy in the whole bit. Mainly you would want to focus in on the block of code at the end that checks to see if the player has already picked up an item and if so, remind the player that they already possess the item.
Give that a try and see if it meets the spirit of your project.
Try:
# The dictionary links a room to other rooms and provides info if there
# is an item in the room along with its status ('noItm':True means item
# was already taken):
rooms = {
"Crew Quarters" : {'East' : 'Ship Storage',
'South': 'Operations Deck',
'noItm': True},
"Ship Storage" : {'West' : 'Crew Quarters',
'South': 'Power and Oxygen Control',
'Item' : 'Spare O2 Tank',
'noItm': False},
"Operations Deck" : {'North': 'Crew Quarters',
'East' : 'Power and Oxygen Control',
'South': 'Crew Training Chamber',
'West' : 'Captain Quarters',
'Item' : 'Head Lamp',
'noItm': False},
"Power and Oxygen Control": {'North': 'Ship Storage',
'West' : 'Operations Deck',
'South': 'Infirmary',
'noItm': True},
"Captains Quarters" : {'East' : 'Operations Deck',
'South': 'Armory',
'Item' : 'Key to POC',
'noItm': False},
"Armory" : {'North': 'Captains Quarters',
'East' : 'Crew Training Chamber',
'Item' : 'Laser Rifle',
'noItm': False},
"Crew Training Chamber" : {'North': 'Operations Deck',
'East' : 'Infirmary',
'West' : 'Armory',
'Item' : 'Space Suit',
'noItm': False},
"Infirmary" : {'North': 'Power and Oxygen Control',
'West' : 'Crew Training Chamber',
'Item' : 'Med-kit',
'noItm': False}
}
# List of commands for movement or to exit the game
directions = ['North', 'South', 'East', 'West']
exit_game = ['e', 'exit', 'q', 'quit']
inv = ['i', 'inv']
get_item = ['get']
inv_list = []
# Current / starting room
c_room = 'Crew Quarters'
# print the game name, commands, and objectives.
print("Spaceship Text Adventure")
print("There's been a breach in the Power and Oxygen Control room on the ship!",
"Take care of the threat!")
print("Collect 6 items to defeat the anomaly or let the ship be taken over!")
print("Move commands: go South, go North, go East, go West")
print("Add to Inventory: get 'item name'")
print("To check your inventory: 'inv'")
print("To exit the game: 'e' or 'exit'")
# Game Loop
while True:
print('\nYou are in the', c_room)
command = input("\nWhat would you like to do? ")
if len(command) >= 2 and command[0:2] == 'go':
direction = command[3:]
if direction in directions:
if direction in rooms[c_room]:
c_room = rooms[c_room][direction]
if rooms[c_room]['noItm'] is False:
print(c_room)
print(f"There is '{rooms[c_room]['Item']}' in this room.")
else:
if 'Item' in rooms[c_room]:
print("You've already taken the item from this room.")
else:
print('You cannot go that way')
elif len(command) > 10 and command[0:3] in get_item:
item_in_room = rooms[c_room]['Item'] if 'Item' in rooms[c_room] else None
item_to_get = command[5:-1]
if rooms[c_room]['noItm'] is False and item_to_get == item_in_room:
inv_list.append(item_in_room)
rooms[c_room]['noItm'] = True
print(f"You have got '{item_in_room}'")
else:
print(f"There is no '{item_to_get}' in this room")
elif command in inv:
print(inv_list)
elif command in exit_game:
print('You have exited the game. Thank you for playing!')
break
else:
print('Invalid command, try again!')
I have added a new key about the existence of an item to the dictionaries in rooms dictionary allowing to add the code for taking items from a room.
''' I've been working on this for about two weeks now, I can't seem to figure out the logic for the code to properly work and I'm having trouble understanding how to properly pull a key or value from a dictionary. Please note I'm a beginner and some of the concepts just go over my head. '''
''' Below is my code and one of the many errors I have received. Any guidance would be appreciated. '''
rooms = {
'Camp Crystal Lake Office': {'South': 'Packanack Lodge', 'East': 'Creepy Forest',
'North': 'Main Entrance', 'West': 'Mess Hall'},
'Main Entrance': {'South': 'Camp Crystal Lake Office', 'East': 'Abandoned Shack'},
'Abandoned Shack': {'Jason Voorhees'},
'Mess Hall': {'East': 'Camp Crystal Lake Office'},
'Creepy Forest': {'North': 'Higgins Haven', 'West': 'Camp Crystal Lake Office'},
'Higgins Haven': {'South': 'Creepy Forest'},
'Packanack Lodge': {'East': "Camping Area", 'North': 'Camp Crystal Lake Office'},
'Camping Area': {'West': 'Packanack Lodge'}
}
items_needed = {
'Main Entrance': 'rifle',
'Mess Hall': 'Flash Light',
'Creepy Forest': 'Battery',
'Higgins Haven': 'Car',
'Packanack Lodge': 'Running Sneakers',
'Camping Area': 'Bear Trap'
}
def game_play_rules():
print('Welcome to Camp Crystal Lake!!')
print('You are able to move North, South, East, West, but Jason Voorhees is lurking around.')
print("You will need to collect all 6 items to escape Jason's wrath")
print("If you want to leave the camp immediately, type Exit otherwise enjoy the game!")
# create function to change the location
def get_new_location(location, direction):
new_location = location
for i in rooms:
if i == location:
if direction in rooms[i]:
new_location = rooms[i][direction]
return new_location
game_play_rules()
location = 'Camp Crystal Lake Office'
inventory = []
while True:
print('\nYou are currently at the ', location) # shows player where they are starting
if location == 'Abandoned Shack':
print("You walked into Jason's shack, better luck next summer.", end= '')
for i in range(100):
for j in range(1000000):
pass
print('.', end=' ', flush = True)
print()
if len(inventory) == 6:
print("You collected all items and were able to escape - enjoy the rest of your summer")
else:
print("Welp, you failed to collect all the items, game over")
break
direction = input('Which way do you want to go: -->' )
print('You want to go ', (get_new_location(location, direction)))
print(f'\nThis location has ',(location, items_needed))
print('Your inventory has ', inventory)
print('\nYou already have that in your inventory', inventory)
if direction.lower() == [location][items_needed].lower():
if items_needed[location] not in inventory:
inventory.append(items[location])
continue
direction = direction.capitalize()
if direction == 'Exit':
exit(0)
if direction == 'North' or direction == 'South' or direction == 'East' or direction == 'West':
new_location = get_new_location((location, direction))
if new_location == location:
print('I would not wander to far if I were you.')
else:
location = new_location
else:
print('Wrong way!!')
'''
Error:
Welcome to Camp Crystal Lake!!
You are able to move North, South, East, West, but Jason Voorhees is lurking around.
You will need to collect all 6 items to escape Jason's wrath
If you want to leave the camp immediately, type Exit otherwise enjoy the game!
You are currently at the Camp Crystal Lake Office
Which way do you want to go: -->south
You want to go Camp Crystal Lake Office
Traceback (most recent call last):
File "C:\Users\jr0sa_000\PycharmProjects\pythonMilestone_v1\Project 2.py", line 66, in
if direction.lower() == [location][items_needed].lower():
TypeError: list indices must be integers or slices, not dict
This location has ('Camp Crystal Lake Office', {'Main Entrance': 'rifle', 'Mess Hall': 'Flash Light', 'Creepy Forest': 'Battery', 'Higgins Haven': 'Car', 'Packanack Lodge': 'Running Sneakers', 'Camping Area': 'Bear Trap'})
Your inventory has []
You already have that in your inventory [] # '''
new_location = get_new_location((location, direction))
should be
new_location = get_new_location(location, direction)
Also fixed issue with pointer being incorrect.
rooms = {
'Camp Crystal Lake Office': {'South': 'Packanack Lodge', 'East': 'Creepy Forest',
'North': 'Main Entrance', 'West': 'Mess Hall'},
'Main Entrance': {'South': 'Camp Crystal Lake Office', 'East': 'Abandoned Shack'},
'Abandoned Shack': {'Jason Voorhees'},
'Mess Hall': {'East': 'Camp Crystal Lake Office'},
'Creepy Forest': {'North': 'Higgins Haven', 'West': 'Camp Crystal Lake Office'},
'Higgins Haven': {'South': 'Creepy Forest'},
'Packanack Lodge': {'East': "Camping Area", 'North': 'Camp Crystal Lake Office'},
'Camping Area': {'West': 'Packanack Lodge'}
}
items_needed = {
'Main Entrance': 'rifle',
'Mess Hall': 'Flash Light',
'Creepy Forest': 'Battery',
'Higgins Haven': 'Car',
'Packanack Lodge': 'Running Sneakers',
'Camping Area': 'Bear Trap'
}
def game_play_rules():
print('Welcome to Camp Crystal Lake!!')
print('You are able to move North, South, East, West, but Jason Voorhees is lurking around.')
print("You will need to collect all 6 items to escape Jason's wrath")
print("If you want to leave the camp immediately, type Exit otherwise enjoy the game!")
# create function to change the location
def get_new_location(location, direction):
new_location = location
for i in rooms:
if i == location and direction in rooms[i]:
new_location = rooms[i][direction]
return new_location
game_play_rules()
location = 'Camp Crystal Lake Office'
inventory = []
while True:
print('\nYou are currently at the ', location) # shows player where they are starting
if location == 'Abandoned Shack':
print("You walked into Jason's shack, better luck next summer.", end= '')
for _ in range(100):
print('.', end=' ', flush = True)
print()
if len(inventory) == 6:
print("You collected all items and were able to escape - enjoy the rest of your summer")
else:
print("Welp, you failed to collect all the items, game over")
break
direction = input('Which way do you want to go: -->' ).lower()
print('You want to go ', (get_new_location(location, direction)))
print(f'\nThis location has ',(location, items_needed))
print('Your inventory has ', inventory)
print('\nYou already have that in your inventory', inventory)
if direction == rooms[location]:
if items_needed[location] not in inventory:
inventory.append(items_needed[location])
continue
direction = direction.capitalize()
if direction == 'Exit':
exit(0)
if direction in ['North', 'South', 'East', 'West']:
new_location = get_new_location(location, direction)
if new_location == location:
print('I would not wander to far if I were you.')
else:
location = new_location
else:
print('Wrong way!!')
I think you meant direction == rooms[location] instead of if direction.lower() == [location][items_needed].lower():
rooms = {
'Camp Crystal Lake Office': {'South': 'Packanack Lodge', 'East': 'Creepy Forest',
'North': 'Main Entrance', 'West': 'Mess Hall'},
'Main Entrance': {'South': 'Camp Crystal Lake Office', 'East': 'Abandoned Shack'},
'Abandoned Shack': {'Jason Voorhees'},
'Mess Hall': {'East': 'Camp Crystal Lake Office'},
'Creepy Forest': {'North': 'Higgins Haven', 'West': 'Camp Crystal Lake Office'},
'Higgins Haven': {'South': 'Creepy Forest'},
'Packanack Lodge': {'East': "Camping Area", 'North': 'Camp Crystal Lake Office'},
'Camping Area': {'West': 'Packanack Lodge'}
}
items_needed = {
'Main Entrance': 'rifle',
'Mess Hall': 'Flash Light',
'Creepy Forest': 'Battery',
'Higgins Haven': 'Car',
'Packanack Lodge': 'Running Sneakers',
'Camping Area': 'Bear Trap'
}
def game_play_rules():
print('Welcome to Camp Crystal Lake!!')
print('You are able to move North, South, East, West, but Jason Voorhees is lurking around.')
print("You will need to collect all 6 items to escape Jason's wrath")
print("If you want to leave the camp immediately, type Exit otherwise enjoy the game!")
# create function to change the location
def get_new_location(location, direction):
new_location = location
for i in rooms:
if i == location and direction in rooms[i]:
new_location = rooms[i][direction]
return new_location
game_play_rules()
location = 'Camp Crystal Lake Office'
inventory = []
while True:
print('\nYou are currently at the ', location) # shows player where they are starting
if location == 'Abandoned Shack':
print("You walked into Jason's shack, better luck next summer.", end= '')
for _ in range(100):
print('.', end=' ', flush = True)
print()
if len(inventory) == 6:
print("You collected all items and were able to escape - enjoy the rest of your summer")
else:
print("Welp, you failed to collect all the items, game over")
break
direction = input('Which way do you want to go: -->' ).lower()
print('You want to go ', (get_new_location(location, direction)))
print(f'\nThis location has ',(location, items_needed))
print('Your inventory has ', inventory)
print('\nYou already have that in your inventory', inventory)
if direction == rooms[location]:
if items_needed[location] not in inventory:
inventory.append(items_needed[location])
continue
direction = direction.capitalize()
if direction == 'Exit':
exit(0)
if direction in ['North', 'South', 'East', 'West']:
new_location = get_new_location((location, direction))
if new_location == location:
print('I would not wander to far if I were you.')
else:
location = new_location
else:
print('Wrong way!!')
I'm working on a text-based adventure game where the player moves between rooms and collects items. 'items' is a duplicate key. When I run my program, it's pulling the last value of 'item', instead of the one that pairs to the location. Here is my code:
#Stephanie Rivera
rooms = {
'Foyer': {'North': 'Kitchen', 'item': 'Pocket Watch', 'East': 'Library', 'item': 'Diary Page'},
'Library': {'West': 'Foyer'},
'Kitchen': {'West': 'Living Room', 'item': 'Ripped Photo', 'East': 'Bedroom',
'North': 'Turret', 'South': 'Foyer'},
'Living Room': {'East': 'Kitchen'},
'Bedroom': {'North': 'Attic', 'item': 'The Shadow Man', 'West': 'Kitchen'},
'Attic': {'South': 'Bedroom', 'item': 'Book of Matches'},
'Turret': {'East': 'Cellar', 'item': 'Ouija Board', 'South': 'Kitchen'},
'Cellar': {'West': 'Turret', 'item': 'Lantern'}
}
print('Welcome to The Shadow Man Text Adventure Game.')
print('Collect 6 items to win the game, or be defeated by The Shadow Man.')
print('Move commands: North, South, East, West.')
print("To add items to inventory, enter: Get 'item'.")
location = 'Foyer'
inventory = []
player_move = ''
item = ''
def show_instructions():
#print instructions
print('You are in the', location)
print('Inventory:', inventory)
print('___________')
def player_location():
#print player's location on the map
print('You are in the', location)
def player_inventory():
#print player's inventory
print('Inventory:', inventory)
print('___________')
def player_input():
print('Enter a move:')
player_move = input()
show_instructions()
print('You are lost in the woods. You see a house with a light on up ahead. You decide to enter the house.')
while len(inventory) < 6:
player_move = input('Enter a move: ' )
for k in rooms[location].keys():
if player_move == k:
value = [rooms[location].get('item')[]]
location = rooms[location][player_move]
player_location()
print('You see a', *value)
player_input()
First of all, there cannot be duplicate keys in a dictionary.
So, if you want to store multiple values, use a list and keep appending to that list.
rooms = {
...
...
'Cellar': {'West': 'Turret', 'item': ['Lantern', 'Book', 'blah', 'blah']}
}
I have to make a text based game for a final project. The goal is to pick up 6 items and to move from room to room. I'm still very new at this and would like some help! I can't seem to call the functions and I don't know how to add an inventory. Here is my current code:
def show_instructions():
#print a main menu and the commands
print("Thousand Year Vampire")
print("Collect 6 items to defeat the vampire or be destroyed by her.")
print("Move commands: go South, go North, go East, go West")
print("Add to Inventory: get 'item name'")
def showStatus(current_room, inventory, rooms):
#print the player's current location
#print the current inventory
#print an item if there is one
def main():
#define inventory and dictionary linking other rooms
rooms = {
'Entry Way': { 'North': 'Stalagmite Cavern'},
'Stalagmite Cavern': {'North': 'Grand Cavern', 'South': 'Entry Way', 'item': 'torch'},
'Grand Cavern': {'North': 'Hallway', 'East': 'Armory', 'West': 'Bedroom', 'South': 'Stalagmite Cavern', 'item': 'cross'},
'Armory': {'North': 'Treasure Trove', 'West': 'Grand Cavern', 'item': 'Stake'},
'Treasure Trove': {'South': 'Armory', 'item': 'silver'},
'Bedroom': {'North': 'Storage', 'East': 'Grand Cavern', 'item': 'elaborate comb'},
'Storage': {'South': 'Bedroom', 'item': 'mirror'},
'Hallway': {'North': 'Cliff Top', 'South': 'Grand Cavern'},
'Cliff Top': {'South': 'Hallway', 'item': 'Orla'}
}
# setting up inventory
inventory = []
# setting the starting room
starting_room = 'Great Hall'
# set current room to starting room
current_room = starting_room
while True:
print("\nYou are currently in {}".format(current_room))
move = input("Enter 'go North/South/East/West' to move or 'Exit': ").split()[-1].capitalize()
# user to exit
if move == 'Exit':
current_room = 'exit'
break
# a correct move
elif move in rooms[current_room]:
current_room = rooms[current_room][move]
# incorrect move
else:
print("You can't go that way. There is nothing to the {}".format(move))
#loop forever
#show game instructions
show_instructions()
This is not the final answer but I wanted to show you the changes you can make to the code to get the program to work.
This is just restructuring your code. It is not the solution. Once we understand what the problem is, I can help add to this to solve for it.
def show_instructions():
#print a main menu and the commands
print("Thousand Year Vampire")
print("Collect 6 items to defeat the vampire or be destroyed by her.")
print("Move commands: go South, go North, go East, go West")
print("Add to Inventory: get 'item name'")
def showStatus(current_room, inventory, rooms):
#print the player's current location
#print the current inventory
#print an item if there is one
#define inventory and dictionary linking other rooms
rooms = {
'Entry Way': { 'North': 'Stalagmite Cavern'},
'Stalagmite Cavern': {'North': 'Grand Cavern', 'South': 'Entry Way', 'item': 'torch'},
'Grand Cavern': {'North': 'Hallway', 'East': 'Armory', 'West': 'Bedroom', 'South': 'Stalagmite Cavern', 'item': 'cross'},
'Armory': {'North': 'Treasure Trove', 'West': 'Grand Cavern', 'item': 'Stake'},
'Treasure Trove': {'South': 'Armory', 'item': 'silver'},
'Bedroom': {'North': 'Storage', 'East': 'Grand Cavern', 'item': 'elaborate comb'},
'Storage': {'South': 'Bedroom', 'item': 'mirror'},
'Hallway': {'North': 'Cliff Top', 'South': 'Grand Cavern'},
'Cliff Top': {'South': 'Hallway', 'item': 'Orla'}
}
# setting up inventory
inventory = []
# setting the starting room
starting_room = 'Hallway'
# set current room to starting room
current_room = starting_room
#show game instructions
show_instructions()
while True:
print("\nYou are currently in {}".format(current_room))
move = input("Enter 'go North/South/East/West' to move or 'Exit': ").split()[-1].capitalize()
# user to exit
if move == 'Exit':
current_room = 'exit'
break
# a correct move
elif move in rooms[current_room]:
current_room = rooms[current_room][move]
# incorrect move
else:
print("You can't go that way. There is nothing to the {}".format(move))
#loop forever