Text based python game - python

My issue is when I have no clue why my program will not tell me I won or lost the game. Can add to inventory and move between rooms, but for some reason, my elif when I enter the last room to see if the player collected all the skills, does not say if they won or lost. Im checking to see by len over my skills and the checking if in current room
# This dictionary stores everyone room, direction of the room and skill of the room
rooms = {
'College Main Hall': {'North': 'Internship', 'East': 'CS-210', 'West': 'IT-140', 'South': 'IT-145'},
'IT-145': {'North': 'College Main Hall', 'East': 'Computer Lab', 'Skill': 'Java'},
'Computer Lab': {'West': 'IT-145', 'Skill': 'Leetcode'},
'IT-140': {'East': 'College Main Hall', 'Skill': 'Python'},
'Company': {'Wast': 'Internship', 'Skill': 'Job'},
'Internship': {'South': 'College Main Hall', 'East': 'Company', 'Skill': 'Internship'},
'CS-210': {'North': 'CS-260', 'West': 'College Main Hall', 'Skill': 'C++'},
'CS-260': {'South': 'CS-210', 'Skill': 'Data'}
}
# This variable stores the current room the player in
current_room = 'College Main Hall'
# This variable stores user skills
skills = []
# This function is used for updating the room with the new room the user choices to go into
def find_new_room(current_room, direction):
# Assigns the current_room to the new room
new_room = current_room
# Loop and if valid direction
# assign new room
for i in rooms:
if i == current_room:
if direction in rooms[current_room]:
new_room = rooms[current_room][direction]
return new_room
# This a intro function that tell the user about the story's game
def intro():
print('*' * 50)
print('This is the story of a young college student\'s')
print('adventure into becoming a software engineer')
print('*' * 50)
# Calling the function intro
intro()
# Gets player name and uses the capitalize function to make the first letter of name capitalize
player_name = input('Please Enter your name? ').capitalize()
# Tell the player the instruction of the game
def instruction():
print('Welcome', player_name)
print('*' * 50)
print('For this game, you must travel to each class')
print('to gain all 6 skills before going')
print('to the job interview.')
print(' Do you have what it takes? ')
print(' *Press enter to continue* ')
# This makes the user have to enter a key before moving on to the game
title_screen = {'play': 'play'}
title_screen['play'] = input()
print('*' * 50)
# Calling the function instruction
instruction()
# This function stores the menu for the player
def player_menu():
# Tells user what room they are in
print('*' * 50)
print('You are currently in the', current_room + '.')
print('Current skills', skills)
print('*' * 50)
# Print each option to the user
print('Enter a direction to move to a different room or select Exit to leave the game.')
print('North, South, East, West')
print('Exit')
# Loop over the game until the user selects Exit
while True:
if 'Skill' in rooms[current_room]:
print('*' * 50)
print('You see ' + rooms[current_room]['Skill'])
# Game menu function
player_menu()
# Ask user what direction, removes white space with the strip function and title the user input
direction = input().strip().lower()
directions = ['north', 'east', 'south', 'west']
# If user type Exit the game ends
if direction == 'Exit':
print('Thanks for play' + player_name)
break
else:
# Checks to see if user direction equals North, South, East or West
if direction in directions:
# Calls the function above to see if the direction the user inputed is in the Dictionary
new_room = find_new_room(current_room, direction.capitalize())
# If the user can not move to this room print unable to move this direction
if new_room == current_room:
print('*' * 50)
print('For some reason, somebody put a wall here? Try another direction.')
print()
# Updates the current room to the new room
else:
current_room = new_room
elif print('*' * 50):
print('You did not enter a direction try again.')
elif len(skills) != 6 and current_room == 'Company':
print('game over')
break
elif len(skills) == 6 and current_room == 'Company':
print('game over')
break
#If the user types the direction wrong print to the user You did not enter a direction try again.
else:
direction.title() == str('Get ' + rooms[current_room]['Skill'])
if rooms[current_room]['Skill'] in skills:
print('You have already retrieved this item!! Pick another direction!')
else:
skills.append(rooms[current_room]['Skill'])
I would like the player to win if they collect all the skills before going to the company.

Related

How to add a function get_new_state that takes in (direction_from_user, current_room)?

Here is the code I have so far. I am working on a project for school making a texted based game. I am able to input my choices in the game, but I run into an issue when entering the room with the Villain and the game not registering it. I can move from room to room and collect items but it doesn't end the game when I enter the room with the Villain without collecting all the items. please help :)
# A dictionary for a simplified moving between rooms game
# The dictionary links a room to other rooms.
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

