I am stayed in getting the right coding. If you happen to run this code, please correct what you see fit. I have searched and there continues to be bugs here and there. Here is the game coding. There may be some issues in the definition terms and I'm still learning the Python vocabulary to defined new items and am not finding right answers. Here is the code that you can run and try. Thank you:
import random
import time
def displayIntro():
print("You are in a city. In front of you,")
print("you see two restraunts. In one pizzeria, the service is friendly")
print("and will share thier free pizza with you. The other pizzeria")
print("is very unpredictable and will hire you to wash the dishes in the back quick.!")
print()
def choosePizzeria():
pizzeria=""
while((pizzeria != "1") and (pizzeria != "2")):
print("Which pizzeria will you go into? (1 or 2) ")
pizzeria = input()
return pizzeria
def checkPizzeria(level,(pizzeria != "1") or (pizzeria != "2")):
print("You approach the pizzeria and see people hustling in and out quickly...")
time.sleep(2)
print("It really crowded with people waiting in line, playing arcade games and just having a good time dancing...")
time.sleep(2)
print("A little manager with a suit steps in in front of you! He quickly slips his arm behind his back...")
print()
time.sleep(2)
friendlypizzeria = random.randint(1, 3)
overworkPizzeria = friendlypizzeria + 1
if overworkPizzeria > 3:
overworkPizzeria -= 3
if chosenPizzeria == str(friendlyPizzeria):
print("Hand you a slip of paper for two free pizzas!")
elif chosenPizzeria == str(overworkPizzeria):
print("He hands you a slip of paper telling you to watch the dishes in the back for a while since you stared at him too long!")
else:
level += 1
if level < 3:
print("You quickly hid behind some customes and head out to 3 more pizzerias")
else:
print("Congratulations you win two free pizzas and")
print("you get to go to the manager's weekend party!!!! ")
return level
playAgain = "yes"
while playAgain == "yes" or playAgain == "y":
displayIntro()
level = 0
pizzeriaNumber = choosePizzeria()
level = checkPizzeria(level,pizzeriaNumber)
if level == 1:
pizzeriaNumber = choosePizzeria()
level = checkPizzeria(level,pizzeriaNumber)
if level == 2:
pizzeriaNumber = choosePizzeria()
level = checkPizzeria(level,pizzeriaNumber)
print('Do you want to play again? (yes or no)')
playAgain = input()
Thank you.
Mostly Syntax errors, I would suggest reading some Python documentation. Especially in regards to Types, and Comparison Operators. But below will run;
import random
import time
def displayIntro():
print("You are in a city. In front of you,")
print("you see two restraunts. In one pizzeria, the service is friendly")
print("and will share thier free pizza with you. The other pizzeria")
print("is very unpredictable and will hire you to wash the dishes in the back quick.!")
print()
def choosePizzeria():
pizzeria=""
while((pizzeria != 1) and (pizzeria != 2)):
print("Which pizzeria will you go into? (1 or 2) ")
pizzeria = input()
return pizzeria
def checkPizzeria(level, pizzariaNumber):
print("You approach the pizzeria and see people hustling in and out quickly...")
time.sleep(2)
print("It really crowded with people waiting in line, playing arcade games and just having a good time dancing...")
time.sleep(2)
print("A little manager with a suit steps in in front of you! He quickly slips his arm behind his back...")
print()
time.sleep(2)
chosenPizzeria = pizzariaNumber
friendlypizzeria = random.randint(1, 3)
overworkPizzeria = friendlypizzeria + 1
if overworkPizzeria > 3:
overworkPizzeria -= 3
if chosenPizzeria == friendlypizzeria:
print("Hand you a slip of paper for two free pizzas!")
elif chosenPizzeria == overworkPizzeria:
print("He hands you a slip of paper telling you to watch the dishes in the back for a while since you stared at him too long!")
else:
level += 1
if level < 3:
print("You quickly hid behind some customes and head out to 3 more pizzerias")
else:
print("Congratulations you win two free pizzas and")
print("you get to go to the manager's weekend party!!!! ")
return level
playAgain = "yes"
while playAgain == "yes" or playAgain == "y":
displayIntro()
level = 0
pizzeriaNumber = choosePizzeria()
level = checkPizzeria(level,pizzeriaNumber)
if level == 1:
pizzeriaNumber = choosePizzeria()
level = checkPizzeria(level,pizzeriaNumber)
if level == 2:
pizzeriaNumber = choosePizzeria()
level = checkPizzeria(level,pizzeriaNumber)
print('Do you want to play again? (yes or no)')
playAgain = raw_input()
Related
I need to include a decrement life counter that has 5 lives. I need to use a while loop and once the player loses a life it needs to send them back to the choice between going left and right in the code. I am new to python so I am not very familiar with it, any help is appreciated.
answer = input("Do you want to go on an adventure? (Yes/No) ")
if answer.lower().strip() == "yes":
x=5
while x > 0:
print("You have ",x,"lives left.")
if x > 0:
break
x-=1
if x == 0:
break
answer= input("You are lost in the forest and the path splits. Do you go left or right? (Left/Right) ").lower().strip()
if answer == "left":
answer = input("An evil witch tries to cast a spell on you, do you run or attack? (Run/Attack) ").lower().strip()
if answer == "attack":
print("She turned you into a green one-legged chicken, you lost!")
elif answer == "run":
print("Wise choice, you made it away safely.")
answer = input("You see a car and a plane. Which would you like to take? (Car/Plane) ").lower().strip()
if answer == "plane":
print("Unfortunately, there is no pilot. You are stuck!")
elif answer == "car":
print("You found your way home. Congrats, you won!")
elif answer != "plane" or answer != "car":
print("You spent too much time deciding...")
else:
print("You are frozen and can't talk for 100 years...")
elif answer == "right":
import random
num = random.randint(1, 3)
answer = input("Pick a number from 1 to 3: ")
if answer == str(num):
print("I'm also thinking about {} ".format(num))
print("You woke up from this dream.")
elif answer != num:
print("You fall into deep sand and get swallowed up. You lost!")
else:
print("You can't run away...")
else:
print("That's too bad!")
You should try to add comments to your code, it will help you and others as well.
I think for getting user answer, you should use a different variable. It will make things easier.
I removed the following code, it didn't make any sense to me.
while x > 0:
print("You have ",x,"lives left.")
if x > 0:
break
x-=1
if x == 0:
break
--
This is the code, which works:
# Try to write imported modules at the top, it's a good practice.
import random
# Start the game
answer_start = input("Do you want to go on an adventure? (Yes/No) ")
# user chooses to play
if answer_start.lower().strip() == "yes":
lives=5
# function for displaying the lives
def display_lives():
print("You have ",lives,"lives")
#display lives
display_lives()
# As long lives are more than 0, this will keep going.
while lives>0:
#First choice
answer1= input("You are lost in the forest and the path splits. Do you go left or right? (Left/Right) ").lower().strip()
#User chooses left
if answer1 == "left":
answer2 = input("An evil witch tries to cast a spell on you, do you run or attack? (Run/Attack) ").lower().strip()
if answer2 == "attack":
print("She turned you into a green one-legged chicken, you lost!")
lives=lives-1
display_lives()
# User is running away
elif answer2 == "run":
print("Wise choice, you made it away safely.")
answer3 = input("You see a car and a plane. Which would you like to take? (Car/Plane) ").lower().strip()
if answer3 == "plane":
print("Unfortunately, there is no pilot. You are stuck!")
elif answer3 == "car":
print("You found your way home. Congrats, you won!")
elif answer3 != "plane" or answer3 != "car":
print("You spent too much time deciding...")
else:
print("You are frozen and can't talk for 100 years...")
elif answer1 == "right":
num = random.randint(1, 3)
answer4 = input("Pick a number from 1 to 3: ")
if answer4 == str(num):
print("I'm also thinking about {} ".format(num))
print("You woke up from this dream.")
elif answer4 != num:
print("You fall into deep sand and get swallowed up. You lost!")
lives=lives-1
else:
print("You can't run away...")
#Player chose not to play or player out of lives.
else:
print("That's too bad!")
import rando
move = rando.Moves()
All of this junk is just writing to a file to give some context about the game
oof = open('README.txt', 'w') #opens the text file
oof.write("The Final Adventure\n")
oof.write("\n") #writes text to the file
oof.write("This game is about an adventurer(you) trying to fight through a
dungeon in order to get the legendary sword of mythos.\n")
oof.write("\n")
oof.write("With this legendary sword you can finally rid your homeland of
the evil king of Mufasa and take the mantle of kingship.\n")
oof.write("\n")
oof.write("Best of luck to you, Warrior!\n")
oof.write("\n")
oof.write("You have 3 move options with any enemy you encounter.\n")
oof.write("\n")
oof.write("1 - Attack\n")
oof.write("2 - Run Away\n")
oof.write("3 - Talk\n")
oof.write("Have fun!!")
oof.close() #closes the file
print("Please read the README.txt in this file")
player = True
A buddy of mine told me I had to have two while loops so not too sure why I need those but it works slightly like it's meant to.
while True:
while player:
#First Door
print("You walk through the forest until you finally find the talked
about entrance door.")
print("There is a Gatekeeper standing by the entrance and in order
to enter you must defeat him")
print("")
move = int(input("What will you do?(Please use numbers 1-2-3 for
moves) "))
The problem is here. I have a module that I made that if the attack fails, you die and player gets set to False but it still continues the while loop.
if move == 1:
rando.Moves.move1(player)
elif move == 2:
rando.Moves.move2(player)
elif move == 3:
rando.Moves.move3(player)
else:
print("You ran out of time and died")
player = False
if player == False:
break
#First Room
print("The door suddenly opens and you walk through.")
print("")
print("After walking for a bit you discover a chest, probably full
of loot!")
print("You walk up and begin to open the chest and it clamps down on
your hand with razor sharp teeth.")
print("ITS A MONSTER!")
print("After struggling, you are able to free your hand.")
move = int(input("What will you do? "))
if move == 1:
rando.Moves.move1(player)
elif move == 2:
rando.Moves.move2(player)
elif move == 3:
rando.Moves.move3(player)
else:
print("You ran out of time and died")
player = False
#Play again
play = input("Want to play again? (y/n) ")
if play == "y":
player = True
elif play == "n":
print("Goodbye!")
break
You don't need two loops, just one.
while True:
if move == 1:
rando.Moves.move1(player)
elif move == 2:
rando.Moves.move2(player)
elif move == 3:
rando.Moves.move3(player)
else:
print("You ran out of time and died")
break
...
Your code was just breaking out of the inner loop, not the outer loop.
I'm trying to make a simple text adventure game with three choices. But I can't seem to figure out why this isn't working.
This is the code I have been working on:
#Text based medieval adventure game
#Imported libraries are required
import random
import time
def displayWelcome():
print ("\nText adventure game\n")
print ("Welcome to the medieval adventure game!")
print ("You will have many choices through out this game")
print ("Be sure to pick the right one")
print (" Good Luck! ")
answer = askYesNo("Would you like help with this program? (Y/N): ")
if answer == "Y":
helpForUser()
time.sleep(3)
def askYesNo (question):
# This function will ask you a yes or no question and will keep asking until one is chosen.
# The following function is used to erase the variable response of any values
response = None
while response not in ("Y", "N"):
response = input (question).upper()
return response
def helpForUser():
#This function will show the user some helpful advice if they desire it
print ("\n+++++++++++++++++++++++++++++++++++++++ Help +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print ("This game is a adventure text based game set in the medieval times")
print ("You will be asked multiple questions with a yes or no response")
print ("you must answer the questions with the answers supplied to you suches as yes or no")
print ("If you don't answer the q uestion with the given answers it will be repeated untill a valid response occurs")
print ("The program can end when you choose")
print ("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
def displayIntro():
#Displays intro to game
print ("\n It's been a rough day in the wild and you despratly need shelter")
print ("There is currently a war going on and nowhere is safe")
print ("But you intend to find somwhere with food and a bed but it wont be easy...")
print ()
def choosePath(lower,middle,upper):
#This functions allows you to choose between multiple options
path = 0
while path < lower or path > upper:
number = input("What path will you take(" + str(lower) + " - " + str(upper) + ")?: ")
if number.isdigit():
path = int (number)
else:
path = 0
return path
def followPath(chosenPath):
print ("you head down a long road\n")
time.sleep(3)
print ("You come across an abandoned campsite and decide to stay there for the night")
time.sleep(3)
print("You wake up to a sudden sound of voices and begin to realise that this campsite wasn't abandoned...")
time.sleep(3)
print("You start to freak out")
time.sleep(3)
if chosenPath == 1:
print("You grab your sword out and decide to go out the tent")
print ("Four well trained knights surround you")
print ("They strike without any hesitation, you counter two knights trying to hit you from the front as two from behind stab you in the back")
print ("The knights decide to burn your body and leave nothing left of you.\n")
elif chosenPath == 2:
print("You dart out of the tent and head for the exit")
print("All the guards try and get you whilst shooting arrows")
print("Several arrows hit you leaving you injured unable to run")
print ("Suddenly a man with a giant axe appears before you and slices you head off in a clean swoop\n")
else chosenPath == 3:
print("You keep calm and decide to sneak past all the guards")
print ("You're close to the exit when suddenly a guard notices you")
print("He's about to call for back up when you dash right into his chest with your sword, leaving it in him and running out the campsite")
print("You make it to a safe forest and decide to rest\n")
displayWelcome()
playAgain = "Y"
while playAgain == "Y":
displayIntro()
choice = choosePath()
followPath(choice)
playAgain = askYesNo ("Would you like to play again?")
print ("\nBye")
Error Number one: line 63, else should be elif or get rid of the condition "chosenPath == 3:
Current state
else chosenPath == 3:
What it should look like
elif chosenPath == 3:
or
else:
The other error is that nothing ever happens on initialization of choice because you forgot to input the "lower, middle, upper" values.
I'm very new to programming and was doing a simple choice game:
Answer = (input("You meet a bear, what do you do? A) Give the bear a hug B) Run away"))
if Answer == ("A)"):
print("The bear chopped your hand off!")
else:
print("Good choice, but the bear is running after you")
But how do I go on? Like add an option after having proceeded with a chopped of hand or running through the forest (2 choices at least for both previous outcomes)
Here is a start you can hopefully figure out how to expand on :)
def main():
print("Tristan Aljamaa's Simple Python Choice Game")
print("===========================================")
print("Instructions: Type A) or B) etc. whenever prompted\n")
game()
def game():
Answer = (input("You meet a bear, what do you do?\n A) Give the bear a hug\n B) Run away \nEnter A) or B):"))
if Answer == ("A)"):
print("The bear chopped your hand off!")
player_died()
else:
print("Good choice, but the bear is running after you")
player_ran()
def player_died():
print("You died, the bear eventually ate you...")
Answer = (input("Game Over!\n\nEnter N) for New Game:"))
if Answer == ("N)"):
main()
else:
print("Good Bye!")
def player_ran():
Answer = (input("You find an exit from the forest, what do you do\n A) Exit forest\n B) Run around in forest \nEnter A) or B):"))
if Answer == ("A)"):
print("You exited the forest")
player_crossedRoad()
else:
print("You (although insanly) chose to run around in the forest")
player_stillRunsinForest()
def player_crossedRoad():
print("You get the idea...")
main() #for testing on this online editor use the below line when calling the .py file on your computer
if __name__ == "__main__":main()
Try the game out here
You could create different functions/procedures for different cases. For example:
def choppedHand():
selection = input("The bear chopped your hand off! What do you do now? \n 1.Fight the bear with one hand.\n 2. Scream and search for help.\n 3. Cry and beg for mercy")
if selection == "1":
fight()
elif selection == "2":
scream()
else:
cry()
def run():
selection = input ("Good choice, but the bear is running after you. What do you do now? 1.Run through the trees. 2.Run in the plain")
#etc etc, same as top.
Answer = (input("You meet a bear, what do you do?\n 1.Give the bear a hug.\n 2.Run away."))
if Answer == ("1"):
choppedHand()
else:
run()
This is just an example, but using functions you can create different options for different cases and call a function in other parts of your code. For example you character can lose his arm in a different situation and in this case you just need to recall you function choppedHand().
I hope this was what you were looking for.
def invalid():
print("Answer not valid")
def game():
Answer = input("You meet a bear, what do you do?\nA) Give the bear a hug\nB) Run away\n>? ")
if Answer == ("A"):
print("The bear chopped your hand off!")
Answer2 = input("The bear is still around you, what will you do?\nA) Bleed out and accept your fate\nB) Try to fight back\n>? ")
if Answer2 == ("A"):
print("You bled out and died")
elif Answer2 == ("B"):
print("You attempt to fight back\nYou have failed, and died")
elif Answer == ("B"):
Answer3 = input("You find a tree and the bear is still running, what do you do?\nA) Climb the tree\nB) Hide behind the tree\n>? ")
if Answer3 == ("A"):
print("You went up the tree, and the bear went away!")
print("You walked home and went to bed")
elif Answer3 == ("B"):
Answer4 = input("You fell down a hill and slid into a village, what do you do?\nA) Trade with a villager\nB) Head home\n>? ")
if Answer4 == ("A"):
Answer5 = input("There is only one merchant, will you trade?\nA) Yes\nB) No")
if Answer5 == ("A"):
print("You traded two gold coins for a sword made of strong steel")
print("You headed home")
elif Answer5 == ("B"):
print("You did not trade, so you headed home")
else:
invalid()
elif Answer4 == ("A"):
print("You headed home")
else:
invalid()
else:
invalid()
else:
invalid()
game()
ive been looking around but ive been unable to fix this error.
also as a side problem before this error the program would always print your week was average nothing much happened and the other 2 variables that could of happened didn't
this is all in python
from random import randint
import time
money = 2000
week = 0
def stockmarket():
global money
global week
stock = int(randint(1,50))
fight_random = int(randint(1,4))
fight = int(randint(1,100))
gain_lose = int(randint(1,2))
win_lose_var = int(randint(1,30))
luck = int(0)
if money > 10000 :
print ("""congratulations you beat the game by earning 10,000
now that you have so much money you can go back to your life as a hip hop artist """)
time.sleep(4)
print("it took you ",week,"weeks's to compleate the game")
print("can you do it faster next time")
else:
print(" you have gained lots of money",money,"")
print("you must now invest it all the stock market")
human_stock = int(input("please pick a number between 1-100 not that it matters as the markets are rigged: "))
#need to make the user number matter
change1 = int(stock-40+luck)
change2 = float (change1/100)
change3 = float (1-change2)
money = money * change3
week = week+1
print ("you have" , money,"")
week = week +1
#THIS IS WHERE THE PROBLEM STARTS!
if fight == 3:
print("bad luck")
fight_run = str(input("""late at night you get approched by a bunch of bad, bad people. they attempt to mugg you but you see there is a chance to run away but you could fight
them and gain lots of money! do you fight or run"""))
if fight_run == "run":
print("you fled the scene but left some money behind which has been stolen.")
money *=.8
print(" ",money," ")
stockmarket()
if fight_run == "fight" :
print ("you chose to fight the oncoming enemys!")
if fight < 0 or fight > 11:
print("you where over powered by your enemys and died")
time.sleep(5)
quit()
elif fight <10 and fight >80 :
win_lose = int(input("the fight is close and you are both weak. /n please pick and number between 1 and 30 for a chance to gain money!"))
elif gain_lose == 1:
print("you deafeated your attacckers and take there money (its not a crime if no one saw)")
money_fight_win = (win_lose/100)+ 1
money = money * money_fight_win
print ("",money,"")
elif gain_lose == 2 :
print ("your attacker won and they took your money luckly you hide some just before the fight ")
money_fight_lose = (win_lose/100)+ 1 - (winlose/50)
money = money * money_fight_lose
else :
print("you mortaliy wounded the atackers (cause ur dench m8) and took their money")
money = money *1.5
#loop
stockmarket()
if fight == 4:
print ("you found a lucky penny and added it to your penny collection")
luck = +1
elif fight == 1 or 2:
print("your week was average nothing much happened")
#loop
stockmarket()
#gets program to start
stockmarket()
What if the value of fight is 1?
Then if fight == 3 is false, so the creation of the variable fight_run is skipped, so the variable fight_run doesn't exist. Then you are testing if fight_run == "run" and you are being told fight_run doesn't exist.
I think what you want to do is to indent the code:
if fight_run == "run":
print("you fled the scene but left some money behind which has been stolen.")
money *=.8
print(" ",money," ")
stockmarket()
if fight_run == "fight" :
print ("you chose to fight the oncoming enemys!")
So that it is part of the if fight == 3 block.
Instead of a long sequence of 'if's, I would also look at using elif and else and maybe putting the input in a loop. What if I typed "pee my pants" instead of "run" or "fight"?
Your immediate problem is indentation level. So, if fight != 3, then fight_run is never declared or set. So when you check fight_run in the next if statement there is a chance that it might not exist. Fix your indentation so it reads.
if fight == 3:
print("bad luck")
fight_run = str(input("""late at night you get approched by a bunch of bad, bad people. they attempt to mugg you but you see there is a chance to run away but you could fight them and gain lots of money! do you fight or run"""))
if fight_run == "run":
print("you fled the scene but left some money behind which has been stolen.")
money *=.8
print(" ",money," ")
stockmarket()
if fight_run == "fight" :
print ("you chose to fight the oncoming enemys!")
This way, if fight == 3, then the player is approached, then depending on the player choice he can fight or run. Addressing this will get you to your next error, your code has a bunch of issues, including some more indentation level issues like this one.
Regarding the other issue you mentioned, when you do elif fight == 1 or 2:, that will always be true because testing 2 as a boolean will always be true. This would need to be elif fight == 1 or fight == 2:.
Also, as Robert said in his answer, you have several fall through situations here where the user can input an instruction that will not match any checks. You should always verify that you the instruction cannot fall through and do nothing.