IT-140 Project 2 Python - python

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?

Related

Text-Based Game project assistance

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

How can I help my player on the game to know where to head to?

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!

how do i fix the KeyError issue im having

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']

Inventory condition so I can only add item once and win condition

I have two small problems, first I need help with the win condition, after collecting all the items I should go in the petting area and get the output 'You defeated the Killer Wolf so I hope you enjoyed playing.
other than this
I have the problem where I can add the same item to my inventory twice, this should not happen, I should get an output message saying 'You already have this item'.
can anyone please help me solve this?
this is the code I have so far.
def game_instructions():
# print a main menu and the commands
print("Killer Wolf Text Game")
print("---" * 20)
print("Collect 6 items to win the game, or be killed by the Wolf.")
print("---" * 20)
print('Move Commands: North , South , East , or West.')
print("---" * 20)
print("Add to Inventory: get 'item name'")
print("---" * 20)
game_instructions()
rooms = {
"Main fair ground": {'South': 'Food stand', 'North': 'Arcade', 'East': 'Corn field', 'West': 'Candy shop'},
"Food stand": {'North': 'Main fair ground', 'East': 'Security', 'item': 'meat'},
"Security": {'West': 'Food stand', 'item': 'armor'},
"Arcade": {'South': 'Main fair ground', 'East': 'Gift shop', 'item': 'sword'},
"Gift shop": {'West': 'Arcade', 'item': 'gloves'},
"Candy shop": {'item': 'candy', 'East': 'Main fair ground'},
"Corn field": {'West': 'Main fair ground', 'North': 'Petting area', 'item': 'repellent'},
"Petting area": {'South': 'Corn field', 'item': 'Killer Wolf'}
}
current_room = 'Main fair ground' # starts player in the Main fair ground
inventory = [] # Adds an inventory
def get_new_room(current_room, direction):
new_room = None
for i in rooms: # starts loop
if i == current_room: # if statement
if direction in rooms[i]: # if statement
new_room = rooms[i][direction] # Assigns new room.
else:
new_room = current_room #this assigns new room to current room if the mentioned direction is not valid
return new_room # returns new room
def get_item(current_room):
if 'item' in rooms[current_room]: # if statement
return rooms[current_room]['item'] # return statement
else:
return 'This room has no item!' # return statement
while (current_room): # gameplay loop
print('You are in the {}'.format(current_room)) # tells player what room they are in.
print('Inventory:', inventory) # shows player their inventory
item = get_item(current_room) # defines item as get item
print('You found the:', item) # tells the player what item they have found
if item == 'Killer Wolf' and len(inventory)<6: # if statement
print('NOM NOM, You did not collected all the necessary items to survive! The game has ended, I hope you '
'enjoyed!') # notifies player game has ended.
break # ends game
direction = input('Enter direction you would like to move. >>') # gets direction from player.
direction = direction.capitalize() # Capitalizes the players input to match what is in the dictionary.
if (direction == 'North' or direction == 'South' or direction == 'East' or direction == 'West'): # if statement
new_room = get_new_room(current_room, direction) # Calling function
if new_room == current_room: # if statement
print('That is a wall not an exit. Try Again!') # Print statement
else:
current_room = new_room # declares current room as new room
elif direction == str('get ' + item).capitalize(): # input statement to add item
if 'item' in inventory: # if statement
print('You have already collected this item. Move to another room!') # print statement
else:
inventory.append(item) # adds item to inventory
else:
print('Not a valid direction!') # Print statement
if len(inventory) == 6: # if statement
print("Congratulations!! You have collected all the necessary items to defeat the killer wolf")
If you could please fix and upload the code here for me I would really appreciate it.
Here's the code with all the bug fixes:
def game_instructions():
# print a main menu and the commands
print("Killer Wolf Text Game")
print("---" * 20)
print("Collect 6 items to win the game, or be killed by the Wolf.")
print("---" * 20)
print('Move Commands: North , South , East , or West.')
print("---" * 20)
print("Add to Inventory: get 'item name'")
print("---" * 20)
game_instructions()
rooms = {
"Main fair ground": {'South': 'Food stand', 'North': 'Arcade', 'East': 'Corn field', 'West': 'Candy shop'},
"Food stand": {'North': 'Main fair ground', 'East': 'Security', 'item': 'meat'},
"Security": {'West': 'Food stand', 'item': 'armor'},
"Arcade": {'South': 'Main fair ground', 'East': 'Gift shop', 'item': 'sword'},
"Gift shop": {'West': 'Arcade', 'item': 'gloves'},
"Candy shop": {'item': 'candy', 'East': 'Main fair ground'},
"Corn field": {'West': 'Main fair ground', 'North': 'Petting area', 'item': 'repellent'},
"Petting area": {'South': 'Corn field', 'item': 'Killer Wolf'}
}
current_room = 'Main fair ground' # starts player in the Main fair ground
inventory = [] # Adds an inventory
def get_new_room(current_room, direction):
new_room = None
for i in rooms: # starts loop
if i == current_room: # if statement
if direction in rooms[i]: # if statement
new_room = rooms[i][direction] # Assigns new room.
else:
new_room = current_room #this assigns new room to current room if the mentioned direction is not valid
return new_room # returns new room
def get_item(current_room):
if 'item' in rooms[current_room]: # if statement
return rooms[current_room]['item'] # return statement
else:
return 'This room has no item!' # return statement
while (current_room): # gameplay loop
print('You are in the {}'.format(current_room)) # tells player what room they are in.
print('Inventory:', inventory) # shows player their inventory
item = get_item(current_room) # defines item as get item
print('You found the:', item) # tells the player what item they have found
if item == 'Killer Wolf':
if len(inventory)<6:
print('NOM NOM, You did not collected all the necessary items to survive! The game has ended, I hope you '
'enjoyed!') # notifies player game has ended.
break
elif len(inventory)==6:
print("You defeated the Killer Wolf so I hope you enjoyed playing")
break
direction = input('Enter direction you would like to move. >>') # gets direction from player.
direction = direction.capitalize() # Capitalizes the players input to match what is in the dictionary.
if (direction == 'North' or direction == 'South' or direction == 'East' or direction == 'West'): # if statement
new_room = get_new_room(current_room, direction) # Calling function
if new_room == current_room: # if statement
print('That is a wall not an exit. Try Again!') # Print statement
else:
current_room = new_room # declares current room as new room
elif direction == str('get ' + item).capitalize(): # input statement to add item
if item in inventory: # if statement
print('You have already collected this item. Move to another room!') # print statement
else:
inventory.append(item) # adds item to inventory
else:
print('Not a valid direction!') # Print statement
if len(inventory) == 6: # if statement
print("Congratulations!! You have collected all the necessary items to defeat the killer wolf")
NOTE: Please copy the changes over properly, I made sure it all works