Stuck on creating the moving parts for my text based game in Python

I am creating a text-based game for my python class. I am trying to get my code to do a few things.
When a user inputs they say no to play, it tells them 'there's always next time' then I want the loop and all gameplay to end. When I execute the code with a break, it gives me my print but also continues the gameplay. The same for if a user inputs exit.
I am trying to access the room and item associated with a users cardinal direction. Ex. The user goes North, the code tells them the current room they are now in as well as the item in that room if there is one.
I have gone through zybooks and gone over dictionaries and functions a few times but I'm not sure where I am messing up at. Thank you guys in advance.
def show_game_instructions():
#show game title and instructions
print('Welcome to Alien v. Tuna Sandwich')
print()
print('Collect 6 items to make a Tuna sandwich or the Alien will stay in your house forever')
print('Move commands: go North, go South, go East, go West')
print("Add to inventory: get 'item name'")
print()
answer = input('Would you like to play? (yes, no, exit)' ) #user input to begin the game or not
while answer != 'exit':
if answer.lower().strip() == 'yes':
print("Great! Let's begin...")
break
game_play()
elif answer.lower().strip() == 'no':
print("That's alright, there's always next time")
break
elif answer.lower().strip() == 'exit': #exit ceases the game immediately
print('Game over, thank you for playing!')
break
else:
print(f'{answer} is an invalid input')
show_game_instructions()
break
show_game_instructions()
rooms = {
'Hallway': {'North': 'Living Room', 'South': 'Bedroom_1', 'West': 'Dining Room', 'East': 'Kitchen', 'Item': 'Empty'},
'Dining Room': {'East': 'Hallway', 'Item': 'Bread'}}
user_input = input('Would you like to go North, South, East, or West? ')
def game_play():
while user_input != exit:
if user_input in rooms.values():
north = rooms[user_input]['Item']
print(north)
else:
print('Thank you for playing')
break

Make User Input Match Specific Criteria (Python)

