Text-base game inventory list (Python) - python

so I'm new to python and I am making a text base game. I created an inventory list and in case the player picks up an item more than once, the second time it should be able to give a message saying that they already have this item. I got it to work to an extent where the item doesn't go over the value more than one, but it does not print the message. Please help!!
elif decision == "use H on comb":
global inventory
if inventory.count("comb")>1:
print ("You already got this item.")
print ("")
print ("Inventory: " + str(inventory))
if inventory.count("comb")<1:
print ("(pick up comb)")
print ("You went over to the table and picked up the comb,")
print ("it's been added to your inventory.")
add_to_inventory("comb")
print("")
print ("Inventory: " + str(inventory))
game()

just use the in operator to test for membership
if "comb" in inventory:
print("I have found the comb already...")
else:
print("Nope not here")
but as to why your code was failing was that
inventory.count('comb') == 1
# which fails inventory.count('comb') > 1 test
# but also fails inventory.count('comb') < 1 test so its not re added
you could have easily solved this yourself by printing the value of inventory.count('comb') , which is a useful method for debugging your program for beginners... basically when something doesnt work correctly, try printing it, chances are the variable is not what you think it is...

maybe a little more structuring can be done and avoid using global inventory .jsut a basic idea below:
def game():
inventory = []
# simulate picking up items( replace this loop with your custom logic )
while True:
item = raw_input('pick up something')
if item in inventory: # use in operator to check membership
print ("you already have got this")
print (" ".join(inventory))
else:
print ("pick up the item")
print ("its been added to inventory")
inventory.append(item)
print (" ".join(inventory))

Related

How would I effectively lock a room for a text based game?

I'm using python 2.7 for this game. I have looked at other answers and questions similar to this but since I'm a python beginner with some experience with python I don't really understand some of the answers and some of the answers I saw weren't that clear. Because of the current code I have, it created a problem where when I got the item necessary to unlock the room it says the room has not been found. This is the code:
## checks which connecting rooms player.currentRoom has available and updates currentRoom on player choice.
def navigate(player,enemyToken):
os.system("clear")
# print available rooms to navigate to
i = 0
for room in player.currentRoom.connectingRooms:
print(str(i) + ": " + room.name)
i = i + 1
try:
navigate = input("Choose room to navigate to [type its number]: ")
# change players current room to selected room and contains the locking code after the "and".
if(navigate <= len(player.currentRoom.connectingRooms) and player.items[0].unlocks == room == True):
player.currentRoom = player.currentRoom.connectingRooms[navigate]
else:
print("room not found!")
time.sleep(1)
except NameError:
print("that was not a number!")
time.sleep(1)
except SyntaxError:
print("that was not a number!")
time.sleep(1)
except IndexError:
print("that was not an option!")
time.sleep(2)
how would I make a lock that would succesfully lock the player from accessing that room untill they have grabbed the object that is required to open this room. If you need more code to help me I would provide it.
Based on my comment, this code should word(Untested as I do not know where the locking mechanism should go)
Code:
x = True
while x = True:
if LockRoom != RoomUnlock:
Code here
else:
Code here when you unlock the room
x = False
player.items[0].unlocks == room == True
This part looks weird to me. player.items[0].unlocks == room should be sufficient to check if the two numbers match.

errors with Elif expected indented block

I'm trying to create a menu for my application, the menu has 4 options and each of these options should return with the correct information when the user has entered the chosen value. i keep getting an error with the Elif statements.
I am a newbie so please understand where am coming from.
much appreciation.
when i indent the while ans: i will receive an error says invalid syntax after indenting the elif ans==2.
elif ans==2 <--- this error keeps saying indention block error or syntex invalid when i indent it.
def print_menu(self,car):
print ("1.Search by platenumber")
print ("2.Search by price ")
print ("3.Delete 3")
print ("4.Exit 4")
loop=True
while loop:
print_menu()
ans==input("Please choose from the list")
if ans==1:
print("These are the cars within this platenumber")
return platenumber_
while ans:
if ans==2:
elif ans==2:
print("These are the prices of the cars")
return price_
elif ans==3:
print("Delete the cars ")
return delete_
elif ans==4:
return Exit_
loop=False
else:
raw_input("please choose a correct option")
You have a while loop without a body. Generally speaking, if there is an indentation error message and the error is not on the line mentioned, it's something closely above it.
loop=True
while loop:
print_menu()
ans = int(input("Please choose from the list"))
if ans==1:
print("These are the cars within this platenumber")
# return some valid information about plate numbers
elif ans==2:
print("These are the prices of the cars")
# return some valid information about pricing
elif ans==3:
print("Delete the cars ")
# Perform car deletion action and return
elif ans==4:
# I am assuming this is the exit option? in which case
# return without doing anything
else:
# In this case they have not chosen a valid option. Send
# A message to the user, and do nothing. The while loop will run again.
print("please choose a correct option")
Also, your code is a bit confusing to me. It looks like you're going to return car_ no matter what, which means your loop will only execute once. Also, = is assignment and == is equality. Be careful.

