Having trouble setting up inventory - python

I'm working on a text-based game where the player had to find 6 items in different rooms before running into the boss or they die. I have the items set in the dict with the rooms but I don't know how to pull from it as the player moves around. What I have currently have has the player able to add things to the inventory but then it's stuck in a permanent loop. I am very new at this and I am having trouble connecting things together. Here is the whole thing with comments.
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'}
}
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 show_status():
print(current_room)
print(inventory)
#print the player's current location
#print the current inventory
#print an item if there is one
# setting up inventory
inventory = []
def game():
inventory = []
# simulate picking up items
while True:
item = input()
if item in inventory: # use in operator to check membership
print("you already have got this")
print(" ".join(inventory))
else:
print("You got ", item)
print("its been added to inventory")
inventory.append(item)
print(" ".join(inventory))
# setting the starting room
starting_room = 'Entry Way'
# set current room to starting room
current_room = starting_room
#show game instructions
show_instructions()
show_status()
while True:
print("\nYou are currently in the {}".format(current_room))
move = input("\n>> ").split()[-1].capitalize()
print('-----------------------------')
# 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]
print('inventory:', inventory)
# incorrect move
else:
print("You can't go that way. There is nothing to the {}".format(move))
#loop forever until meet boss or gets all items and wins

A nice start from you, Here is some modification as a small push to inspire your thoughts, and you can complete yourself or change according to the scenario you prefer- but discover the changes your self :) I have tested this code:
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'}
}
def show_instructions():
#print the 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 show_status():
print(current_room)
print(inventory)
#print the player's current location
#print the current inventory
#print an item if there is one
# setting up inventory
inventory = []
def game(item):
# simulate picking up items
if item in inventory: # use in operator to check membership
print("you already have got this")
print(" ".join(inventory))
else:
print("You got ", item)
print("its been added to inventory")
inventory.append(item)
print(" ".join(inventory))
# setting the starting room
starting_room = 'Entry Way'
# set current room to starting room
current_room = starting_room
#show game instructions
show_instructions()
show_status()
while True:
print("\nYou are currently in the {}".format(current_room))
if 'item' in rooms[current_room]:
game(rooms[current_room]['item'])
move = input("\n>> ").split()[-1].capitalize()
print('-----------------------------')
# 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]
#print('inventory:', inventory)
# incorrect move
else:
print("You can't go that way. There is nothing to the {}".format(move))
#loop forever until meeting boss or gets all items and wins
Good Luck

If each room only has one item, I think that the following line in the game() function should be removed
while True:
since that will cause an infinite loop with the first three printouts being "You got..." and "... added to inventory ..." and "[contents of inventory]" but the next printouts will be "you have already got this" and "[contents of inventory]" over and over again.

Related

Text Based Game, picking items up

