Reputation: 11
I am trying to create a Text-Based Adventure Game in Python but I am brand new to coding and need some guidance, please! I need to move the rooms dictionary inside the main game function but when I do I get errors no matter what I try. Here is my code so far, any feedback or advice what be greatly appreciated! Thanks
# Define the rooms and their properties
rooms = {
'Entrance Hall': {
'Directions': {'North': 'Kitchen', 'South': 'Secret Passageway', 'East': 'Throne Room', 'West': 'Grand Hall'},
'Item': 'None' # Each room initially has no item
},
'Kitchen': {
'Directions': {'South': 'Entrance Hall', 'East': 'Dining Room'},
'Item': 'Diamond Crown'
},
'Throne Room': {
'Directions': {'West': 'Entrance Hall', 'North': 'Armory'},
'Item': 'Silver Scepter'
},
'Armory': {
'Directions': {'South': 'Throne Room'},
'Item': 'Emerald Necklace'
},
'Grand Hall': {
'Directions': {'East': 'Entrance Hall'},
'Item': 'Golden Chalice'
},
'Dining Room': {
'Directions': {'West': 'Kitchen'},
'Item': 'Enchanted Orb'
},
'Secret Passageway': {
'Directions': {'North': 'Entrance Hall', 'East': "Sorcerer's Lair"},
'Item': 'Mystic Amulet'
},
"Sorcerer's Lair": {
'Directions': {'West': 'Secret Passageway'}
}
}
# Function to display player's status
def show_status(current_room, inventory):
"""Display the status of the player."""
print(f"Current Room: {current_room}")
print(f"Inventory: {inventory}")
# Function to update the player's current room based on the direction entered
def get_new_state(direction_from_user, current_room):
"""Update the player's current room based on the direction entered."""
valid_directions = rooms[current_room]['Directions'].keys()
if direction_from_user in valid_directions:
return rooms[current_room]['Directions'].get(direction_from_user)
else:
print('Invalid direction! Please enter a valid direction.')
return current_room
# Function to display a message if the player picks up an item
def display_item_pickup(current_room, inventory):
"""Display a message if the player picks up an item."""
item = rooms[current_room]['Item']
if item != 'None':
print(f'You found a {item} in this room!')
inventory.append(item)
rooms[current_room]['Item'] = 'None' # Remove the item from the room once picked up
# Function to process item collection commands
def process_item_collection(command, current_room, inventory):
"""Process item collection commands."""
if command.startswith('get'):
item = ' '.join(command.split()[1:]) # Collect item name even if it has multiple words
if rooms[current_room]['Item'] == item:
inventory.append(item)
rooms[current_room]['Item'] = 'None' # Remove item from room once picked up
print('Item collected:', item)
else:
print('Item not found in this room.')
else:
print('Invalid command! Please enter a valid item collection command.')
# Main function to start the game
def main():
"""Main function to start the game."""
# Display game instructions and movement commands
print('Welcome to The Lost Kingdom Text Adventure Game')
print('Collect all 6 items to defeat the Wicked Sorcerer and win the game, or endure the Wicked Sorcerer’s Spell '
'of Death')
print('Move commands: go South, go North, go East, go West')
print('Add to Inventory: get \'item name\'')
print('------------------------------') # Print line of dashes
current_room = 'Entrance Hall'
inventory = []
# Start the main game loop
while not (len(inventory) == 6 and current_room == "Sorcerer's Lair") and not current_room == "Sorcerer's Lair":
# Display player's status and room information
show_status(current_room, inventory)
# Check if there's an item to pick up in the current room
display_item_pickup(current_room, inventory)
command = input('Enter your move: ')
print('------------------------------') # Print line of dashes
if command.startswith('go'):
# Process movement commands
direction = command.split()[1]
current_room = get_new_state(direction, current_room)
elif command.startswith('get'):
# Process item collection commands
process_item_collection(command, current_room, inventory)
else:
# Handle invalid command input
print('Invalid command! Please enter a valid move or item.')
# Check if the game ended due to winning or losing condition
if len(inventory) == 6 and current_room == "Sorcerer's Lair":
print('Congratulations! You have collected all items and defeated the Wicked Sorcerer!')
else:
print('The Wicked Sorcerer cast the Spell of Death on you!...GAME OVER!')
# Display farewell message
print('Thanks for playing. Hope you enjoyed the game!')
if __name__ == '__main__':
main()
I have tried to move it inside the main game function but I can not figure out what I am doing wrong. Any help in enhancing my code would also be greatly appreciated!
# Function to display player's status
def show_status(current_room, inventory):
"""Display the status of the player."""
print(f"Current Room: {current_room}")
print(f"Inventory: {inventory}")
# Function to update the player's current room based on the direction entered
def get_new_state(direction_from_user, current_room, rooms):
"""Update the player's current room based on the direction entered."""
valid_directions = rooms[current_room]['Directions'].keys()
if direction_from_user in valid_directions:
return rooms[current_room]['Directions'].get(direction_from_user)
else:
print('Invalid direction! Please enter a valid direction.')
return current_room
# Function to display a message if the player picks up an item
def display_item_pickup(current_room, inventory, rooms):
"""Display a message if the player picks up an item."""
item = rooms[current_room]['Item']
if item != 'None':
print(f'You found a {item} in this room!')
inventory.append(item)
rooms[current_room]['Item'] = 'None' # Remove the item from the room once picked up
# Function to process item collection commands
def process_item_collection(command, current_room, inventory, rooms):
"""Process item collection commands."""
if command.startswith('get'):
item = ' '.join(command.split()[1:]) # Collect item name even if it has multiple words
if rooms[current_room]['Item'] == item:
inventory.append(item)
rooms[current_room]['Item'] = 'None' # Remove item from room once picked up
print('Item collected:', item)
else:
print('Item not found in this room.')
else:
print('Invalid command! Please enter a valid item collection command.')
# Main function to start the game
def main():
"""Main function to start the game."""
# Define the rooms and their properties
rooms = {
'Entrance Hall': {
'Directions': {'North': 'Kitchen', 'South': 'Secret Passageway', 'East': 'Throne Room', 'West': 'Grand Hall'},
'Item': 'None' # Each room initially has no item
},
'Kitchen': {
'Directions': {'South': 'Entrance Hall', 'East': 'Dining Room'},
'Item': 'Diamond Crown'
},
'Throne Room': {
'Directions': {'West': 'Entrance Hall', 'North': 'Armory'},
'Item': 'Silver Scepter'
},
'Armory': {
'Directions': {'South': 'Throne Room'},
'Item': 'Emerald Necklace'
},
'Grand Hall': {
'Directions': {'East': 'Entrance Hall'},
'Item': 'Golden Chalice'
},
'Dining Room': {
'Directions': {'West': 'Kitchen'},
'Item': 'Enchanted Orb'
},
'Secret Passageway': {
'Directions': {'North': 'Entrance Hall', 'East': "Sorcerer's Lair"},
'Item': 'Mystic Amulet'
},
"Sorcerer's Lair": {
'Directions': {'West': 'Secret Passageway'}
}
}
# Display game instructions and movement commands
print('Welcome to The Lost Kingdom Text Adventure Game')
print('Collect all 6 items to defeat the Wicked Sorcerer and win the game, or endure the Wicked Sorcerer’s Spell '
'of Death')
print('Move commands: go South, go North, go East, go West')
print('Add to Inventory: get \'item name\'')
print('------------------------------') # Print line of dashes
current_room = 'Entrance Hall'
inventory = []
# Start the main game loop
while not (len(inventory) == 6 and current_room == "Sorcerer's Lair") and not current_room == "Sorcerer's Lair":
# Display player's status and room information
show_status(current_room, inventory)
# Check if there's an item to pick up in the current room
display_item_pickup(current_room, inventory, rooms)
command = input('Enter your move: ')
print('------------------------------') # Print line of dashes
if command.startswith('go'):
# Process movement commands
direction = command.split()[1]
current_room = get_new_state(direction, current_room, rooms)
elif command.startswith('get'):
# Process item collection commands
process_item_collection(command, current_room, inventory, rooms)
else:
# Handle invalid command input
print('Invalid command! Please enter a valid move or item.')
# Check if the game ended due to winning or losing condition
if len(inventory) == 6 and current_room == "Sorcerer's Lair":
print('Congratulations! You have collected all items and defeated the Wicked Sorcerer!')
else:
print('The Wicked Sorcerer cast the Spell of Death on you!...GAME OVER!')
# Display farewell message
print('Thanks for playing. Hope you enjoyed the game!')
if __name__ == '__main__':
main()
We're unable to classify your code currently, and if you are struggling we advise you to consult your professor on it. In the meantime - you can ALSO use this as a reference for your game system driver - 1) You need a function get_new_state that takes in (direction_from_user, current_room) as arguments and updates status of player. This function should access rooms dictionary and check that the direction stays within the rooms. (You may also have a few additional functions for displaying information to user if you wish). 2) Then you need a driving while loop. Your while loop must checks for the following conditions, given current room - whether current room has an item to collect, whether a kill zone is landed upon, whether player has pressed a direction or QUIT or something invalid. This loop must also call the get_new_state function and move to new room upon player's commands. We have given you some links here so your coding adventure goes smoothly - feel free to refer to them. References - 1) While loops 2) Function definitions Hope it helps!
class gameKeeper():
def __init__(self):
# Define the rooms and their properties
self.rooms = {
'Entrance Hall': {
'Directions': {'North': 'Kitchen', 'South': 'Secret Passageway', 'East': 'Throne Room', 'West': 'Grand Hall'},
'Item': 'None' # Each room initially has no item
},
'Kitchen': {
'Directions': {'South': 'Entrance Hall', 'East': 'Dining Room'},
'Item': 'Diamond Crown'
},
'Throne Room': {
'Directions': {'West': 'Entrance Hall', 'North': 'Armory'},
'Item': 'Silver Scepter'
},
'Armory': {
'Directions': {'South': 'Throne Room'},
'Item': 'Emerald Necklace'
},
'Grand Hall': {
'Directions': {'East': 'Entrance Hall'},
'Item': 'Golden Chalice'
},
'Dining Room': {
'Directions': {'West': 'Kitchen'},
'Item': 'Enchanted Orb'
},
'Secret Passageway': {
'Directions': {'North': 'Entrance Hall', 'East': "Sorcerer's Lair"},
'Item': 'Mystic Amulet'
},
"Sorcerer's Lair": {
'Directions': {'West': 'Secret Passageway'}
}
}
# Function to display player's status
def show_status(self, current_room, inventory):
"""Display the status of the player."""
print(f"Current Room: {current_room}")
# Check if there's an item in the room
if self.rooms[current_room]['Item'] != 'None':
print(f"Item in Room: {self.rooms[current_room]['Item']}")
else:
print("No item in this room.")
# Display player's inventory
print("Inventory:")
if inventory:
for item in inventory:
print(f"- {item}")
else:
print("Empty")
# Display available directions
print("Directions:")
directions = self.rooms[current_room]['Directions']
for direction, room in directions.items():
print(f"- {direction}: {room}")
# Function to update the player's current room based on the direction entered
def get_new_state(self, direction_from_user, current_room):
"""Update the player's current room based on the direction entered."""
valid_directions = self.rooms[current_room]['Directions'].keys()
if direction_from_user in valid_directions:
return self.rooms[current_room]['Directions'].get(direction_from_user)
else:
print('Invalid direction! Please enter a valid direction.')
return current_room
# Function to display a message if the player picks up an item
def display_item_pickup(self, current_room, inventory):
"""Display a message if the player picks up an item."""
item = self.rooms[current_room]['Item']
if item != 'None':
print(f'You found a {item} in this room!')
inventory.append(item)
self.rooms[current_room]['Item'] = 'None' # Remove the item from the room once picked up
# Function to process item collection commands
def process_item_collection(self, command, current_room, inventory):
"""Process item collection commands."""
if command.startswith('get'):
item = ' '.join(command.split()[1:]) # Collect item name even if it has multiple words
if self.rooms[current_room]['Item'] == item:
inventory.append(item)
self.rooms[current_room]['Item'] = 'None' # Remove item from room once picked up
print('Item collected:', item)
else:
print('Item not found in this room.')
else:
print('Invalid command! Please enter a valid item collection command.')
# Main function to start the game
def main():
gandalf = gameKeeper()
"""Main function to start the game."""
# Display game instructions and movement commands
print('Welcome to The Lost Kingdom Text Adventure Game')
print('Collect all 6 items to defeat the Wicked Sorcerer and win the game, or endure the Wicked Sorcerer’s Spell '
'of Death')
print('Move commands: go South, go North, go East, go West')
print('Add to Inventory: get \'item name\'')
print('------------------------------') # Print line of dashes
current_room = 'Entrance Hall'
inventory = []
# Start the main game loop
while not (len(inventory) == 6 and current_room == "Sorcerer's Lair") and not current_room == "Sorcerer's Lair":
# Display player's status and room information
gandalf.show_status(current_room, inventory)
# Check if there's an item to pick up in the current room
gandalf.display_item_pickup(current_room, inventory)
command = input('Enter your move: ')
print('------------------------------') # Print line of dashes
if command.startswith('go'):
# Process movement commands
direction = command.split()[1]
current_room = gandalf.get_new_state(direction, current_room)
elif command.startswith('get'):
# Process item collection commands
gandalf.process_item_collection(command, current_room, inventory)
else:
# Handle invalid command input
print('Invalid command! Please enter a valid move or item.')
# Check if the game ended due to winning or losing condition
if len(inventory) == 6 and current_room == "Sorcerer's Lair":
print('Congratulations! You have collected all items and defeated the Wicked Sorcerer!')
else:
print('The Wicked Sorcerer cast the Spell of Death on you!...GAME OVER!')
# Display farewell message
print('Thanks for playing. Hope you enjoyed the game!')
if __name__ == '__main__':
main()
Says there is no function to centrally display status.
You will need a show_status function to print out the game status for the player when he/she lands in a room. This is what you must print in the function - 1) Which room the player is currently in. 2) What item is present in the room. 3) What items are in the inventory. 4) The directions he can move in from this room. After you code this function - make sure you call it in a driver loop that facilitates the gameplay.
Upvotes: 0
Views: 123
Reputation: 1222
You could put rooms in a class or you could define it inside the main function, right under the main def.
def main():
rooms = {...}
class gameKeeper():
def __init__(self):
# Define the rooms and their properties
self.rooms = {
'Entrance Hall': {
'Directions': {'North': 'Kitchen', 'South': 'Secret Passageway', 'East': 'Throne Room', 'West': 'Grand Hall'},
'Item': 'None' # Each room initially has no item
},
'Kitchen': {
'Directions': {'South': 'Entrance Hall', 'East': 'Dining Room'},
'Item': 'Diamond Crown'
},
'Throne Room': {
'Directions': {'West': 'Entrance Hall', 'North': 'Armory'},
'Item': 'Silver Scepter'
},
'Armory': {
'Directions': {'South': 'Throne Room'},
'Item': 'Emerald Necklace'
},
'Grand Hall': {
'Directions': {'East': 'Entrance Hall'},
'Item': 'Golden Chalice'
},
'Dining Room': {
'Directions': {'West': 'Kitchen'},
'Item': 'Enchanted Orb'
},
'Secret Passageway': {
'Directions': {'North': 'Entrance Hall', 'East': "Sorcerer's Lair"},
'Item': 'Mystic Amulet'
},
"Sorcerer's Lair": {
'Directions': {'West': 'Secret Passageway'}
}
}
# Function to display player's status
def show_status(self, current_room, inventory):
"""Display the status of the player."""
print(f"Current Room: {current_room}")
print(f"Inventory: {inventory}")
# Function to update the player's current room based on the direction entered
def get_new_state(self, direction_from_user, current_room):
"""Update the player's current room based on the direction entered."""
valid_directions = self.rooms[current_room]['Directions'].keys()
if direction_from_user in valid_directions:
return self.rooms[current_room]['Directions'].get(direction_from_user)
else:
print('Invalid direction! Please enter a valid direction.')
return current_room
# Function to display a message if the player picks up an item
def display_item_pickup(self, current_room, inventory):
"""Display a message if the player picks up an item."""
item = self.rooms[current_room]['Item']
if item != 'None':
print(f'You found a {item} in this room!')
inventory.append(item)
self.rooms[current_room]['Item'] = 'None' # Remove the item from the room once picked up
# Function to process item collection commands
def process_item_collection(self, command, current_room, inventory):
"""Process item collection commands."""
if command.startswith('get'):
item = ' '.join(command.split()[1:]) # Collect item name even if it has multiple words
if self.rooms[current_room]['Item'] == item:
inventory.append(item)
self.rooms[current_room]['Item'] = 'None' # Remove item from room once picked up
print('Item collected:', item)
else:
print('Item not found in this room.')
else:
print('Invalid command! Please enter a valid item collection command.')
# Main function to start the game
def main():
gandalf = gameKeeper()
"""Main function to start the game."""
# Display game instructions and movement commands
print('Welcome to The Lost Kingdom Text Adventure Game')
print('Collect all 6 items to defeat the Wicked Sorcerer and win the game, or endure the Wicked Sorcerer’s Spell '
'of Death')
print('Move commands: go South, go North, go East, go West')
print('Add to Inventory: get \'item name\'')
print('------------------------------') # Print line of dashes
current_room = 'Entrance Hall'
inventory = []
# Start the main game loop
while not (len(inventory) == 6 and current_room == "Sorcerer's Lair") and not current_room == "Sorcerer's Lair":
# Display player's status and room information
gandalf.show_status(current_room, inventory)
# Check if there's an item to pick up in the current room
gandalf.display_item_pickup(current_room, inventory)
command = input('Enter your move: ')
print('------------------------------') # Print line of dashes
if command.startswith('go'):
# Process movement commands
direction = command.split()[1]
current_room = gandalf.get_new_state(direction, current_room)
elif command.startswith('get'):
# Process item collection commands
gandalf.process_item_collection(command, current_room, inventory)
else:
# Handle invalid command input
print('Invalid command! Please enter a valid move or item.')
# Check if the game ended due to winning or losing condition
if len(inventory) == 6 and current_room == "Sorcerer's Lair":
print('Congratulations! You have collected all items and defeated the Wicked Sorcerer!')
else:
print('The Wicked Sorcerer cast the Spell of Death on you!...GAME OVER!')
# Display farewell message
print('Thanks for playing. Hope you enjoyed the game!')
if __name__ == '__main__':
main()
Upvotes: 0
Reputation: 52
I don't know if I understood your problem. If you want to have a copy of your dictionary inside the main function, the easiest way is to create a new variable and assign it the dictionary previously created. So the main function would look something like this:
def main():
"""Main function to start the game."""
# Display game instructions and movement commands
print('Welcome to The Lost Kingdom Text Adventure Game')
print('Collect all 6 items to defeat the Wicked Sorcerer and win the game, or endure the Wicked Sorcerer’s Spell '
'of Death')
print('Move commands: go South, go North, go East, go West')
print('Add to Inventory: get \'item name\'')
print('------------------------------') # Print line of dashes
current_room = 'Entrance Hall'
rooms_dict = rooms # Here is the rooms dict copy
print(rooms_dict)
inventory = []
# Start the main game loop
while not (len(inventory) == 6 and current_room == "Sorcerer's Lair") and not current_room == "Sorcerer's Lair":
# Display player's status and room information
show_status(current_room, inventory)
# Check if there's an item to pick up in the current room
display_item_pickup(current_room, inventory)
command = input('Enter your move: ')
print('------------------------------') # Print line of dashes
if command.startswith('go'):
# Process movement commands
direction = command.split()[1]
current_room = get_new_state(direction, current_room)
elif command.startswith('get'):
# Process item collection commands
process_item_collection(command, current_room, inventory)
else:
# Handle invalid command input
print('Invalid command! Please enter a valid move or item.')
# Check if the game ended due to winning or losing condition
if len(inventory) == 6 and current_room == "Sorcerer's Lair":
print('Congratulations! You have collected all items and defeated the Wicked Sorcerer!')
else:
print('The Wicked Sorcerer cast the Spell of Death on you!...GAME OVER!')
# Display farewell message
print('Thanks for playing. Hope you enjoyed the game!')
But I don't see the point of creating a new variable and assign it the same value, since the room dictionary has a global scope, so you should be able to access it from the main function
Upvotes: 0