text based game inventory issues

def game_instructions():
#print a main menu and the commands
print("Lion Text Adventure Game")
print("Collect 6 items to win the game, or be Attacked by the Lion.")
print('Move Commands: North , South , East , or West.')
print("Add to Inventory: get 'item name'")
game_instructions()
#Shows rooms available to move and items in each room
rooms = {
'Auditorium': {'North': 'Info Exhibit', 'East': 'Library', 'South': 'Utility Room', 'West': 'Storage'},
'Info Exhibit': {'South': 'Auditorium', 'East': 'Observation Area', 'item': 'Tranquilizer Gun'},
'Observation Area': {'West': 'Info Exhibit', 'item': 'Lion'},
'Storage': {'East': 'Auditorium', 'item': 'Tranquilizer Darts'},
'Utility Room': {'North': 'Auditorium', 'East': 'Cafeteria', 'item': 'Night Vision Goggles'},
'Library': {'West': 'Auditorium', 'North': 'Office', 'item': 'Facts Book'},
'Office': {'South': 'Library', 'item': 'Keys'},
'Cafeteria': {'West': 'Utility Room', 'item': 'Steak'},
}
current_room = 'Auditorium' # starts player in the Great Hall
inventory = [] # Adds an inventory
def get_new_room(current_room, direction):
new_room = current_room # declares new room as current room.
for i in rooms: # starts loop
if i == current_room: # if statement
if direction in rooms[i]: # if statement
new_room = rooms[i][direction] # Assigns new room.
return new_room #returns new room
def get_item(current_room):
if 'item' in rooms[current_room]: #if statement
return rooms[current_room]['item'] #return statement
else:
return 'This room has no item!' #return statement
while (current_room): # gameplay loop
print('You are in', current_room) # tells player what room they are in.
print('Inventory:', inventory) # shows player their inventory
item = get_item(current_room) # defines item as get item
print('You found the:', item) # tells the player what item they have found
if item == 'Lion': #if statement
print('The Lion found you before you collected all the necessary items to survive! The game has ended!') # notifies player game has ended.
break # ends game
direction = input('Enter direction you would like to move. >>') # gets direction from player.
direction = direction.capitalize() # Capitalizes the players input to match what is in the dictionary.
if (direction == 'North' or direction == 'South' or direction == 'East' or direction == 'West'): # if statement
new_room = get_new_room(current_room, direction) # Calling function
if new_room == current_room: # if statement
print('That is a wall not an exit. Try Again!') # Print statement
else:
current_room = new_room # declares current room as new room
elif direction == str('get '+item): #input statement to add item
if 'item' in inventory: # if statement
print('You have already collected this item. Move to another room!') #print statement
else:
inventory.append(item) # adds item to inventory
else:
print('Not a valid direction!') # Print statement
if len(inventory)==6: # if statement
print('Congratulations!! You have collected all the necessary items and have safely put the lion back in his exhibit!') # print statement
I am trying to make a text based game. Everything is working besides the code is not adding my item to the inventory. When I input get and item name it is just saying invalid direction and not adding it. Iv looked it over and I can not see where I am going wrong. Any help would be greatly appreciated ! thank you!
Since you capitalized the input here,
direction = input('Enter direction you would like to move. >>') # gets direction from player.
direction = direction.capitalize() # Capitalizes the players input to match what is in the dictionary.
The elif statement would have never been true, if you add capitalize to that condition then it works.
elif direction == str('get '+item).capitalize():
Always make sure you work with the same kind of string.

Categories

Resources