I am currently working on a text based game for a school project. My only issue is that I cannot get my program to print 'Invalid input' when the user input does not include 'Take' and [item name]. So the item is added to inventory as long as the user input is 'Take'.
`
import sys
def start_menu():
# Print start menu and commands
print('<>' * 50) # Print lines to separate text
title = (r"""
╔═╗┬─┐┌─┐┌─┐┌┬┐ ╔═╗┬ ┬┬─┐┌─┐┌┬┐┬┌┬┐ ┌─┐┌─┐ ╔╦╗┌─┐┌─┐┬─┐┌─┐┌─┐┌┐┌
║ ╦├┬┘├┤ ├─┤ │ ╠═╝└┬┘├┬┘├─┤││││ ││ │ │├┤ ║║║├┤ ├┤ ├┬┘├┤ ├┤ │││
╚═╝┴└─└─┘┴ ┴ ┴ ╩ ┴ ┴└─┴ ┴┴ ┴┴─┴┘ └─┘└ ╩ ╩└─┘└─┘┴└─└─┘└─┘┘└┘
""")
print(title)
print('<>' * 50 ) # Print lines to separate text
print('You are a Spy visiting the Great Pyramid of Meereen. You must make your way from the top of the\n'
'Pyramid to the Dragon Pit. Collect all of the items along the way to help defeat the two Dragons.\n'
'If you are successful you will put an end to Queen Daenerys reign and save the Seven Kingdoms.\n'
'\nHappy Adventuring!')
print('<>' * 50)
print('Input move: North, South, East or West')
print('Input "Take [item name]" to add item to inventory')
print('Input "Exit" to quit game')
print('<>' * 50)
start_menu()
# Dictionary of rooms and items
rooms = {
'Terrace': {'East': 'Daenerys Chambers'},
'Daenerys Chambers': {'West': 'Terrace', 'East': 'Barristan\'s Chambers', 'South': 'Royal Chambers',
'item': 'Dragon Necklace'},
'Barristan\'s Chambers': {'West': 'Daenerys Chambers', 'item': 'Barristan\'s Sword'},
'Royal Chambers': {'North': 'Daenerys Chambers', 'South': 'Torture Cells',
'West': 'Audience Chamber', 'East': 'Stables', 'item': 'Milk of the Poppy'},
'Audience Chamber': {'East': 'Royal Chambers', 'item': 'Torch'},
'Stables': {'West': 'Royal Chambers', 'item': 'Health Potion'},
'Torture Cells': {'North': 'Royal Chambers', 'East': 'Dragon Pit', 'item': 'Magic Potion'},
'Dragon Pit': {'West': 'Torture Cells', 'Item': 'Dragons'}
}
def gameplay_loop():
move_direction = ['North', 'South', 'East', 'West']
inventory = []
current_room = 'Terrace'
# Gameplay loop
while True:
# Display Inventory
print('Inventory', inventory, '\n')
# Shows current location and item
if current_room == 'Terrace':
print('You are on the {}.\n'.format(current_room))
if current_room == 'Daenerys Chambers' or current_room == 'Barristan\'s Chambers':
print('You are in {}.'.format(current_room))
if item not in inventory:
print('Item:', item, '\n')
else:
print('You have collected all of the items in this room.\n')
elif current_room != 'Terrace':
print('You are in the {}.'.format(current_room))
if current_room == 'Torture Cells':
print('A sign reads: "Beware of Dragon Pit: East"')
if item not in inventory:
print('Item:', item, '\n')
else:
print('You have collected all of the items in this room.\n')
# Display user input
user_input = input('Enter your move:' + '\n' + '> ') # Movement control
print('') # Space for visual formatting
user_input = user_input.capitalize() # Capitalize user input to match dictionary
print('<>' * 50)
if user_input in move_direction:
user_input = user_input
if user_input in rooms[current_room].keys():
current_room = rooms[current_room][user_input]
print(current_room)
print('<>' * 50)
else:
# for invalid movement
print('You can\'t go there!')
print('<>' * 50)
# Check for exit command
elif user_input == 'Exit':
print('Thank you for playing!')
print('<>' * 50)
break
# invalid command
elif 'Take' not in user_input:
print('Invalid input\n')
if current_room != 'Terrace' and current_room != 'Dragon Pit':
item = rooms[current_room]['item']
# Update inventory
if 'Take' in user_input and current_room != 'Terrace' and item not in inventory:
inventory.append(item)
print('You found:', item)
print('<>' * 50)
if current_room == 'Terrace' and 'Take' in user_input:
print('There is no item here!')
print('<>' * 50)
# Game over
if len(inventory) == 6 and current_room == 'Dragon Pit':
print('\nYou have defeated the Dragons and saved the Seven Kingdoms!')
print('Thanks for playing!')
restart_game()
elif len(inventory) < 6 and current_room == 'Dragon Pit':
print('\nYou died.')
print('Collect all six items before facing the Dragons...')
restart_game()
def restart_game():
# Restart or exit game
restart = input('Play again? (y,n):\n> ')
if restart == 'y':
start_menu()
gameplay_loop()
if restart == 'n':
print('Goodbye.')
sys.exit()
else:
print('Invalid input')
restart_game()
gameplay_loop()
`
I tried adding this to my code but it still just accepts 'Take' for user input.
`
# invalid command
elif ('Take'+item) not in user_input:
print('Invalid input\n')
`
This operates the way you expect. I've made several changes in the organization here. I have removed all of your "automatic capitalization", so you must type the command exactly. I have removed all of your recursive calls and replaced them with loops -- this is not a proper use of recursion.
I also deleted your block title because I didn't want to deal with the character set. You can add that back in.
import sys
def start_menu():
# Print start menu and commands
print('<>' * 50)
print('You are a Spy visiting the Great Pyramid of Meereen. You must make your way from the top of the\n'
'Pyramid to the Dragon Pit. Collect all of the items along the way to help defeat the two Dragons.\n'
'If you are successful you will put an end to Queen Daenerys reign and save the Seven Kingdoms.\n'
'\nHappy Adventuring!')
print('<>' * 50)
print('Input move: North, South, East or West')
print('Input "Take [item name]" to add item to inventory')
print('Input "Exit" to quit game')
print('<>' * 50)
# Dictionary of rooms and items
rooms = {
'Terrace': {'East': 'Daenerys Chambers'},
'Daenerys Chambers': {'West': 'Terrace', 'East': 'Barristan\'s Chambers', 'South': 'Royal Chambers',
'item': 'Dragon Necklace'},
'Barristan\'s Chambers': {'West': 'Daenerys Chambers', 'item': 'Barristan\'s Sword'},
'Royal Chambers': {'North': 'Daenerys Chambers', 'South': 'Torture Cells',
'West': 'Audience Chamber', 'East': 'Stables', 'item': 'Milk of the Poppy'},
'Audience Chamber': {'East': 'Royal Chambers', 'item': 'Torch'},
'Stables': {'West': 'Royal Chambers', 'item': 'Health Potion'},
'Torture Cells': {'North': 'Royal Chambers', 'East': 'Dragon Pit', 'item': 'Magic Potion'},
'Dragon Pit': {'West': 'Torture Cells', 'Item': 'Dragons'}
}
def gameplay_loop():
move_direction = ['North', 'South', 'East', 'West']
inventory = []
current_room = 'Terrace'
# Gameplay loop
while True:
# Display Inventory
print('Inventory', inventory, '\n')
if current_room == 'Terrace':
print('You are on the {}.\n'.format(current_room))
else:
print('You are in the {}.'.format(current_room))
if current_room == 'Torture Cells':
print('A sign reads: "Beware of Dragon Pit: East"')
item = None
if 'item' in rooms[current_room]:
item = rooms[current_room]['item']
if item in inventory:
print('You have collected all of the items in this room.\n')
item = None
else:
print('Item:', item, '\n')
# Display user input
user_input = input('Enter your move:' + '\n' + '> ') # Movement control
print('') # Space for visual formatting
# user_input = user_input.title() # Capitalize each word
print('<>' * 50)
if user_input in move_direction:
user_input = user_input
if user_input in rooms[current_room].keys():
current_room = rooms[current_room][user_input]
print(current_room)
print('<>' * 50)
else:
# for invalid movement
print('You can\'t go there!')
print('<>' * 50)
continue
# Check for exit command
elif user_input == 'Exit':
print('Thank you for playing!')
print('<>' * 50)
break
# invalid command
elif 'Take' not in user_input:
print('Invalid input\n')
continue
# What item did they want?
want = user_input[5:]
if want != item:
print("That item is not available.")
continue
# Update inventory
if current_room != 'Terrace' and item not in inventory:
inventory.append(item)
print('You found:', item)
print('<>' * 50)
# Check for game over
if len(inventory) == 6 and current_room == 'Dragon Pit':
print('\nYou have defeated the Dragons and saved the Seven Kingdoms!')
print('Thanks for playing!')
elif len(inventory) < 6 and current_room == 'Dragon Pit':
print('\nYou died.')
print('Collect all six items before facing the Dragons...')
while True:
# Restart or exit game
restart = input('Play again? (y,n):\n> ')
if restart == 'y':
start_menu()
return True
if restart == 'n':
print('Goodbye.')
return False
print('Invalid input')
start_menu()
while gameplay_loop():
pass
To validate Take + Items, you need to read input and store them somthing like below if i understand correctly .
# Check for Take in input and Item name
elif 'Take' in user_input:
item = user_input[5:]
if item in rooms[current_room].values():
inventory.append(item)
print('You have added {} to your inventory.'.format(item))
print('<>' * 50)
else:
print('You can\'t take that!')
print('<>' * 50)```

Python text based game - How to show the correct output when player wins or loses game by reaching the room with the villain

My code works fine moving between rooms and collecting items but when player gets to the Food court where the villain is without all 6 items in the inventory it should output the player lost, or if player has all item then player wins. See my code below, I added an "if len(Inventory) == and !=" but it isn't working. Any help is appreciated.
This is my first programing/scripting course I take so I need this code probably needs a lot more work than what I think but this is what I have so far.
#enter code here#
#instructions
print('You are at the mall and there is an Alien in the Food Court that you must defeat!')
print("You can only move around the mall by typing 'North', 'South', 'East', or 'West' when asked for your move. Type 'Exit' at any time to leave the game. ")
print("You need to collect 6 items from 6 different stores to defeat the Alien.")
print("If you get to the Alien without all 6 items in your inventory, you die and lose the game.")
print('Good luck!')
rooms = { 'Marshalls': {'name': 'Marshalls', 'East': 'Miscellaneous', 'North': 'Champs'},
'Miscellaneous': {'name': 'Miscellaneous', 'West': 'Marshalls'},
'Champs': {'name': 'Champs', 'North': 'Pharmacy', 'South': 'Marshalls', 'East': 'Sports', 'West': 'Food Court'},
'Sports': {'name': 'Sports', 'North': 'Verizon'},
'Verizon': {'name': 'Verizon', 'South': 'Sports'},
'Food Court': {'name': 'Food Court', 'East': 'Champs'},
'Pharmacy': {'name': 'Pharmacy', 'East': 'Toys', 'South': 'Champs'},
'Toys': {'name': 'Toys', 'West': 'Pharmacy'},
}
items = {'Miscellaneous': 'Rope',
'Champs': 'Running shoes',
'Sports': 'Baseball bat',
'Verizon': 'Phone',
'Pharmacy': 'Tranquilizer',
'Toys': 'Water gun'
}
direction = ['North', 'South', 'East', 'West'] #how player can move
current_room = 'Marshalls'
Inventory = []
#function
def get_new_statement(current_room, direction):
new_statement = current_room #declaring current player location
for i in rooms: #loop
if i == current_room:
if direction in rooms[i]:
new_statement = rooms[i][direction] #assigning new direction to move player
return new_statement #return
while True:
print('You are in the', current_room, 'store')
print('Current inventory:', Inventory)
print('__________________________')
direction = input('Type an allowed direction to move to another store? or type Exit to leave game: ' )
direction = direction
if (direction == 'exit'):
print('Goodbye, thanks for playing!')
exit()
if (direction == direction):
new_statement = get_new_statement(current_room, direction)
if new_statement == current_room:
print('Move not allowed, try again.')
else:
current_room = new_statement
else:
print('Invalid entry')
#ask to collect item in current room
if current_room in items.keys() and items[current_room] != None and items[current_room] != 'Food Court':
print('You an item: ', items[current_room])
option = input('Do you wish to collect it (y/n): ')
if option[0] == 'y' or option == 'Y':
Inventory.append(items[current_room])
items[current_room] = None
#if player gets to the Food Court then player either win or looses the game
if current_room in items.keys() and items[current_room] == 'Alien':
if len(Inventory) == 6:
print('Congrats you defeated the Alien!!')
elif len(Inventory) != 6:
print("You lost")
print('Goodbye')
break
You need to change the line
if current_room in items.keys() and items[current_room] == 'Alien':
to
if current_room == 'Food Court':
Because current_room isn't in items, so the if statement always goes false. If you put Food Court in items, with alien as its value, then it will ask you if you want to collect it. So you need to just check if the room is Food Court, then it will evaluate to true.
Note: You might want to make it check if direction.lower() is in the room's values, so the user can enter any type of capitalized word and it will move if it can.

Building a Text Based Game in Python, area not defined

I'm working on a text based game in python and everything seems to be working except for the area which the player will travel to and collect items in. When I start the game, it goes through the intro (which I left out) and then shows me this error along with the player's stats:
item = player(location)
enter code hereline 59, in player
return area[location]['item']
NameError: name 'area' is not defined
I don't really understand how to fix it, I've been trying to define area but I'm still getting the same error.
def rules():
print(' \n Using the commands, North, South, East and West to navigate through the warehouse.')
print('Find your Tiramisu cake! Search the rooms of the warehouse to get your cake!')
print('........Or use Exit to leave the game.')
area = {
'Warehouse': {
'South': 'Basement', 'North': 'Storage Room', 'East': 'Parking Lot', 'West': 'Dusty Room'
},
'Parking Lot': {'West': 'Warehouse','item': 'key'},
'Basement': {'North': 'Warehouse', 'item': 'Kingpin'},
'Storage Room': {'South': 'Warehouse', 'item' : 'Tiramisu Cake'},
'Dusty Room': {'East': 'Warehouse', 'item': 'Safe' }
}
location = 'Warehouse'
def fetch(location, new_dir):
new_room = location
for i in area:
if i == location:
if new_dir in area [i]:
new_room = area [i][new_dir]
return new_room
def stats(location):
return area[location]['item']
rules()
pockets = []
#loop starts here
while 1:
print('\n***********************************************')
print('You are in the', location)
print('In your pockets you hold', pockets)
print('***********************************************')
item = area[location].get('item')
print('In this room you see', 'item')
if item == 'Kingpin':
print ('Oh no! The Kingpin!!......He pummels you, Game Over')
exit(0)
if item is not None and new_dir == 'You got ' + item:
if item in pockets:
print('This room seems empty.....oh wait you already got that item')
else:
pockets.append
new_dir = input('\n Which direction are you going?: ')
new_dir = new_dir.capitalize
if (new_dir == 'Exit'):
print('Thanks for playing!')
exit(0)
if new_dir == 'North' or new_dir == 'South' or new_dir == 'East' or new_dir == 'West':
new_room = fetch(location, new_dir)
if new_room == location:
print(' \n Invalid move, try another direction.')
else:
location = new_room
if new_dir ==str('get'+ 'item'):
if 'item' in pockets:
print('You found', 'item', '!')
pockets.append(area[location]['item'])
else:
print('Invalid move')
if len(pockets) ==3:
print('You have got what you came for, you win! Thanks for playing!')
exit(0)
break
You haven't passed area to the fecth() and stats() functions.
Either pass it or make it global

Categories