I am having real problems with getting my program to work. Every time I fix an error another one follows. The code below is what i have so far (only been coding for about 2 months so be nice :) ). I am stuck with my code note allowing me to advance to the next room. It keeps repeating the same room. I put the entire code here as i dont exactly know where my error is. Any suggestions?
I will gladly send what the exact instructions are for the project if needed.
rooms = {
'Stable': {'West': 'Foyer'},
'Foyer': {'South': 'Great Hall'},
'Great Hall': {'South': 'Dining Room', 'East': 'Study', 'West': 'Balcony’, ‘North’: ‘Foyer'},
'Study': {'North': 'Library', 'West': 'Great Hall'},
'Dining Room': {'North': 'Great Hall', 'East': 'Kitchen'},
'Library': {'South': 'Study'},
'Kitchen': {'West': 'Dining Room'},
'Balcony': {'East': 'Great Hall'},
}
items = {
'Foyer': {'Shield'},
'Great Hall': {'Sword'},
'Study': {'Armor'},
'Library': {'Spell Book'},
'Dining Room': {'Helmet'},
'Kitchen': {'Cooked Chicken'},
'Balcony': {'Dark Knight'},
}
# Dark Knight is the villain
# Main Title/Menu and Move Commands
print('Dark Knight and the Royal Palace Text Adventure Game')
print('Collect 6 items to win the game, or be beaten by the Dark Knight.')
print('Move Commands: North, South, East, West, Exit')
print('Add to Inventory: get ''')
# Start the player in the Great Hall
state = 'Stable'
# store the items collected so far
inventory = []
# function
def get_new_statement(state, direction):
new_statement = state # declaring
for i in rooms: # loop
if i == state: # if
if direction in rooms[i]: # if
new_statement = rooms[i][direction] # assigning new_statement
return new_statement # return
while True: # loop
print('----------------------------------------------')
print('You are in the', state) # printing state
# display inventory
print('Current inventory: ', inventory)
direction = input('Enter which direction you want to go or enter exit: ') # asking user for input
direction = direction.capitalize() # making first character capital remaining lower
if direction == 'Exit': # if
print('----------------------------------------------')
print('Thank you for playing! Challenge the Dark Knight again soon!')
exit(0) # exit function
if direction == 'East' or direction == 'West' or direction == 'North' or direction == 'South': # if
new_statement = get_new_statement(state, direction) # calling function
if new_statement == state: # if
print('That’s a wall! Try another direction.') # print
else:
state = new_statement # changing state value to new_statement
else:
print('Invalid Command!') # print
# ask to collect item in current room
if state in items.keys() and items[state] != None and items[state] != 'Balcony':
print('This room has ', items[state])
option = input('Do you want to collect it (y/n): ')
if option[0] == 'y' or option == 'Y':
inventory.append(items[state])
items[state] = None
# if we have reached a room then we either win or loose the game
if state in items.keys() and items[state] == 'Dark Knight':
if len(inventory) == 6:
print('Congratulations you have saved the Royal Family!!')
else:
print("You have been defeated!")
print('try again')
break
Related
In my last assignment my code worked and i was able to move rooms. In the final project however my character isn't able to move rooms and the code looks exactly alike. Can someone share some light on why my character will not move rooms. My code is pasted below. I don't get any errors in Pycharm. But I keep getting invalid move message everytime i type a direction. After reviewing my code for hours I can't find the issue of why my character will not move rooms. ** Update issue was fixed but now i can not collect items in the room. My inventory_list.append code looks good but for some reason i can not collect the item in the room.
rooms = {
'Lobby': {'East': 'Kennel room','item': 'No items'},
'Kennel room': {'west': 'Lobby', 'south': 'Pet wash', 'east': 'Grooming room', 'north': 'Infirmary', 'item': 'Josh'},
'Infirmary': {'south': 'Kennel room', 'east': 'Play room', 'item': 'Chello'},
'Play room': {'west': 'Infirmary','item': 'Dog Catcher!'}, # The villain is in the Playroom
'Grooming room': {'west': 'Kennel room', 'north': 'Food storage', 'item': 'Taco'},
'Food storage': {'south': 'Grooming room', 'item': 'Therral'},
'Pet wash': {'north': 'Kennel room', 'east': 'Training room', 'Item': 'Dwan'},
'Training room': {'west': 'Pet Wash', 'item': 'Neisha'}
}
def player_status(): # indicate room and inventory
print("-" * 20)
print('You are in the {}'.format(current_room))
print('In this room you find {}'.format(rooms[current_room]['item']))
print('Inventory:', inventory_items)
print("-" * 20)
# Print main menu and commands
def player_instructions():
print("-" * 20)
print('Escape the pound!!')
print('You are Sam a lost pup trapped at the pound trying to escape to find your family.')
print('During your escape you and your six friends are separated when the alarm goes off.')
print('Before you escape to freedom you must find your six friends Neisha, Therral, Taco, Josh, Chello, and Dwan.')
print('Beware the dog catcher is out to get you and once he does its game over.')
print('Collect all six friends and escape before the dog catcher gets you.')
print('\nMove through the room using commands: "north, "south", "east", or "west"')
print('Once you enter the room with a friend to collect use the command: "(Get (friends name))"')
print('Type "exit" to escape the game at anytime')
print("-" * 20)
player_instructions()
inventory_items = [] # Inventory starts empty
current_room = 'Lobby' # Starting point
player_move = ''
while current_room != 'Exit':
player_status()
# Get user input
player_move = input('Enter your move:\n')
# Quit game
if player_move in ('Exit', 'exit'):
current_room = 'Exit'
print('Play again soon!')
break
# Lose game
if player_move in rooms[current_room]:
current_room = rooms[current_room][player_move]
if current_room == 'Play room':
print("SWIPE!! OH NO!! You were caught by the dog catcher"'\nGame Over')
break
else:
# Movement
if player_move in rooms[current_room]:
if player_move in rooms[current_room]['item']:
inventory_items.append(player_move)
print('You have found {}'.format['item'])
else:
current_room = rooms[current_room][player_move]
else:
print('Invalid command')
# Win game
if len(inventory_items) != 6:
pass
else:
print("Congratulations!! You helped Sam gather all of his friends and escape the dog catcher. \nYou Win")
def main():
inventory = [] # A list for the player to store their items
# Dictionary of the Rooms and which directions are to be taken for each room.
# This links one room to the other rooms.
rooms = {
'Lobby': {'East': 'Gym'},
'Gym': {'West': 'Lobby', 'South': 'Pool area', 'item': 'Dumbbell'},
'Pool area': {'North': 'Gym', 'East': 'Restaurant', 'West': 'Playroom', 'South': 'Your Room',
'item': 'Sunscreen'},
'Restaurant': {'West': 'Pool area', 'North': 'Bathrooms', 'item': 'Cloth Napkin'},
'Bathrooms': {'South': 'Restaurant', 'item': 'Toilet Roll'},
'Playroom': {'East': 'Pool area', 'South': 'Supply Closet', 'item': 'Deck of Cards'},
'Supply Closet': {'North': 'Playroom', 'item': 'Uniform'},
'Your Room': {'North': 'Pool area', 'East': 'Suite', 'item': 'Laptop'},
'Suite': {'West': 'Your Room'}}
current_room = 'Lobby' # Set the current room to begin the gameplay loop.
show_menu()
while current_room != 'Exit': # If the current room is not the exit the user can continue to the next room.
item = show_status(current_room, inventory, rooms) # Displays the current room and items in inventory.
moves = rooms[current_room]
# The player will be prompted for which move they want to make.
player_move = input("Enter 'go North, South, East or West' to move, or get Item, or 'Exit': ")
if player_move == 'Exit': # The user will exit the game.
current_room = 'exit'
break # Stops the game from continuing.
elif player_move.split()[-1] in rooms[current_room]: # Valid command from the user.
current_room = rooms[current_room][player_move.split()[-1]]
# The player will move from one room to the other.
elif player_move.split()[0].capitalize() == "Get": # Command to collect item to inventory.
if player_move == "get " + item:
get_item(item, inventory, rooms, current_room)
# The item in the current room will be put in the inventory.
print(item, "collected") # Tells the player that the item was collected.
else:
print("Invalid command")
else: # Set the invalid move command.
print("Invalid Move. There's no room to the {}".format(player_move))
print("^" * 20) # Set separating line.
if len(inventory) == 7: # Amount of items required to win the game.
print('Congratulations! You have collected all items and now can move to the Suite'
'to face off the politician!')
print('You have defeated the Corrupt Politician')
print('Thanks for playing')
break # The game will end after collecting all items.
main()
So I made this code for a class of a text based game where the player goes through different rooms and collects items. I want to help my player know which directions they can take whenever they enters the room. That way they are not guessing which way to go or a put a map.
I think your code is a bit messy, you should separate the "item" from the rooms dic so you could check if the "current_room" is in the "rooms" and find the room's choices you have to go ahead.
if current_room in rooms.keys():
print(list(rooms.get(current_room).keys())[0]) #print the direction you can go to
current_room = list(rooms.get(current_room).values())[0] #change the rooms
print(current_room)
According to the code above the player will go to the next room, but it always is the first room in the values.
For example - from "Gym" it will always go to the "Lobby", and from "Lobby" it will always go to the "Gym".
So it could stack in a loop.
You can play with the list index and randomize it so the rooms will change.
But before you change it you should remove the "item" from the dic, cause the code will consider "item" as a direction that can cause problems.
Good luck!
I am working on my final project for my intro to scripting class. we are using python. my code seems to be doing well except a a few lines of code, i cannot seem to define my item and state. The errors are traceback errors on lines 27 and 45.
Here is my code:
# declaration
rooms = {
'Town Square': {'North': 'Bookstore', 'South': 'Restaurant', 'East': 'Tailor', 'West': 'Jeweler'},
'Tailor': {'East': ' Town Square', 'item': 'Suit'},
'Restaurant': {'North': 'Town Square', 'East': 'Hair Dresser', 'item': 'salad'},
'Hair Dresser': {'West': 'Restaurant', 'item': 'Comb'},
'Book Store': {'South': 'Town Square', 'East': 'Shoemaker', 'item': 'Bible'},
'Shoemaker': {'West': 'Book Store', 'item': 'Shoes'},
'Jeweler': {'North': 'Chapel', 'West': 'Town Square', 'item': 'Ring'},
'Chapel': {'South': 'Chapel', 'item': 'Wife'}
}
state = 'Town Square'
# function
def get_new_state(state, direction):
new_state = state # declaraing
for i in rooms: # loop
if i == state: # if
if direction in rooms[i]: # if
new_state = rooms[i][direction] # assigning new_state
return new_state # return
# function
def get_item(state):
return rooms[state]['Item'] # returning Item value
# function
def show_instructions():
# print a main menu and the commands
print("Welcome to the Wedding Adventure!")
print("Collect all 6 items before you reach the chapel, so you will not die of embarrassment when you get left at "
"the altar")
print("Move commands: go South, go North, go East, go West")
print("Add to Inventory: get 'item name'")
show_instructions() # calling function
inventory = []
while (1): # gameplay loop
print('You are in ', state) # printing state
print('Inventory:', inventory) # printing inventory
item = get_item(state) # calling get_item function
print('You see a', item) # print
print('------------------------------')
if item == 'Wife': # if
print('SLAP ... GAME OVER!')
print('Thanks for playing! Hope you enjoyed it!')
exit(0)
direction = input('Enter your move: ') # asking user
if (direction == 'go East' or direction == 'go West' or direction == 'go North' or direction == 'go South'): # if
direction = direction[3:]
new_state = get_new_state(state, direction) # calling function
if new_state == state: # if
print('The room has wall in that direction enter other direction!') # print
else:
state = new_state # changing state value to new_state
elif direction == str('get '+item): # if
if item in inventory: # if item already present in inventory
print('Item already taken go to another room!!')
else:
print(f"{item} retrieved!\n")
inventory.append(item) # appending
else:
print('Invalid direction!!') # print
if len(inventory) == 6:
# print
print('Congratulations! You have collected all items and got married!')
print('Thanks for playing! Hope you enjoyed it!')
exit(0)
The code runs but has traceback errors on when initially run. I am not certain on how to trace the inventory for the items. Should I create a new dictionary for inventory?
I have been using everyone's suggestions to help me to write this script, and I am greatly appreciative. My game works great until i get to the final room with all of my items. I can't seem to get my winning conditions to work. I currently have them as an outer loop but I have tried them as the first inner loop and even a second inner loop. no matter where I put the winning conditions I cant seem to get them to work. I have also tried different things with the inventory to help make the winning conditions work I have been beating my head against the wall for days and I just cant seem to find the solution.
enter code here
def game():
answer = input('Would you like to help Galatrix save Halloween Town?(y/n)')
if answer.lower() == 'y':
print('Great! Welcome to Halloween Town!')
instructions()
else:
print('Too bad they really need your help.')
exit()
# define rules
def instructions():
print('Galatrix and her mentor have been noticing some strange goings on in their home of Halloween Town.')
print(
'Help Galatrix find all 6 items she needs to finish the potion to charge the Ancient wand and defeat the Warlock.')
print('Collect 6 items around Halloween Town. Then head to the theater to face off with the Warlock.')
print('Move commands: North, South, East, West')
print("Add objects to inventory: type 'get'.")
print("To end the game at any time, just type 'end'.")
print('*****************************')
# define rooms
# remind user what room they are in
rooms = {'Town Square': {'name': 'Town Square> Home of the Jack-o-lantern.', 'North': 'Dentist', 'South': 'General Store', 'East': 'Rec Center', 'West': 'Galatrix House', 'object': '0'},
'Galatrix House': {'name': 'Galatrix House', 'East': 'Town Square', 'object': 'Cloak'},
'Dentist': {'name': 'Dentist', 'South': 'Town Square', 'East': 'Hair Salon', 'object': 'Vampire tooth'},
'Hair Salon': {'name': 'Hair Salon', "West": 'Dentist', 'object': 'Werewolf hair'},
'General Store': {'name': "General Store", 'North': 'Town Square', 'East': 'Mentor House', 'object': 'Cauldron'},
'Mentor House': {'name': 'Mentor House', 'West': 'General Store', 'object': 'Ancient Wand'},
'Rec Center': {'name': 'Rec Center', 'North': 'Theater', 'West': 'Town Square', 'object': 'Ghost sweat'},
'Theater': {'name': 'Thearter', 'South': 'Rec Center', 'object': 'Warlock'}
}
current_room = rooms['Town Square']
end_point = rooms['Theater']
def move(player, direction):
current_room = player
if directions in rooms[current_room]:
current_room = rooms[current_room][direction]
else:
print('There is nothing in that direction.')
return current_room
# define supplies
inventory = []
Inventory = {}
def add_to():
if object not in Inventory:
Inventory[object] = 1
else:
pass
# define directions
directions = {'North', 'South', 'East', 'West'}
game()
while True:
if current_room['name'] == 'Warlock' and Inventory == 6:
print('CONGRATULATIONS!!! YOU SAVED HALLOWEEN TOWN!!!!!')
exit('The End')
elif Inventory != 6 and current_room['name'] == 'Theater':
print('Keep searching.')
print('You are in the {}.'.format(current_room['name']))
print('Inventory: {}'.format(inventory))
command = input('\nWhat do you do?')
if command in directions:
if command in current_room:
current_room = rooms[current_room[command]]
print('You see the {}.'.format(current_room['object']))
else:
print("You can't go that way.")
elif command == 'get':
if current_room['object'] != '0':
print('You grabbed the {}.'.format(current_room['object']))
inventory.append(current_room['object'])
current_room['object'] = '0'
add_to()
elif current_room['object'] == '0':
print("I don't see anything here.")
elif command in quit:
print('Thanks for playing!')
break
else:
print('You can not go that way.')
I'm getting a keyerror for 'Item' and I can't figure out what I'm doing wrong. it's for the line. item = get_item(state) I'm a noob to coding and I've spent the last 5 hours and can not fix the issue.
NOT IMPORTANT
Scenario
You work for a small company that creates text-based games. You recently pitched your design ideas for a text-based adventure game to your team. Your team was impressed by all of your designs, and would like you to develop the game! You will be able to use the map and the pseudocode or flowcharts from your designs to help you develop the code for the game. In your code, you have been asked to include clear naming conventions for functions, variables, and so on, along with in-line comments. Not only will these help you keep track as you develop, but they will help your team read and understand your code. This will make it easier to adapt for other games in the future.
Recall that the game requires players to type in a command line prompt to move through the different rooms and get items from each room. The goal of the game is for the player to get all of the items before encountering the room that contains the villain. Each step of the game will require a text output to let the player know where they are in the game, and an option of whether or not to obtain the item in each room.
rooms = {
'Master Bedroom': {'South': 'Kitchen', 'North': 'Toy Room', 'East': 'Garage', 'West': 'Closet'},
'Kitchen': {'North': 'Master Bedroom', 'East': 'Bathroom', 'West': 'Backyard', 'Item': 'Cell Phone'},
'Gun Room': {'South': 'Closet', 'East': 'Toy room', 'Item': 'Pistol'},
'Backyard': {'East': 'Kitchen', 'Item': 'ZOMBIE'},
'Garage': {'West': 'Master Bedroom', 'South': 'Bath Room', 'Item': 'Body Armor'},
'Toy Room': {'South': 'Master Bedroom', 'West': 'Gun Room', 'Item': 'Baseball Bat'},
'Closet': {'East': 'Master Bedroom', 'North': 'Gun Room', 'Item': 'Flashlight'},
'Bathroom': {'North': 'Garage', 'West': 'Kitchen', 'Item': 'Bandages'},
}
state = 'Master Bedroom'
def get_new_state(state, direction):
new_state = state
for i in rooms:
if i == state:
if direction in rooms[i]:
new_state=rooms[i][direction]
return new_state
def get_item(state):
return rooms[state]['Item']
def show_instructions():
print('ZOMBIE run Adventure Game')
print('Collect 6 items to win the game, or be eaten by a ZONBIE.')
print('Move commands: go South, go North, go East, go West')
print("Add to Inventory: get 'Item_name'")
print("type quit to end the game")
show_instructions() #calling Function
Inventory = []
while (1):
print('You are in ', state) #printing state
print('Inventory:', Inventory) #printing inventory
item = get_item(state) #calling get_item function
print('You see a ', item) #print
print('--------------------')
if item == 'ZOMBIE':
print('NOM NOM...GAME OVER!')
exit(0)
direction = input('Enter your move:')
if direction == 'go East' or direction == 'go West' or direction == 'go North' or direction == 'go South': #if
direction = direction[3:]
new_state = get_new_state(state, direction) #calling function
if new_state == state: #if
print('The room has wall in that direction enter other direction!')
else:
state = new_state
elif direction == str('get ' + item):
if item in inventory:
print('Item already taken go to another room!!')
else:
inventory.append(item)
else:
print('Invalid direction!')
if len(Inventory) == 6:
print('Congratulations! You have collected all items and defeated the ZOMBIE!')
exit(0)
stop = "go"
while stop != 'quit':
show_instructions()
user_input = input("what would you like to do?")
if user_input == 'quit':
break
The error seems to be the fact that there is no item in the master bedroom. Hence it throws a KeyError. You just need to add an 'Item' value to the rooms['Master Bedroom']
Edit: The context seems to be that the Master Bedroom has no item. So it would be better if you just added a state validation:
def get_item(state):
if state!='Master Bedroom':
return ' a'+rooms[state]['Item']
else:
return 'Nothing'
And just for the text to make sense:
print('You see', item) #print
If you want to avoid KeyError, a useful method of dicts is get.
>>>rooms.get('item')
>>>
you can give a default value as 2nd argument in case the key does not exist:
>>>rooms.get('item', 'this room does not exist')
>>>'this room does not exist'
or in case of nested dicts
>>>rooms = {'kitchen': {'items': ['sink', 'oven']}}
>>>rooms.get('kitchen').get('items')
>>>['sink', 'oven']