Python fill-in-the-blanks code

I am a programming beginner and I am trying to build a fill-in-the-blank quiz. I am almost finished but I am stuck on 2 problems I am not able to solve, whatever I do. I would really appreciate your help with this. Thank you for helping me with this!
If you try to run the code and play the game:
1) It prints the quiz according to the difficulty(easy-insane) and quiz you want to play(apple, bond and programming quiz) which is great but afterwards it prompts you to choose difficulty again (the player_level() function keeps going even though the player/user has already chosen the difficulty level. I don't really understand why it does it? The player_level() procedure seems perfectly okay and logical to me.
2) The errors:
a) local variable blanks_index referenced before assignment
b) global name list_of_answers is not defined.
I know that it is related to the initialize_game() function but I don't know how to change the code so it refers all the variables (blanks_index, answers_index, player_lives) correctly.
It could be solved by creating global variables(I guess) but that is not a good practice so I am trying to avoid it. Formerly, the whole function initialise_game() and play_game() were one function, but as there are over 25 lines of code in one function, it is not a good practice as it is long and messy and I know that I can separate it but I don't know how.
Here is the code:
"""3 diffferent quizzes : Apple quiz, James Bond quiz, Programming quiz"""
"""Quiz and answers about Apple"""
Apple_quiz = ("The most valuable company in terms of market cap in 2016 is, ___1___."
"It was founded in ___2___. Its flagship product is called ___3___."
"___1___ has many competitors, the biggest rival is ___4___,founded by"
" nobody but the richest man on the planet,___5___ ___6___.")
list_of_answers_Apple = ["Apple", "1976", "Iphone", "Microsoft", "Bill", "Gates"]
"""Quiz and answers about Bond"""
Bond_quiz = ("James Bond is agent ___1___. He serves his country,___2___ ___3___"
" against its enemies. His car of choice is usually ___4___ ___5___."
" His favorite drink is ___6___.")
list_of_answers_Bond = ["007", "United", "Kingdom", "Aston", "Martin", "Martini"]
"""Quiz and answers about programming basics"""
Programming_quiz = ("___1___ are created with the def keyword. ___1___ are also called ___2___"
" You specify the inputs a ___1___ take by adding ___3___ separated by commas"
" between the parentheses. ___3___ can be standard data types such as string, number"
" ,dictionary, tuple, and ___4___ or can be more complicated such as ___5___"
" and ___6___ functions.")
list_of_answers_Programming = ["Functions", "procedures", "arguments", "lists", "objects", "lambda"]
blank_space = ["___1___", "___2___", "___3___", "___4___", "___5___", "___6___]"]
#List of levels with corresponding lives/guesses that player can have
quiz_list = ["Apple", "Bond", "Programming"]
level_list = ["easy", "medium", "hard", "superhard", "insane"]
lives_easy = 5
lives_medium = 4
lives_hard = 3
lives_superhard = 2
lives_insane = 1
def choose_quiz():
""" Prompts player to pick a type of quiz and loads the quiz """
#Input = player_quiz (raw input from player)
#Output = loaded quiz, player chose
while True:
player_quiz = raw_input("Please, select a quiz you want to play: "
"(Apple, Bond or Programming): ")
if player_quiz == "Apple":
return Apple_quiz
elif player_quiz == "Bond":
return Bond_quiz
elif player_quiz == "Programming":
return Programming_quiz
else:
print "We don't have such quiz, pick again!"
def answers_for_quiz():
""" Loads appropiate answers to the quiz that player has chosen"""
#Input = player quiz (raw input from player)
#Output = loaded quiz answers from the quiz player chose
player_quiz_pick = choose_quiz()
if player_quiz_pick == Apple_quiz:
return list_of_answers_Apple
elif player_quiz_pick == Bond_quiz:
return list_of_answers_Bond
elif player_quiz_pick == Programming_quiz:
return list_of_answers_Programming
def player_level():
""" Loads a difficulty that player chooses """
#Input = player_level_input (raw input of player choosing a difficulty)
#Output = corresponding number of lives:
#Easy = 5 lives, Medium = 4 lives
#Hard = 3 lives, Superhard = 2 lives
#Insane = 1 life
while True:
player_level_input = raw_input("Please type in a difficulty level: "
"(easy, medium, hard, superhard, insane): ")
if player_level_input == "easy":
return lives_easy #Easy = 5 lives
elif player_level_input == "medium":
return lives_medium #Medium = 4 lives
elif player_level_input == "hard":
return lives_hard #Hard = 3 lives
elif player_level_input == "superhard":
return lives_superhard #Superhard = 2 lives
elif player_level_input == "insane":
return lives_insane #Insane = 1 life
else:
print "We do not have such difficulty! Pick again!"
def correct_answer(player_answer, list_of_answers, answers_index):
""" Checks, whether the the answer from player matches with the answer list. """
#Input: player_answer (raw input that player enters in order to fill in the blank)
#Output: "Right answer!" or "Wrong! Try again!" this output will be later used in the game
if player_answer == list_of_answers[answers_index]:
return "Right answer!"
return "Wrong! Try again!"
def initialize_game():
"""Functions that sets up a game so we can play it """
player_quiz_pick, player_level_pick, list_of_answers = choose_quiz(), player_level(), answers_for_quiz()
print player_quiz_pick
print "\nYou will get maximum " + str(player_level_pick) + " guesses for this game. Good luck.\n"
blanks_index, answers_index, player_lives = 0, 0, 0
#for elements in blank_space:
while blanks_index < len(blank_space):
player_answer = raw_input("Please type in your answer for " + blank_space[blanks_index] + ": ")
if correct_answer(player_answer,list_of_answers,answers_index) == "Right answer!":
print "Correct answer! Keep going!\n"
player_quiz_pick = player_quiz_pick.replace(blank_space[blanks_index],player_answer)
answers_index += 1
blanks_index += 1
print player_quiz_pick
if blanks_index == len(blank_space):
print "Congratulations! You nailed it! You are the winner!"
else:
player_level_pick -= 1
if player_level_pick == 0:
print "Game over! Maybe next time!"
break
else:
print "One life less, that sucks! Have another shot!"
print "You have " + str(player_level_pick) + " guesses left."
initialize_game()
Your main problem is that you keep calling the same functions over and over again and do not save the input into variables. Here are some tips about your code and questions:
You are not doing anything with your player_level() method call, so the player doesn't actually chooses a level in a way that affects the game. You should change the function call, so the returned value will be stored.
//the call to the method:
player_level_pick = player_level()
Afterwards, you keep calling the player_level() method, and not using the actual answer that the user supplied. Change all player_level() appearences to player_level_pick - the variable you use to save the answer (as I showed above). Same goes to all other unneeded function calls such as choose_level().
You should initialize number_of_guesses, player_lives, list_of_answers, and other vars to a matching value to player_level_pick as well, so it will hold the right value according to the level. Likewise, you should change this line:
# the line that checks if game is over
# change from:
if number_of_guesses == player_lives:
# to :
if number_of_guesses == 0:
In order to return multiple values, you have to use tuples. Using multiple return statements one after the other does not work anywhere.
so, instead of:
return list_of_answers
return number_of_guesses
return blanks_index
return answers_index
return player_lives
you should use tuples, and unpack them properly:
# the return statement:
return (list_of_answers, number_of_guesses, blanks_index, answers_index, player_lives)
# and the unpacking in the calling function:
list_of_answers, number_of_guesses, blanks_index, answers_index, player_lives = initialize_game()
this way, all of the returned values go into the wanted variables in the calling function. this way, you need to call the initialize_game() from play_game(). it will be the efficient way for you.
Just saying it again, as I said in the end of (4) - you should unit initialize_game() and play_game() into a single function (because a lot of data is the same needed data), or just call initialize_game() from play_game().
Better practice then using this recursivly: return choose_level(), you should use a while True: loop, and just brake when you get a proper answer.

