I'm trying to make a game where you go through a maze and try to escape from a voice, but everytime the player says the wrong answer to one of the questions it says "Game Over" but then carries on where it kept off, I've tried a lot of things and researched, but I can't seem to figure it out, I'm only a beginner
`
import time
import os
print ("Your adventure starts as a young boy, running away from home becuase you're a rebel")
time.sleep(2)
print ("You find the famous labyrinth, do you go in?")
time.sleep(2)
answer = input("Make your choice, Yes OR No")
time.sleep(2)
print ("The answer",answer ,"got you stuck in a hole")
time.sleep(2)
print ("But you find a secret passage")
answer = input("Do you go through the door, Yes or No?")
if answer == "No":
time.sleep(2)
print ("Game Over.")
elif answer == "Yes":
time.sleep(2)
print("You hear a strange voice")
time.sleep(2)
answer = input("What do you say to the Voice, Hello or Who are you?")
if answer == "Hello":
print ("Hello")
elif answer == "Who are you?":
print ("Im your worst nightmare")
time.sleep(2)
print("You try and escape the labyrinth and turn a large gate with a gnome on the over end")
answer = input("Do you open the gate, Yes Or No?")
if answer == "Yes":
time.sleep(3)
print ("Game Over, you get brutally killed by a gnome, good job")
os._exit(0)
elif answer == "No":
time.sleep(3)
print ("You go the other way and see a light at the end of the tunnel")
answer = input("You see your family outside crying and waiting for you, do you go with them?")
if answer == "Yes":
print("You have a nice ending and you're sorry you ran away")
print("You have been graded: ")
elif answer == "No":
print("God smites you for being stupid.")
os._exit(0)`
take this block, for example
print ("But you find a secret passage")
answer = input("Do you go through the door, Yes or No?")
if answer == "No":
time.sleep(2)
print ("Game Over.")
elif answer == "Yes":
time.sleep(2)
print("You hear a strange voice")
time.sleep(2)
# continuation
if the user enters "No" it will print "Game Over" - which I assume is correct. However, control flow in the program continues past the if/else block. What you need to do is exit the program using something like sys.exit() or make sure your control flow only has paths forward if it should i.e. wrapping what happens next in the truthy part of the if/else block
if answer == "No":
time.sleep(2)
print ("Game Over.")
elif answer == "Yes":
time.sleep(2)
print("You hear a strange voice")
time.sleep(2)
# put continuation here
Related
About 3 days ago I started learning Python as a hobby.
Today I wanted to try to program a text adventure in Python.
When I tried to test the code I had an error, but I don't know why. Can someone please help me?
The code:
name = 'bot'
def intro():
print("On day you wake up but you don't remember anything, except your name.\n"
"You are in a unknown room. Right in front of you is a unlocked Computer.\n"
"\nWhat do you do?\n"
"\n1) Go to the computer.\n"
"2) Try to escape.\n"
"3) ")
anwser = input(">>> ")
if anwser.lower() == "1" or "go to the computer":
return computer()
elif anwser.lower() == "2" or "try to escape":
return escape()
intro()
def computer():
print("You go to the computer and there is a folder called" +name)
print("\nWhat do you do:\n"
""
"\n1) Open the folder.\n"
"2) Delete the folder\n"
"3) Lock the computer and try to escape.")
anwser = input(">>> ")
if anwser.lower() == "1" or "open the folder":
print("You open the folder an there a lot of dokuments.\n But you see a folder called \" Project Raspbrain \"")
elif anwser.lower() == "2" or "delete the folder":
print("You decide to delete the folder but you feel wired and fall on the ground.\n"
"You die!")
elif anwser.lower() == "3" or "lock the computer and try to escape":
escape()
def escape():
print("You see a door on your right side, you decide to go through it but there are two guards in front of you\n"
"What do you do?\n"
"\n1) Kill the guards"
"\n 2) Run")
anwser = input(">>>")
if anwser == "Kill the guards" or "1":
print("You try to kill the guards but don't have any weapons.\n Instead they kill you.\n You die")
elif anwser == "2" or "run":
print("You try to run but you stumble an fall on your head.\n You die!")
You need to move intro() to the end of this script, and your first line name = bot is very wired, I assume bot is a string and the code will look like below. The code will run well.
Remember that python is script language, it will run by order of your code, so in your scenario, you run intro() before the definition of computer(), and it will pop out not define error.
name = 'bot'
def intro():
print("On day you wake up but you don't remember anything, except your name.\n"
"You are in a unknown room. Right in front of you is a unlocked Computer.\n"
"\nWhat do you do?\n"
"\n1) Go to the computer.\n"
"2) Try to escape.\n"
"3) ")
anwser = input(">>> ")
if anwser.lower() == "1" or "go to the computer":
return computer()
elif anwser.lower() == "2" or "try to escape":
return escape()
def computer():
print("You go to the computer and there is a folder called" +name)
print("\nWhat do you do:\n"
""
"\n1) Open the folder.\n"
"2) Delete the folder\n"
"3) Lock the computer and try to escape.")
anwser = input(">>> ")
if anwser.lower() == "1" or "open the folder":
print("You open the folder an there a lot of dokuments.\n But you see a folder called \" Project Raspbrain \"")
elif anwser.lower() == "2" or "delete the folder":
print("You decide to delete the folder but you feel wired and fall on the ground.\n"
"You die!")
elif anwser.lower() == "3" or "lock the computer and try to escape":
escape()
def escape():
print("You see a door on your right side, you decide to go through it but there are two guards in front of you\n"
"What do you do?\n"
"\n1) Kill the guards"
"\n 2) Run")
anwser = input(">>>")
if anwser == "Kill the guards" or "1":
print("You try to kill the guards but don't have any weapons.\n Instead they kill you.\n You die")
elif anwser == "2" or "run":
print("You try to run but you stumble an fall on your head.\n You die!")
intro()
Please clarify what is "bot"?. Is it a pre-defined variable or just a syntax error?
For the function error just move the intro function call to the bottom
def intro():
(…)
def computer():
(…)
def escape():
(…)
intro()
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 new to this website so please bear with my questioning problems on the website. I need some help to finish off this mini text-based game as homeowork of learning python the hard way book. This is the code I wrote. and I don't know the missing links and what I've done wrong. Help would be appreciated!
from sys import exit
def start():
print "You are in an old temple."
print "There is a door to your right and left or you can walk forwad."
print "Which one do you take?"
choice = raw_input("> ")
if choice == "left":
gold_room()
elif choice == "right":
trap_room()
elif choice == "forward":
monster_room()
else:
dead("you got caught by the ancient gods and you must be killed.")
start()
def monster_room():
print "you're in a room with a monster. what you gonna do?"
choice = raw_input("> ")
if "left" in choice:
print "you are going to the gold room"
gold_room()
elif "right" in choice:
print "you are going to the trap room"
trap_room()
else:
dead("couldnt understand what did you say so you are dead!")
def gold_room():
print "you chose the left room. now you are in a room with a pot of gold!"
print "you can take the pot."
print "or you can just rob the money in it."
print "or you go go to other rooms."
choice = raw_input("> ")
if choice == "take the pot":
print "you are a millionaire from now on!!!"
elif choice == "rob the money":
dead("you will never rest in piece!")
else choice == "another room":
monster_room()
def trap_room():
print "you are now in a trap room."
print "there is a hidden trap in this room."
print "be careful!"
print "you can go back to the monster room"
print "or you can find the trap"
choice = raw_input("> ")
if "find" in choice:
start()
elif "back" in choice:
gold_room()
def dead(why):
print why, "rekt!"
exit(0)
Ok, I've fixed it. Your code has several indentation mistakes, Python requires four spaces or one tab indentation after a def statement.
Another thing is, that you used else with a condition test (else choice == "another room":). That is wrong, it should be elif choice == "another room": or just else.
You also may have noticed, that I changed raw_input() to input(). This converts all inputs to strings (input() will interpret intergers as integers, lists as lists and so on...), and is also more secure.
The last thing is, you run your program (start()) before definign all called functions, this cannot work!
Your code (fixed):
from sys import exit
def start():
print("You are in an old temple.")
print("There is a door to your right and left or you can walk forwad.")
print("Which one do you take?")
choice = input("> ")
if choice == "left":
gold_room()
elif choice == "right":
trap_room()
elif choice == "forward":
monster_room()
else:
dead("you got caught by the ancient gods and you must be killed.")
def monster_room():
print("you're in a room with a monster. what you gonna do?")
choice = input("> ")
if "left" in choice:
print("you are going to the gold room")
gold_room()
elif "right" in choice:
print("you are going to the trap room")
trap_room()
else:
dead("couldn't understand what did you say so you are dead!")
def gold_room():
print("you chose the left room. now you are in a room with a pot of gold!")
print("you can take the pot.")
print("or you can just rob the money in it.")
print("or you go go to other rooms.")
choice = input("> ")
if choice == "take the pot":
print("you are a millionaire from now on!!!")
elif choice == "rob the money":
dead("you will never rest in piece!")
elif choice == "another room":
monster_room()
def trap_room():
print("you are now in a trap room.")
print("there is a hidden trap in this room.")
print("be careful!")
print("you can go back to the monster room")
print("or you can find the trap")
choice = input("> ")
if "find" in choice:
start()
elif "back" in choice:
gold_room()
def dead(why):
print(why, "rekt!")
exit(0)
start()
I would call the start() function at the end, after all the functions you defined. A usual way to write that is to write the following code at the end:
if __name__ == "__main__":
start()
This basically means that the programm runs the start() function at the end, if you're executing the file.
Furthermore you have to leave spaces after defining a function. You wrote:
def monster_room():
print "you're in a room with a monster. what you gonna do?"
but it should be:
def monster_room():
print "you're in a room with a monster. what you gonna do?"
If that didnt help, specify the problem
When the user chooses option 4 on hall(), it should run blue(), but when I try to run it I get an error saying that blue() is not defined. How do I fix this?
import time
import sys
name = input ("Name: ")
print ("Hello", (name), ", and welcome to my game that i made to learn python.")
print ("How to play the game, just type the number its not that hard.")
time.sleep(5)
def intro():
print ("You are in a room, to the south there is a torch on the wall and to the north there is a door.")
time.sleep(5)
print ("Your options are: ")
time.sleep(3)
print ("1. Do nothing")
print ("2. Go south and pick up the torch")
print ("3. Go north, open and go through the door")
print ("4. You decide to build an orphanage in the room, makes sense.")
choice = input(">>> ")
if choice == "1":
print("You decide to curl into a ball and go to sleep, you never wake up again. --GAME OVER--")
print("I guess you could try again if you must.")
time.sleep(5)
intro()
elif choice == "2":
print("You walk southwards towards the wall, grab the torch off the wall and hold it in your hands.")
print("You walk over towards the door and open it")
time.sleep(5)
elif choice == "3":
print("You walk over towards the door and open it, on the other side there is a dark corridor, you step forward and the door closes behind you. You get surrounded in darkness and die. --GAME OVER--")
print("I guess you could try again if you must.")
time.sleep(5)
intro()
elif choice == "4":
print("You can't build an orphanage in a room with nothing there idiot, you wasted your whole life attempting. --GAME OVER--")
print("I guess you could try again if you must.")
time.sleep(5)
intro()
else:
print("Type the correct number idiot")
intro()
intro()
def hall():
print ("As you open the door a strong gust of cold air comes through making the torch flicker")
time.sleep(3)
print ("You continue up the corridor with the torch illuminating your surroundings, you feel like your being watched")
time.sleep(3)
print ("You keep walking for what seems like hours and you finally come across a part where the corridor splits off into 3 different ones")
print ("What do you do?")
print ("1. Go north.")
print ("2. Go east.")
print ("3. Go back the way you came.")
print ("4. Go west.")
time.sleep(5)
hall()
choice = input(">>> ")
if choice == "1":
print("You head north but as soon as you do the ground under you crumbles and you fall. And die. --GAME OVER--")
print("I guess you could try again if you must.")
time.sleep(5)
hall()
elif choice == "2":
print("You go down the east corridor and get a glimpse of a dark red light before it disappears.")
print("You continue to walk")
time.sleep(5)
red()
elif choice == "3":
print("Well done, you just went back to the place you wanted to get out from, your legs are tired and your torch has gone out. idiot. --GAME OVER--")
print("I guess you could try again if you must.")
time.sleep(5)
hall()
elif choice == "4":
print("You go down the west corridor and get a glimpse of a dark blue light before it disappears.")
print("You continue to walk")
time.sleep(5)
blue()
else:
print("Type the correct number idiot")
time.sleep(5)
hall()
def red1():
print ("As you continue to walk down the corridor the air around you seems to head up more and more.")
time.sleep(3)
print ("You come around a little podium and on it is a piece of paper with the numbers 264 894 written on it")
time.sleep(3)
print ("You go to pick it up but it crumbles into dust and under the dust are the words blue carved into the podium")
time.sleep(3)
print ("you continue walking")
time.sleep(3)
print ("After a while you come across a shiny iron door with a keypad by the side on the keypad it spells the words red on it.")
time.sleep(3)
print ("You attempt to enter the correct code.")
red1()
code1 = input(">>> ")
if code1 == "362 682":
print ("The door slides open without making a noise, you step into the door and continue walking")
else:
print ("Incorrect code. Hint:RED")
print ("restarting...")
time.sleep(10)
intro()
def blue1():
print ("As you continue to walk down the corridor the air around you seems to get colder and colder more and more.")
time.sleep(3)
print ("You come around a little podium and on it is a piece of paper with the numbers 362 682 written on it")
time.sleep(3)
print ("You go to pick it up but it crumbles into dust and under the dust are the words red carved into the podium")
time.sleep(3)
print ("you continue walking")
time.sleep(3)
print ("After a while you come across a rusty iron door with a keypad by the side on the keypad it spells the words red on it.")
time.sleep(3)
print ("You attempt to enter the correct code.")
blue1()
code2 = input(">>> ")
if code2 == "264 894":
print ("The door slides open without making a noise, you step into the door and continue walking")
else:
print ("Incorrect code. Hint:BLUE")
print ("restarting...")
time.sleep(10)
intro()
nice story btw). anyway to the problem.
you call function blue() that is not defined in your code - there is no such function ). if you meant to call blue1() you will get an error and that's because
you first need to declare the function before using it
for example:
1.this will not work:
blue()
def blue(): ...
2. this will work:
def blue(): ...
blue()
any way for good practice its good to maintain a simple code structure, all functions above and the main is the last one that calls other function.
The reason you're getting an error is because there indeed is no function called blue() defined. It's blue1() in your code. I strongly suggest investing in a linter.
This is my first post on stackoverflow and I'm only asking because I truly am stuck. A good friend and I are trying to make a simple text based game(let's hear it for the 80's). It's my first day essentially with python and I've run into a problem. The player has a choice to pick up a dagger or to not. Later on I want this decision to come into play. Except I've no idea how to check and see what said player entered!
Here's my code
Note:It crashes in the state it's in right now mainly because of me stumbling around trying to get this problem fixed.
def start():
print("You wake up in a dank tunnel reeking of death and decomposition,")
print("you have no weapons to defend yourself with.")
time.sleep(1)
print("\n")
print("You head north and find yourself at a four way tunnel.")
print("\n")
print("Down the west tunnel, you hear sounds which could have only come")
print("from hell itself. With every sound uttered, your fear grows.")
time.sleep(1)
print("\n")
print("Down the north tunnel, there is a room with a glimmering object")
print("lying on the ground.")
time.sleep(1)
print("\n")
print("Down the East tunnel, there appears to have been a cave in.")
time.sleep(1)
print("\n")
print("The South tunnel is the way you just came. \n")
time.sleep(1)
while True:
r3 = input("Which way would you like to go?\n")
if r3 == "west" or r3 == "West":
print("The sounds are becoming Louder, do you continue or head back?")
while True:
w1 = input("")
if w1 == "continue" or w1 == "Continue" or w1 == "west":
print("You continue further on...")
time.sleep(2.5)
westtunnel()
elif w1 == "head back" or w1 == "Head Back" or w1 == "back" or w1 == "Back":
print("\n")
print("The voices congregate behind you. No way your going back that way!\n")
time.sleep(1)
westtunnel()
else:
print("\n")
print("You couldn't possibly do anything else.\n")
time.sleep(1)
print("Greater minds prevail and you continue westward...\n")
time.sleep(2)
westtunnel()
elif r3 == "north" or r3 == "North":
print("You find a rusty dagger on the floor, stained with blood.")
print("Do you want to pick up the dagger?")
print("1: Yes, that seems useful!")
print("2: No, I'm a bit of a pacifist you see.")
while True:
pd = input("")
if pd == "1":
print("You slowly picked up the dagger.")
number = int(pd)
break
else:
print("You left the dagger. All alone.")
number = int(pd)
break
print("You can go only go back the way you came.\n")
time.sleep(1)
print("You head back to the four way tunnel.")
elif r3 == "east" or r3 == "East":
print("\n")
print("You can not go that way, there are rocks there. We told you this.\n")
time.sleep(1)
print("You go back to the four way tunnel")
elif r3 == "south" or r3 == "South":
print("\n")
print("This is the room you awoke in, there is nothing of interest.\n")
time.sleep(1)
print("You head back to the four way tunnel")
else:
print("\n")
print("You run into a corner, you hurt yourself in confusion. \n")
time.sleep(1)
print("You stumble back to the four way.")
def ladder():
print("Do you have a dagger?!")
number = pd
if number == "1":
print("Good you have it!")
start()
input("")
else:
print("awh...no dagger for you...")
start()
input("")
if __name__ == '__main__':
menu()
Look into Python classes.
You probably want to create a Game State object that holds the results of decisions made in the course of the game. Then, later, when the results of those decisions matter, you check the state.
You will need to keep a reference to that game state object during your main game loop. However, keeping it in one object keeps all the state information organized, instead of keeping references to several disparate variables.