I have been working on this project for a week now, I have looked all over the internet, tried different methods and nothing seems to work. My program is for a game moving between rooms and collecting items to defeat a boss. I have the movement down, I have ending the game down but I cannot pick items up and store them in my inventory. I would greatly appreciate if someone could point me in the right direction. Here is what I have so far.
rooms = {'Entrance Hall': {'name': 'Entrance Hall', 'west': 'Loft', 'item': 'no items'},
'Loft': {'name': 'Loft', 'north': 'Dining Room', 'east': 'Entrance Hall', 'item': 'sword'},
'Dining Room': {'name': 'Dining room', 'west': 'Study', 'east': 'Bedroom', 'north': 'Apothecary', 'south': 'Loft', 'item': 'garlic'},
'Study': {'name': 'Study', 'east': 'Dining Room', 'item': 'scroll'},
'Bedroom': {'name': 'Bedroom', 'west': 'Dining Room', 'north': 'Living Room', 'item': 'torch'},
'Living Room': {'name': 'Living Room', 'south': 'Bedroom', 'item': 'boots'},
'Apothecary': {'name': 'Apothecary', 'south': 'Dining Room', 'east': 'Basement', 'item': 'potion'},
'Basement': {'name': 'Basement', 'west': 'Apothecary', 'item': 'no item'}
}
#defining game instrucions
def game_instructions():
print('Welcome to the Dracula game')
print('You have traveled to Draculas mansion to put an end to his terror')
print('You will need to collect 6 items around his mansion to be able to defeat him and win')
print('If you go into the basement without the 6 items, you lose')
print('Move commands: north, south, east and west')
print('When moving to a new room if there is an item, type "get" to pick it up or leave behind')
def user_status():
print('\n ------------------------')
print('You are currently in the {}.'.format(current_room['name']))
print('In this room you see a {}' .format(current_room['item']))
print('Inventory: ', inventory)
print('\n ------------------------')
def get_item(current_room, user_input, rooms, inventory):
inventory.append(rooms[current_room]['item'])
del rooms[current_room]['item']
#setting directions to the variables
directions = ['north', 'south', 'east', 'west']
#starting room
current_room = rooms['Entrance Hall']
#calling on game instructions
game_instructions()
inventory = []
# Starting game loop
continue_loop = True
while continue_loop:
if current_room['name'] == 'Basement':
if len(inventory) == 6:
print('You have collected all the items and defeated dracula')
print('Thank you for playing')
else:
print('You have not collected all the items and dracula was too strong')
print('You lose, thanks for playing')
continue_loop = False
else:
user_status()
# Displaying current room
# print('You are currently in the {}.'.format(current_room['name']))
# getting user direction
user_input = input('\nWhich direction would you like to go?')
# deciding where to go based on input
if user_input in directions:
if user_input in current_room:
current_room = rooms[current_room[user_input]]#moving player to new room if input is valid
else:
# input was not in specific rooms directions
print('You cannot go that way.')
if len(user_input) == 4 and user_input == 'get' and s.join(user_input[1:3]) in rooms[current_room]['item']:
print('You pick up {}'.format(rooms[current_room]['item']))
get_item()
continue
# input was not valid, not in move commands
else:
print('Invalid input')
continue
You probably need to provide the right arguments to the get_item function:
get_item(current_room, "get", rooms, inventory)
Note also that the second argument of such function is useless since it is not used in the function body, you can remove it from the function definition and not provide it in the function call.
As a side note, it is not really clear what variable s in the lastif condition refers to.
I think you have two problems:
As mentioned already, you are not passing arguments to the get_item() function.
Also as mentioned above it seems that get_item() receives redundant arguments, and also the usage of current_room is confusing there (since in the main loop it represents an object and you use it as a string inside get_item().
def get_item(current_room, inventory) should be enough.
since current_room already points to the object representing the whole room.
In addition it seems like the expected user input for picking up items is get <item name>.
therefore I suggest a condition like:
if user_input[0:3] == 'get':
if user_input[4:] in rooms[current_room]['item'] and user_input[4:] != 'no item':
get_item(current_room, inventory)
else:
print('Item does not exist in the room')

Needing help trying to pick up items with TypeError in text based game

#Trevor Anderson
# this dictionary connects each room to their destination by direction
rooms = {
'Orderly Room': {'North': 'Admin Office', 'East': 'Recruiters Office', 'South': 'Supply Room', 'West': 'Drill Hall'},
'Admin Office': {'East': 'First Sergeant Office', 'South': 'Orderly Room', 'Item': 'Grip'},
'First Sergeant Office': {'West': 'Admin Office', 'Item': 'Magazine'},
'Recruiters Office': {'South': 'Outside of the Armory', 'West': 'Orderly Room', 'Item': 'Ammunition'},
'Outside of the Armory': {'North': 'Recruiters Office', 'Item': 'Terrorists'},
'Drill Hall': {'North': 'Kitchen', 'East': 'Orderly Room', 'Item': 'Bolt'},
'Kitchen': {'South': 'Drill Hall', 'West': 'Pantry', 'Item': 'Charging Handle'},
'Pantry': {'East': 'Kitchen', 'Item': 'Crayons'},
'Supply Room': {'North': 'Orderly Room', 'West': 'Cold Storage', 'Item': 'Receiver'},
'Cold Storage': {'East': 'Supply Room', 'West': 'Weapons Room', 'Item': 'Trigger'},
'Weapons Room': {'East': 'Cold Storage', 'Item': 'Stock'}
}
startGame = True
inventory = ()
# allows soldier to move room to room
def move(soldier, direction):
global rooms
startRoom = soldier
# verifies there is a room in that direction
if direction in rooms[startRoom]:
startRoom = rooms[startRoom][direction]
# tells soldier there is no room in that direction
else:
print('You can not go that direction')
return soldier
# returns where soldier is located
return startRoom
# announces the rules and commands of the game
def gameRules():
print('Move commands: go North, go East, go West, go South\nCollect all 8 items to win the game, or be captured by the terrorists!\nType exit if you want to exit the game ')
def pickupItem(startRoom):
if 'Item' in startRoom:
print('You have spot a', startRoom['Item'])
def show_status(startRoom):
print(startRoom)
print(inventory)
def game(item):
if 'item' in inventory:
print("you already have got this")
print(" ".join(inventory))
else:
print('You have accounted for', 'Item')
inventory.append(Item)
print(" ".join(inventory))
def main():
gameRules()
soldier = ('Orderly Room')
while startGame:
startRoom = soldier
pickupItem(rooms[startRoom])
# output
print('\nYou are in the', startRoom)
print('Inventory:', inventory)
print(pickupItem(startRoom))
# villian is located
if soldier == 'Outside of the Armory':
print('Oh no! You have been captured!\nThanks for playing the game. Good luck next time!')
break
# separation between commands and input
print('---------------------')
soldier_move = input('Enter your move:\n')
# invalid move syntax
if 'go' in soldier_move or 'exit' in soldier_move:
# split string
command = soldier_move.split(' ')
# move soldier
if command[0] == 'go':
soldier = move(soldier, command[1])
# exit the gamego
elif command[0] == 'Escape!':
if len(inventory) == 8:
print('Equip your M4 rifle! Lets get out of here!')
else:
print('You are missing some items!')
# end loop with invalid command
else:
print('Invalid Command!')
elif 'pickup' in soldier_move:
command = soldier_move.split(' ')
pickupItem(startRoom, command[1])
# end loop with invalid command with continue to play
else:
print('Invalid Command!')
continue
# run program
main()

text based python game with functions, function patameters and global variables

I am making a text-based python game for school. They want parameters in the move_room function but that makes it loop the same room. So I tried making current_room = move_rooms(move, current_room, inventory) but if I pick up an item, the program thinks that item is the room. Can someone give me some help with this please?
def give_instructions():
# print game instructions
print("Welcome to the game!\n"
"You were arriving home when attacked by a rival wizard,\n"
"you wake in a strange cell where the walls meet at impossible angles.\n"
"You have a sense of impending doom and a massive headache.\n"
"As your head clears you realize you are in your own home.\n"
"You must collect 7 items to defeat the wizard in your parlor.\n"
"To move type 'go North', 'go South', 'go East' or 'go West'\n"
"To pick up items type 'get' Item name\n"
"To exit type 'Exit'\n")
def show_status(room, stuff, roomsli):
# show player their current status(room, room exits and inventory)
print('You are in {}'.format(room))
print('Inventory:', stuff)
if "Item" in roomsli[room]:
print("{} is in {}".format(roomsli[room].get('Item'), room))
for direction, room in roomsli[room].items():
if direction != 'Item':
print("You can exit {} to {}".format(direction, room))
def move_rooms(move, current_room, inventory):
# controls for room movement and inventory
if move[0] in ['Exit', 'exit']:
# to exit game
current_room = 'Exit'
return current_room
elif move[0] == 'go':
# to change rooms or get error if not a good direction
if move[1] not in rooms[current_room]:
print("Invalid move\n")
elif move[1] in rooms[current_room]:
direction = move[1]
current_room = rooms[current_room][direction]
return current_room
elif move[0] == 'get':
# to get item, add it to inventory, remove it from rooms, or error if wrong item
if move[1] not in rooms[current_room].get("Item"):
print("That item is not in this room\n")
else:
item = rooms[current_room].get('Item')
inventory.append(item)
del (rooms[current_room]['Item'])
return inventory
else:
# if other move is entered
print("Invalid move\n")
if __name__ == '__main__':
# main program
# room dictionary
rooms = {
'Dungeon Cell': {'West': 'Basement'},
'Basement': {'East': 'Dungeon Cell', 'West': 'Cellar', 'North': 'Grand Hall', 'Item': 'Keys'},
'Cellar': {'East': 'Basement', 'Item': 'Amulet'},
'Grand Hall': {'South': 'Basement', 'East': 'Sitting Room', 'West': 'Dining Room', 'North': 'Entryway',
'Item': 'Staff'},
'Sitting Room': {'North': 'Library', 'West': 'Grand Hall', 'Item': 'Cloak'},
'Library': {'South': 'Sitting Room', 'Item': 'Book'},
'Dining Room': {'East': 'Grand Hall', 'North': 'Kitchen', 'Item': 'Dusty Cupcake'},
'Kitchen': {'South': 'Dining Room', 'East': 'Entryway', 'Item': 'Strange Potion'},
'Entryway': {'West': 'Kitchen', 'South': 'Grand Hall', 'East': 'Parlor'},
'Parlor': {'West': 'Entryway'},
'Exit': {'exits the game'}
}
# call for instructions
give_instructions()
# set current room and start inventory
current_room = "Dungeon Cell"
inventory = []
# main game loop
while current_room != 'Exit' or current_room != 'Parlor':
show_status(current_room, inventory, rooms)
move = input("What is your move?\n").split()
current_room = move_rooms(move, current_room, inventory)
# exit game conditional
if current_room == 'Exit':
print('You exited the game. Thanks for playing!')
break
elif current_room == 'Parlor':
# room conditional if wizard in room and inventory full
if len(inventory) == 7:
print("You use your items to defeat the wizard and regain control of your home.\n"
"Congratulations you have won!\n"
"Thanks for playing!")
break
# room conditional if wizard in room and inventory not full
else:
print("The wizard kills you as you are not prepared enough.\n"
"You have lost!\n"
"Thanks for playing!")
break

New to Python and not getting how to pull the 'Item' (key,value) from the rooms dict into my code

I need help defining a function that will allow me to access a dictionary key for each room that I enter for a text-based game that I am developing. I have tried doing this in different ways, but am confused about how to make this work.
I have tried creating a global variable that I could use dict.get(), which isn't working, I have tried to create a local variable that would pull the value of the key,value pairs and unfortunately I am just not familiar enough with dictionaries to make this work I guess.
I am not sure how to make this work and I am, quite frankly, getting discouraged.
I am trying to get the player to go from room to room, see an item, and then get it appended to their inventory. This is the part that keeps giving me issues. It says that the variable item is not defined.
# Function to show instructions and welcome the player to the game.
def show_instructions():
print("Welcome to the Saga of Light Text Adventure Game!")
print("Collect 6 items to win the game, or be beaten by The Dark Elf Nebo.")
print("Movement commands: North, South, East, West, or Exit to leave the Game.")
print("Add to Inventory: Get 'Item'")
# Define player location and state current inventory
def player_location():
print('-' * 20)
print('You are in the {}'.format(location))
print('Inventory: ', inventory)
print('-' * 20)
def get_new_location(location, player_move):
new_state = location
if location in rooms:
if player_move in rooms[location]:
new_state = rooms[location][player_move]
return new_state
def get_room_item(location):
item = rooms['Item']
return rooms[location][item]
def main_gameplay():
# Dictionary linking rooms and items obtain in them.
rooms = {
'Main Hall': {'South': 'Bedroom', 'North': 'library', 'East': 'Kitchen', 'West':
'Music Room'},
'Music room': {'East': 'Main Hall', 'Item': 'Music Box'},
'Bedroom': {'North': 'Main Hall', 'East': 'Safe room', 'Item': 'Cloak of
Strength'},
'Safe room': {'West': 'Bedroom', 'Item': 'Bow & Arrows'},
'Dining Room': {'South': 'Kitchen', 'Item': 'The Dark Elf Nebo'},
'Kitchen': {'West': 'Main Hall', 'North': 'Dining Room', 'Item': 'Energy
Drink'},
'Study': {'West': 'Library', 'Item': 'Ring of Light'},
'Library': {'East': 'Study', 'South': 'Main Hall', 'Item': 'Book'}
}
return rooms
rooms = main_gameplay()
# Call for the function to display instructions
show_instructions()
location = 'Main Hall'
player_move = ''
inventory = []
# gameplay loop for game
while len(inventory) < 6:
player_location()
# variables for the starting room and player moves and empty inventory list.
direction = player_move
player_move = input('Which location would you like to go?\n').lower() # Ask player
for location to go.
location = get_new_location(location, player_move)
if player_move == 'Exit': # If Exit is selected, game over.
rooms = 'Exit'
print('Thank you for playing!') # Thank you message for playing
# using if/else statements and dict for rooms and telling players where they are.
if 'Item' in rooms[get_room_item(location)]:
if player_move == ('Get' + 'Item').lower():
inventory = inventory.append('Item')
if location in rooms:
if location == 'Main Hall':
print()
elif location == 'Safe Room':
print(rooms.get('Item'))
print('You see a ' + 'Item')
print()
elif location == 'library':
print(rooms.get('Item'))
print('You see a ' + 'Item')
print()
elif location == 'Music room':
print(rooms.get('Item'))
print('You see a ' + 'Item')
print()
elif location == 'Dining room':
print(rooms.get('Item'))
print('You see a ' + 'Item')
print()
elif location == 'Kitchen':
print(rooms.get('Item'))
print('You see a ' + 'Item')
print()
elif location == 'Study':
print(rooms.get('Item'))
print('You see a ' + 'Item')
print()
if len(inventory) == 6: # Print congratulatory message!
print('Congratulations! You have collected all items and defeated the The
Dark Elf Nebo!')
exit(0)
You have a nested dictionary, so you first need to index by the room, then you can get the item
print(rooms[location]['Item'])
In fact you already do this in your get_room_item function, so you can just use that
def get_room_item(rooms, location):
return rooms[location]['Item']
If you just want to check that a room has an 'Item' at all then just
if 'Item' in rooms[location]:

KeyError with text based game

I am creating a text-based game where you make your way through a series of rooms and collect all the objects without running into the villain.
I keep getting a KeyError when trying to leave the starting room. But only if I entered an invalid direction. It's the only room that the error occurred in.
What am I doing wrong?
def show_instructions():
# Print a main menu and commands
print('Halloween Scavenger Hunt Text Adventure Game')
print('Collect 6 items to win or lose them to the Dentist!')
print('Move commands: go North, go South, go East, go West, Exit')
print('Add to inventory: get', 'item')
show_instructions()
# define an inventory which will start off empty and start position
inventory = []
current_room = 'Town Square'
def show_status():
# print the player current status
print('-----------------------------------')
print('You are in the', current_room)
show_status()
# A dictionary linking a room to other rooms
# and linking one item for each room except the Start room (Home) and the room containing the villain
rooms = {
'Town Square': {'East': 'Grocery Store'},
'Grocery Store': {'West': 'Town Square', 'North': 'Diner', 'South': 'Candy Shop', 'East': 'Bakery',
'item': 'Candy Corn'},
'Candy Shop': {'North': 'Grocery Store', 'East': 'Cafe', 'item': 'Gummy Bears'},
'Cafe': {'West': 'Candy Shop', 'item': 'Caramel Apple'},
'Diner': {'South': 'Grocery Store', 'East': 'Ice Cream Parlor', 'item': 'Bubble Gum'},
'Bakery': {'West': 'Grocery Store', 'North': 'Convenience Store', 'item': 'Popcorn Ball'},
'Convenience Store': {'South': 'Bakery', 'item': 'Candy Bar'},
'Ice Cream Parlor': {'West': 'Diner', 'item': 'Dentist'}
}
def get_item():
return rooms[current_room]['item']
while True:
if current_room == 'Exit':
print('Thanks for playing!')
break
if current_room == 'Ice Cream Parlor':
print('Game over! You lose all your sweets!')
break
if len(inventory) == 6:
print('Congratulations! You won!')
break
print('Inventory', inventory)
print('-----------------------------------')
player_move = input("Enter your move: >")
player_move = player_move.split()
if player_move[0] == 'go':
if player_move[1] in rooms[current_room]:
current_room = rooms[current_room][player_move[1]]
print('You are in the', current_room)
else:
print('You can not go that way!')
item = get_item()
if item in rooms[current_room]['item']:
if item not in inventory:
print('You see the', item)
elif item in inventory:
print()
if player_move[0] == 'get':
inventory.append(item)
print(item, 'retrieved!')
elif player_move[0] == 'Exit':
current_room = 'Exit'
else:
print('Invalid move!')
print('Thanks for playing the game!')
Here's a screenshot of the error.
If you read the last line in the error it says 'KeyError' for 'item'. What this means is that the key does not exist in the dictionary. The reason this is happening to you every time they enter a wrong move at the beginning is because the default room is Town Square which does not contain a key for item like the rest of the rooms so it will always fail when the function get_item() is called and the current room is still Town Square.
See below
'Town Square': {'East': 'Grocery Store'} # **NO ITEM KEY**
'Diner': {'South': 'Grocery Store', 'East': 'Ice Cream Parlor','item': 'Bubble Gum'

Categories