Is there a way to make my code repeat after a "death" in my text based game without a systemexit.exit()?
I have tried to search loops but nothing, I have looked at other games online, and I have searched this website for anything that can help
if option==1:
print('\nyou break the front bericade but as you walk in you see a laser streatching across the door frame a little too late, you died')
thisdict["death"] = True
print('\nyou died')
SystemExit.exit()
I want it to just say you died then start you at the beginning and say so, but a system exit doesn't do that very well.
Use a loop, prepare your games state dictionary and call your game-function.
When you die, return out of it, ask for continue and create a "new" game state dict:
def game(starter):
# do stuff
lr = input(f"Hello {starter['name']} - nothing to see but go Left or Right? [L,R]: ").lower()
if lr == "left":
return # doing anything is futile, you die anyhow
else:
return # doing anything is futile, you die anyhow
def main():
state = {"name": "someone"}
while True:
game(state)
if not input("You are dead - Play again? [y,n]").lower() == "y":
break
# create new games state dict (just altering the name here)
state["name"] += "_again"
print("bye")
main()
Output:
Hello someone - nothing to see but go Left or Right? [L,R]: l
You are dead - Play again? [y,n] y
Hello someone_again - nothing to see but go Left or Right? [L,R]: r
You are dead - Play again? [y,n] y
Hello someone_again_again - nothing to see but go Left or Right? [L,R]: nothing
You are dead - Play again? [y,n] n
bye
Related
I'm creating a text based adventure game and when the user's health gets to 0, I ask them if they want to restart the game. This works fine - however, I am duplicating my code a lot inside this while loop and want to know how to create a function which I can call to restart the game.
This is the code I use to restart:
if health <= 0:
print('You died. Do you want to restart? (y/n)')
ans = input().lower()
if ans == 'y':
continue
else:
break
There are a lot of ways you could do this, but this is one.
The following function will return True if the user enters 'yes', and False otherwise:
def continue_prompt():
typewriter('You now have 0 health and lose the game.')
print('\nDo you want to restart? (yes/no)')
return input().lower() == 'yes':
The below code will short circuit if health isn't 0, so the function will only be called in the event that the character has died. Then it will continue or break depending on the return value of continue_prompt.
if health <= 0 and continue_prompt():
continue
else:
break
You could also customize the prompt by having continue_prompt accept one or more arguments, if you wanted it to say different things for different causes of death, for instance.
You could use a custom exception and raise it when healths is 0. Then it's possible to move all the health affecting to a reusable function that handles death. Just call the function to change health instead of adding or subtracting
Define the exception:
class DeceaseException(Exception):
pass
And a function for handling health
def affect_health(gain):
global health
health += gain
if health <= 0:
raise DeceaseException
Wherever the health is affected you put for example:
# health decreases
affect_health(-10)
And in main function:
while True:
try:
# main game code
except DeceaseException:
print('You died. Do you want to restart? (y/n)')
ans = input().lower()
if ans == 'y':
continue
else:
break
I'm assuming this is just sitting inside of a while loop?
If so, one option could be
if not health:
typewriter('You now have 0 health and lose the game.')
restart = input('\nDo you want to restart? (yes/no)')
if restart.lower() == 'yes':
continue
In my text-adventure game, when I have
Would You like To Play (yes/no)yes
Ah! You are being chased by something! You need to go fast!
Should you take the bike or the skateboard (bike/skateboard)skateboard
Ah! You are being chased by something! You need to go fast!
Should you take the bike or the skateboard (bike/skateboard)
This means when I choose skateboard once, the question repeats, but if I chose bike, it goes on normally. This is the code:
def chooseAnswer():
answer=''
while answer.lower().strip() !='yes' and answer.lower().strip() !='no':
answer = input('Would You like To Play (yes/no)')
return answer
def chooseAnswer1():
answer1=''
while answer1.lower().strip() !='bike' and answer1.lower().strip() !='skateboard':
answer1= input('''Ah! You are being chased by something! You need to go fast!\nShould you take the bike or the skateboard (bike/skateboard)''')
return answer1
#Branches off 1 if choose Bike
def chooseAnswer11():
answer11=''
while answer11.lower().strip() !='right' and answer11.lower().strip() != 'left':
answer11= input('''You see two paths. Quickly, you have to decide which path to go on! The left one is dark and looks like it goes down a cave. The right one goes up a hill and into sunlight.(left/right)''')
return answer11
#Branches Off 1 if choose skateboard
def chooseAnswer12():
answer12=''
while answer12.lower().strip() !='sleep' and answer12.lower().strip() != 'awake':
answer12= input('''Quickly you hop on your skateboard, heading for woods.\nYou settle for the night in the woods.\nYou see the mysterious thing that is search for you.\nDo you sleep or stay awake?(awake/sleep)''')
return answer12
if chooseAnswer()=='yes':
if chooseAnswer1()=='bike':
if chooseAnswer11()=='right':
if chooseAnswer111()=='TBD':
print('TBD')
elif chooseAnswer112()=='TBD':
print('TBD')
elif chooseAnswer11=='left':
if chooseAnswer121()=='TBD':
print('TBD')
elif chooseAnswer122()=='TBD':
print('TBD')
elif chooseAnswer1()=='skateboard':
if chooseAnswer12()=='awake':
Anyone see why the input prompt is repeating twice?
The issue is being caused by calling the chooseAnswer1 function in your conditionals.
if chooseAnswer()=='yes':
# First call of chooseAnswer1
if chooseAnswer1()=='bike':
...Code Removed for Readability...
# second call of chooseAnswer1
elif chooseAnswer1()=='skateboard':
if chooseAnswer12()=='awake':
To fix this you'll want to assign the function call to a variable and then compare the object it returns to that variable in your conditional. You'll likely want to do this for all functions throughout your program:
# Single call of chooseAnswer
answer0 = chooseAnswer()
if answer0 == 'yes':
# Single call of chooseAnswer1
answer1 = chooseAnswer1()
if answer1 == 'bike':
...Code Removed for Readability...
# Since the variable is assigned to the returned object,
# the function is not called again in the elif condition.
elif answer1 == 'skateboard':
answer12 = chooseAnswer12()
if answer12 == 'awake':
Also Python 3.8's new walrus := operator may also be useful here, but I'm still using 3.7 so I'm going to leave it to someone else to provide code examples on how to use it in this situation.
Edit: OP said in a comment to my answer:
So I ran into another problem with this. I assigned all the functions variables, so when I think it goes in order I put the variables in. What I'm saying is when the first question pops up, it answers it as though I said yes and even though I say skateboard, it gives me the bike path.
My response is too long to post into a comment due to how long the url is for this python tutor link, but I recommend they compare their placement of their function calls to where I placed them in my example:
answer0 = chooseAnswer()
if answer0 == 'yes':
answer1 = chooseAnswer1()
if answer1 == 'bike':
answer11 = chooseAnswer11()
if answer11 == 'right':
print("right path")
elif answer11 == 'left':
print("left path")
elif answer1 == 'skateboard':
answer12 = chooseAnswer12()
if answer12 == 'sleep':
print("sleep path")
elif answer12 == 'awake':
print("awake path")
The key detail here is placement of the function calls.
I'm currently working on a text based game for a school project. I keep getting an invalid syntax error for the part that says 'reply'. Would you know why this may be? I've used this method a lot throughout the game and this is the first time i'm getting this error.
print("You decide it's time to look for a way out of this place. You consider travelling upstream to investigate where the wallet came from. You also remember being told that all rivers will eventually lead to a town or village.")
direction = input("Do you travel a)upstream or b)downstream? >")
if direction == "upstream" or direction == "Upstream" or direction == "Up" or direction == "up" or direction == "travel upstream" or direction == "Travel upstream":
print("You travel upstream")
elif direction == "downstream" or direction == "Downstream" or direction == "Down" or direction == "down" or direction == "travel downstream" or direction == "Travel Downstream":
print("You travel downstream. You walk for hours but the river does not lead anywhere. It gets dark and you can no longer find your way. You decide to rest until morning.")
print("You are suddenly woken from your sleep by a familiar voice. It's your", spouse+"!")
print(spouse_name.upper()+":", '"'+name_f+"!?",'What are you doing here?'
reply = input("Enter 1 for 'What are you doing here??' Enter 2 for 'I don't know, I just woke up here' >")
if reply == '1':
print(name_f.upper()+':',"What are you doing here??")
print(name_f.upper()+':',"I
elif reply == '2':
print(name_f.upper()+':',"I don't know, I just woke up here")
print(name_f.upper()+':',"I don't remember anything, I don't remember how I got here"
print(spouse_name.upper()+":", "How are you still alive?"
print(name_f.upper()=':', spouse_name+',','what are you talking about??')
print("before you have time to realise what's going on,", spouse,"pulls out a gun and shoots you in the head")
print("GAME OVER")
In this part of the code:
print(name_f.upper()+':',"I
elif reply == '2':
You aren't ending your print statement or your string, unfinished work I suppose.
Therefore, the rest of the code is treated as a string, the string has no end and the print statement has no closing parentheses.
Programmers make these mistakes all the time but as you get more and more experienced you need to catch these mistakes.
At this line
print(name_f.upper()+':',"I
you should enclose the string in two double quotes and then close with a final parenthesis:
print(name_f.upper()+':',"I")
I have been working on a text-based adventure game. I've revised it a few times and can't seem to get the outcome I want, when I attempt to create EVENTS rather than simply relying on an abundance of PRINT strings. Whenever I choose the option I want (door 1 in this case), then the following options, the input is unresponsive or gives me an error. Below is a portion of the code for door 1. A little clarity would be appreciated!
def main():
import sys
from colorama import init
init()
init(autoreset=True)
from colorama import Fore, Back, Style
def run_event(event):
text, choices = event
text_lines = text.split("\n")
for line in text_lines:
print(Style.BRIGHT + line)
print()
choices = choices.strip()
choices_lines = choices.split("\n")
for num, line in enumerate(choices_lines):
print(Fore.GREEN + Style.BRIGHT + str(num + 1) + ". " + line)
print()
return colored_input()
def colored_input():
return input(Fore.YELLOW + Style.BRIGHT + "> ")
print ("")
print ("")
print (" WELCOME TO THE MAZE ")
print ("")
print ("")
print ("You have found yourself stuck within a dark room, inside this room are 5 doors.. Your only way out..")
print ("")
print ("Do you want to enter door 1,2,3,4, or 5?")
print ("")
EVENT_DOOR1 = ("""
Theres an alien eating what appears to be a human arm, though its so damaged it's hard to be sure. There is a knife next to the alien.
what do you want to do?
""","""
Go for the knife
Attack alien before it notices you
""")
EVENT_ALIEN = ("""
You approach the knife slowly, While the alien is distracted. You finally reach the knife, but as you look up, the alien stares back at you.
You make a move to stab the alien, but he is too quick. With one swift motion, the alien thrusts you into the air.
You land hard, as the alien makes it's way towards you again. What should you do?
""", """
Accept defeat?
Last ditch effort?
""")
EVENT_ALIEN2 = ("""
You catch the alien off-guard. He stumbled and hisses in your direction. You scream in terror before he grabs the knife, and punctures your throat as he rips off your limbs.")
You died.. GAME OVER.. Mistakes can't be made this soon.. OUCH
""")
door = colored_input()
if door == "1":
run_event(EVENT_DOOR1)
alien = colored_input()
if alien == "1":
run_event(EVENT_ALIEN)
elif alien == "2":
run_event(EVENT_ALIEN2)
restart=input("Start over? Yes or No? ").lower()
if restart == "yes":
sys.stderr.write("\x1b[2J\x1b[H")
main()
else:
exit()
main()
You run_event function unnecessarily makes another call to colored_input() when it returns, causing the unresponsiveness as the script waits for another input. Remove the return colored_input() line and your code would work.
Also note that you should add a comma to the single-item tuple assigned to EVENT_ALIEN2; otherwise it would be evaluated as a string:
EVENT_ALIEN2 = ("""
You catch the alien off-guard. He stumbled and hisses in your direction. You scream in terror before he grabs the knife, and punctures your throat as he rips off your limbs.")
You died.. GAME OVER.. Mistakes can't be made this soon.. OUCH
""",)
I'm working on a text based adventure game in python. Nothing super fancy. I want to have a lever in 2 different rooms unlock a gate in a third room. Both levers need to be pulled in order for the gate to be unlocked.
here are the two rooms with the levers.
def SnakeRoom():
choice = raw_input("> ")
elif "snake" in choice:
FirstRoom.SnakeLever = True
print "As you pull the lever... You hear something click down the hall behind you."
SnakeRoom()
elif "back" in choice:
FirstRoom()
else:
dead("Arrows shoot out from the walls. You don't make it.")
def WolfRoom():
choice = raw_input("> ")
elif "wolf" in choice:
FirstRoom.WolfLever = True
print "As you pull the lever... You hear something click down the hall behind you."
WolfRoom()
elif "back" in choice:
FirstRoom()
else:
dead("Arrows shoot out from the walls. You don't make it.")
Here is the room with the gate.
def FirstRoom():
Lever = WolfLever and SnakeLever
choice = raw_input("> ")
if "straight" in choice and Lever != True:
print "You see a large gate in front of you. The gate is locked, there doesn't seem to be any way to open it."
FirstRoom()
elif "straight" in choice and Lever == True:
SecondRoom()
elif "left" in choice:
WolfRoom()
elif "right" in choice:
SnakeRoom()
elif "lever" in choice:
print "WolfLever: %s" % WolfLever
print "SnakeLever: %s" % SnakeLever
print "Lever: %s" % Lever
FirstRoom()
I shortened the code so you don't have to read through all the unnecessary stuff.
My biggest problem is I'm not super familiar with the Python language yet, so I'm not sure how to word everything to find the answers I'm looking for.
edit: Instead of FirstRoom.WolfLever I also tried just using WolfLever, in the body of my code, above Start() I have:
WolfLever
SnakeLever
Lever = WolfLever and SnakeLever
But my functions weren't updating these values. So I tried the FirstRoom. approach.
Credit to #Anthony and the following link: Using global variables in a function other than the one that created them
Globals definitely were the answer (With the exception of using classes). Here's what my WolfRoom() and SnakeRoom() functions look like now:
def WolfRoom():
global WolfLever
choice = raw_input("> ")
elif "wolf" in choice:
WolfLever = True
print "As you pull the lever... You hear something click down the hall behind you."
WolfRoom()
For FirstRoom() I added
global Lever
to the beginning of the function and right before Start() I have
WolfLever = False
SnakeLever = False
this way I have no errors or warnings (Was getting syntax warnings for assigning a value to my levers before declaring them as global) and everything works perfectly.