Python failing IF STATEMENTS/ Changing Variables

I'm having an issue. Speedy responses would be greatly appreciated! My program is failing IF conditions becuase my functions are not changing the global variable properly for me. They're supposed to, for example, be able to go south and take a key. With that key they can go East and open a locked drawer. Except... they fail the if check to be able to open the drawer.
Thanks in advance! The code blocks in question should be below!
def south():
print ("You can see a key just lying there on the table! What luck!")
choice = raw_input("You better TAKE that!")
if choice == 'TAKE' :
print "You took the key!"
return Key1 == 1, moverooms()
else:
print "You didn't take the key to freedom!?"
south()
def east():
print("You can see a drawer here! Wonder what is inside?")
choice = raw_input("You can MOVEROOMS, or try to USE the drawer and TAKE what's inside...\n ")
if choice == 'USE' :
print "You try to open the drawer... \n"
if Key1 == 1 :
print "You use the key to open the drawer and find a flashlight inside! Better TAKE it!"
Drawer == 1
east()
else:
print ("It's locked! Better find a key...\n")
east()
You really don't want to use global variables, but if you must, your problem seems to be that you're not assigning Key1 = 1 in your TAKE conditional, but returning True or False according to whether or not it already has that value (Key1==1). Note that you need to set it before the return.
Note that if you want to do this (you don't), you'll need to assert global Key at the top of your south() function.
To avoid global variables, return a value for Key1 from south and pass it to east:
def south():
print ("You can see a key just lying there on the table! What luck!")
choice = raw_input("You better TAKE that!")
if choice == 'TAKE' :
print "You took the key!"
Key1 = 1
else:
print "You didn't take the key to freedom!?"
Key1 = 0
return Key1
def east(Key1):
print("You can see a drawer here! Wonder what is inside?")
choice = raw_input("You can MOVEROOMS, or try to USE the drawer and TAKE what's inside...\n ")
if choice == 'USE' :
print "You try to open the drawer... \n"
if Key1 == 1 :
print "You use the key to open the drawer and find a flashlight inside! Better TAKE it!"
Drawer = 1
return Drawer
else:
print ("It's locked! Better find a key...\n")
Drawer = 0
return Drawer
You'll have to handle the logic of the calls to south and east yourself, though.
This might be overkill, but ideally you'll do something along these lines:
class Character(object):
"""
This class represents the player.
It keeps track of found items, opened drawers, etc...
"""
def __init__(self):
# game start: Key not found, drawer not opened.
self.has_key= False
self.has_opened_drawer= False
def go_south(self):
print "You can see a key just lying there on the table! What luck!"
choice = raw_input("You better TAKE that!\n")
if choice == 'TAKE' :
print "You took the key!"
self.has_key= True
else:
print "You didn't take the key to freedom!?"
def go_east(self):
print "You can see a drawer here! Wonder what is inside?"
choice = raw_input("You can MOVEROOMS, or try to USE the drawer and TAKE what's inside...\n")
if choice == 'USE':
print "You try to open the drawer... \n"
if self.has_key:
print "You use the key to open the drawer and find a flashlight inside! Better TAKE it!"
self.has_opened_drawer= True
else:
print "It's locked! Better find a key...\n"
def input_loop(self):
while True:
choice= raw_input('Do you want to go SOUTH or EAST?\n')
if choice=='SOUTH':
self.go_south()
elif choice=='EAST':
self.go_east()
player= Character() # create a Character
player.input_loop() # and let the user control it
Instead of using global variables, you create a Character to store all necessary data, like whether the key was found, or whether the drawer has been opened. That way you won't clutter your global scope with variables.

Use of lists for collecting items

I'm currently going through the book "Learning Python The Hard Way", and I'm trying to make a simple game. In this game, I want to be able to pick up at item "Flashlight" in one room, to be able to get into another room. I can, however, not make it work :-(
So the question is, how do I carry the same list through several functions, and how do I put things in it? I want to be able to put multiple things in it.
I tried to call the pick() function within it self, but keep getting a "TypeERROR: 'str' is not callable, though I am providing my function with a list?
Hope you can help me out, thanks :-)
Code:
def start(bag):
print "You have entered a dark room"
print "You can only see one door"
print "Do you want to enter?"
answer = raw_input(">")
if answer == "yes":
light_room(bag)
elif answer == "no":
print "You descidede to go home and cry!"
exit()
else:
dead("That is not how we play!")
def light_room(bag):
print "WOW, this room is amazing! You see magazines, cans of ass and a flashlight"
print "What do you pick up?"
print "1. Magazine"
print "2. Cans of ass"
print "3. Flashlight"
pick(bag)
def pick(bag):
pick = raw_input(">")
if int(pick) == 1:
bag.append("Magazine")
print "Your bag now contains: \n %r \n" % bag
elif int(pick) == 2:
bag.append("Can of ass")
print "Your bag now contains: \n %r \n" % bag
elif int(pick) == 3:
bag.append("Flashlight")
print "Your bag now contains: \n %r \n" % bag
else:
print "You are dead!"
exit()
def start_bag(bag):
if "flashlight" in bag:
print "You have entered a dark room"
print "But your flashlight allows you to see a secret door"
print "Do you want to enter the 'secret' door og the 'same' door as before?"
answer = raw_input(">")
if answer == "secret":
secret_room()
elif answer == "same":
dead("A rock hit your face!")
else:
print "Just doing your own thing! You got lost and died!"
exit()
else:
start(bag)
def secret_room():
print "Exciting!"
exit()
def dead(why):
print why, "You suck!"
exit()
bag = []
start(bag)
I tried to call the pick() function within it self, but keep getting a "TypeERROR: 'str' is not callable, though I am providing my function with a list?
The problem here is that in this line:
def pick(bag):
pick = raw_input(">")
you bind pick to a new value (a str) so it doesn't reference a function anymore. Change that to something like:
def pick(bag):
picked = raw_input(">")

Categories

Resources