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')
Related
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
I know about .lower() and .upper() but no matter what they don't seem to work and they just cause my directions to not work at all. Any help would be appreciated as this is for a project due Sunday and I'm really stuck. All of my code is as follows:
def menu():
print('*' * 20)
print("InSIDious: Sid & the Commodore 64")
print('*' * 20)
print("Collect the 6 pieces of the Commodore 64 before facing Death Adder.")
print("Otherwise succumb to him and be stuck in this realm forever!")
print("How to play: To move, enter 'go North', 'go East', 'go South', 'go West' or 'Exit'/'exit' to quit playing.")
print("To pick up items, enter 'get Item Name' and it will be added to your inventory.")
print("Good luck!\n")
def Main():
rooms = {
'Court Yard': {'North': 'Great Hall', 'East': 'Bed Chambers', 'South': 'Gate House', 'West': 'Kitchen'},
'Great Hall': {'East': 'Throne Room', 'South': 'Court Yard', 'item': 'Sockets'},
'Bed Chambers': {'North': 'Bathroom', 'West': 'Court Yard', 'item': 'Semiconductors'},
'Gate House': {'North': 'Court Yard', 'East': 'Chapel', 'item': 'Capacitors'},
'Kitchen': {'East': 'Court Yard', 'item': 'Connectors'},
'Throne Room': {'West': 'Great Hall', 'item': 'Resistors'},
'Bathroom': {'South': 'Bed Chambers', 'item': 'Filters'},
'Chapel': ''
}
def user_status():
print('-' * 20)
print('You are currently in the {}'.format(current_room))
print('Inventory:', inventory)
print('-' * 20)
directions = ['North', 'South', 'East', 'West']
current_room = 'Court Yard'
inventory = []
menu()
while True:
if current_room == 'Chapel':
if len(inventory) == 6:
print('-----------------')
print('Congratulations!')
print('-----------------')
print('You can now return home after collecting the 6 pieces of the Commodore 64')
print('& defeating Death Adder!')
print('Thank you for playing!')
break
# Losing condition
else:
print('Oh no! You have been found by Death Adder before acquiring all the items to defeat him!')
print('You are now trapped in this realm forever!')
print('Thank you for playing!')
break
print()
user_status()
dict1 = rooms[current_room]
if 'item' in dict1:
item = dict1['item']
if item not in inventory:
print('You see the {} in this room'.format(rooms[current_room]['item']))
command = input('What would you like to do?\n').split()
if command[0] == 'go':
if command[1] in directions:
dict1 = rooms[current_room]
if command[1] in dict1:
current_room = dict1[command[1]]
else:
print('You cannot go that way.')
elif command[0] in ['exit', 'Exit']:
print('Thank you for playing, play again soon!')
break
elif command[0] == 'get':
if command[1] == item:
inventory.append(item)
print('You picked up the' + item)
else:
print('Invalid command.')
else:
print('Invalid input, try again.')
Main()
I have no idea if this is your problem or not, but when you call lower, make sure it's on the string read as input, and not on the array created by calling .split().
command = input('What would you like to do?\n').lower().split()
might be what you're looking for.
The directions in the directions list are in title case (eg "North"), so neither .upper (which would yield eg "NORTH") nor .lower (which would yield eg "north") make them equal.
command[1].title() will format the input in the same way as the directions in the list. Alternatively, you could store the directions in all-lowercase or all-uppercase and use command[1].lower() or command[1].upper().
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]:
This is for a intro to Python class. Typical exercise, move through the rooms, get an item (add to an inventory list), and win the game. I've gotten the move part down, it's the get/add to list part that is driving me up a wall.
My code to follow in its entirety but this ELIF section is what I need some guidance on.
below on execution gets the "invalid move" when trying to get the 'item' from the room. I get that my elif statement is probably not the best, and that my join is the problem, but variations on this theme aren't helping. Where did I go wrong?
Excerpt code with
elif len(move) == 4 and move[0] == 'Get' and s.join(move[1:3]) in rooms[current_room]['item']:
print('You pick up the {}'.format(rooms[current_room]['item']))
get_item(current_room, move, rooms, inventory)
Full code
def main_menu():
print('\nThe Castle Thief Game')
print('Collect all 6 treasures and bribe the guard if you encounter him to get out…better have all 6 though!')
print('Move Commands: go South, go North, go East, go West')
print('Add Item to Inventory: get "item name"\n')
def move_between_rooms(current_room, move, rooms):
current_room = rooms[current_room][move]
return current_room
def get_item(current_room, rooms, inventory):
inventory.append(rooms[current_room]['item'])
del rooms[current_room]['item']
def main():
rooms = {'Main Castle Hall': {'South': 'Princess Sitting Room', 'North': 'Royal Alchemy Lab', 'East': 'Kings Sitting Room', 'West': 'Guard Room'},
'Kings Sitting Room': {'West': 'Main Castle Hall', 'North': 'Kings Bedroom', 'item': 'Royal Sword'},
'Kings Bedroom': {'South': 'Kings Sitting Room', 'item': 'Kings Crown'},
'Princess Sitting Room': {'North': 'Main Castle Hall', 'East': 'Princess Bedroom', 'item': 'Magic Bow'},
'Princess Bedroom': {'West': 'Princess Sitting Room', 'item': 'Princess Tiara'},
'Royal Alchemy Lab': {'South': 'Main Castle Hall', 'East': 'Royal Library', 'item': 'Potion of Invisibility'},
'Royal Library': {'West': 'Royal Alchemy Lab', 'item': 'Grimoire'},
'Guard Room': ''
}
s = ' '
inventory = []
current_room = 'Main Castle Hall'
main_menu()
while True:
if current_room == 'Guard Room':
if len(inventory) == 6:
print('Bribe time! The guard draws his sword slowly...clearly not wanting to...')
print('You nonchalantly hand the guard a treasure...')
print('...the guard relaxes and smiles, then goes on his way. >phew!<')
print('Congratulations you have bribed the guard and live to see another day!')
print('That is all folks, you win! Play again some time!')
break
else:
print('The guard looks expectantly at you for a bribe..."')
print('Oh crud, you realize you do not have anything to give! With a disappointed look and a shrug...')
print('**STAB**...the guard runs you through with his sword! ')
print('The last thing you see and hear is the guard muttering about gotta pay if you wanna play.')
print('You have died, please try again...and this time get all the treasures first!!!')
break
print('You are in the ' + current_room)
print(inventory)
if current_room != 'Guard Room' and 'item' in rooms[current_room].keys():
print('You see the {}'.format(rooms[current_room]['item']))
print('------------------------------')
move: list[str] = input('Enter your move: ').title().split()
if len(move) >= 2 and move[1] in rooms[current_room].keys():
current_room = move_between_rooms(current_room, move[1], rooms)
continue
elif len(move) == 4 and move[0] == 'Get' and s.join(move[1:3]) in rooms[current_room]['item']:
print('You pick up the {}'.format(rooms[current_room]['item']))
get_item(current_room, move, rooms, inventory)
else:
print('invalid move, please try again')
continue
main()
I tried modifying my elif statement but to no avail so far. I can get it to error out, with an index out of range but I feel like I am missing the forest for the trees. I am expecting to "get" the item from the current_room I am in and adding it to my inventory[] empty list. the goal is to get the inventory full with all 6 'items' and when I encounter the guard in my code I can win the game. So far, been unsuccessful modifying the elif statement to correctly work.
Rather than guessing what might have been selected based on how many words are available, I would advise defining actions:
actions = ['go', 'get', 'check', 'quit'] # for example
and then just splitting the first element off the input with maxsplit and checking against this for initial validity:
while True:
move = input('Enter your move: ').lower().split(sep=None, maxsplit=1)
if len(move) > 0 and move[0] in actions:
break
print('Valid actions are: ' + ', '.join(actions))
act = actions.index(move[0])
then the index of the action word lets you choose the next code branch with confidence, and move[1] may be available (or not) as the subject of the action. Informative statements on what doors/items are available in appropriate cases would be easier to produce.
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.