Sorry for the long code, but I felt that it was important that I include what I was trying to accomplish. I am a beginner with Python and programming in general and I was trying to make a simple text-based adventure game. The game was working good at first until I added the encounter with the bees. I ran the program and I chose to run from the bear, so my hp should be at 40, which was displayed. However, when I chose to swat the bees, my hp should then be at 0 because 40(my current hp)-40=0. My hp is however is displayed at 60, as if the bear encounter never happened. Is there some way I can fix this or is this a limitation in Python?
from sys import exit
from time import sleep
import time
#Hp at start of game:
hp = 100
#The prompt for inputs
prompt = "> "
#Bear encounter
def bear(hp):
choice = raw_input("> ")
if "stand" in choice:
print "The bear walks off, and you continue on your way"
elif "run" in choice:
print "..."
time.sleep(2)
print "The bear chases you and your face gets mauled."
print "You barely make it out alive, however you have sustained serious damage"
hp = hp-60
currenthp(hp)
elif "agressive" in choice:
print "..."
time.sleep(2)
print "The bear sees you as a threat and attacks you."
print "The bear nearly kills you and you are almost dead"
hp = hp-90
currenthp(hp)
else:
print "Well do something!"
bear(hp)
#Bee encounter
def bee(hp):
choice = raw_input(prompt)
if "run" in choice:
print "..."
sleep(2)
print "The bee flies away and you continue on your way."
currenthp(hp)
elif "swat" in choice:
print "..."
sleep(1)
print "You succesfully kill the bee. Good Job!"
sleep(1)
print "Wait a minute"
sleep(2)
print "The bee you killed gives off pheremones, now there are hundreds of bees chasing you."
print "The bees do some serious damage."
hp = hp-40
sleep(1)
currenthp(hp)
else:
print "Well, do something."
bee(hp)
#Function to display the current hp of the current player
def currenthp(hp):
if hp < 100:
print "Your hp is now at %d" % hp
elif hp <= 0:
dead()
else:
print "You are still healthy, good job!"
#Called when player dies
def dead():
print "You sustained too much damage, and as a result have died."
time.sleep(3)
print "GAME OVER!"
print "Would you like to play again?"
choice = raw_input("> ")
if "y" in choice:
start_game()
else:
exit(0)
#Called to Start the Game, useful for restarting the program
def start_game():
print "Welcome to Survival 101"
#START OF GAME
start_game()
print "You start your regular trail."
print "It will be just a little different this time though ;)"
time.sleep(3)
print "You are walking along when suddenly."
time.sleep(1)
print "..."
time.sleep(2)
#Start of first encounter
print "Wild bear appears!."
print "What do you do?"
print "Stand your ground, Run away, be agressive in an attempt to scare the bear"
#first encounter
bear(hp)
#Start of second encounter
print "You continue walking and see a killer bee approaching you"
print "What do you do"
print "run away, swat the bee away"
bee(hp)
You pass hp to functions and inside a function you are updating it, but you are not getting the updated value hp back from the function. You should specify return hp inside the function to return the updated value, and you can store (or update) the updated value in the function call - e.g., hp = bear(hp).
Related
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 Python and I'm creating a multiple path game but whenever I open it up in the .py it closes instantly! So if anyone could help me out here it would be much apprecitated!
Heres my code:
def Roadto1stWin():
print("You have just joined the world of CounterStrike")
print("3 Hours later")
print("You have now got to rank 2 so you can finally play comp")
print("You find yourself playing a game of Comp on the map mirage")
print("Now that you have got to pistol round where do you go?")
print("Mid? B? or A?")
a = input("Type mid, b or a then hit 'Enter'.").lower()
if a ==("mid"):
print("Okay nice you are going Mid")
print("Where should you watch from?")
print("Connector? Short? or Window?")
b = input("Type connector, short or window Then hit 'Enter'.").lower()
if b ==("connector"):
print ("They rush B and kill the rest of your team and you lose the round")
print ("Now your team are questioning your mid ability!")
print ("Do you fight back and try to win the argument? or do you just carry on playing")
c = input ("Type fight or play then hit 'Enter'.").lower()
if c ==("fight"):
print ("Your TeamMates end up not liking you and kick you")
elif c ==("play"):
print ("Another one of your teammates goes mid instead of you!")
print ("You have decided to go B since there is only 1 at b")
print ("Now your Teammate dies instantly at mid")
print ("The enemy team win this round as well")
print ("Now do you complain or play")
d = input ("Type complain or play then hit 'Enter'.").lower()
if d == ("play"):
print ("Your team are mad at you for no voting to kick him so you get kicked")
print ("The End")
elif d == ("complain"):
print ("Nice your team stand up with you and you kick the player")
print ("Now that the player is gone your team have good chemistry")
print ("You end up winning the game well done!")
if b == ("short"):
print ("You die instantly and since your team are full of Russians you get kicked")
print ("The End")
if b == ("window"):
print ("You kill 3 of the enemies rushing mid and your teammates praise you!")
print ("Now a second teammate has pushed short killing the player you were gonna kill!")
print ("What do you do?")
print ("argue at him or leave it alone")
e = input ("Type argue or leave it then hit 'Enter'.").lower()
if e == ("argue"):
print ("Your team are toxic and don't like your attitude so they kick you")
print ("The end")
elif e == ("leave it"):
print ("You get on well with each other and win the game")
Roadto1stWin()
This is the code!
Thank you for your replies
I am teaching myself python in my spare time. I've only been at it for a couple days so for practice I've been messing around with various raw_input lines. Currently I am trying to make a short text-venture for a friend to try out. I have hit a block, part of it asks the user if they want to enter a village. If they choose to enter, everything works just fine, but if they choose not to, I need it to jump down past all of the dialogue and inputs that happen while inside the village. How do I make it jump down to an input further down the page?
it's very basic but here:
name = raw_input("What is your name adventurer? ")
where = raw_input("You are in a magical forest, you can go North or East, which
way do you go?")
if where.lower() == "north":
troll = raw_input("You encounter a troll, what do you do? Attack or flee? ")
else:
print("You encounter a dragon, you are dead, GAME OVER")
if troll.lower() == "attack":
print ("You have no weapon, that was a bad choice, you are dead, GAME OVER")
else:
flee = raw_input("You flee further North, you encounter a village, do you
enter or continue? ")
if flee.lower() == "enter":
army = raw_input("As you enter the village, a knight hands you a sword,
assuming you are there to join the army. Join him or leave the village? ")
else:
print ("You ignore the village and continue down the road.") #jump from here
if army.lower() == "join":
print ("You head off to war and are killed almost instantly because you are an
untrained fool")
else:
print ("You are kicked out of the village")
dark = raw_input("It is getting dark, do you continue or seek shelter") #to here
if dark.lower() == "continue":
print ("You are attacked by vampires and killed, GAME OVER")
else:
caves = raw_input("You find two caves, do you pick cave one which is pitch
black, or two which has light coming from it? ")
if caves.lower() == "one":
print ("You enter the cave, light a small fire, and sleep for the night.")
else:
print ("You enter the cave, there are bandits inside, you are murdered, GAME OVER")
I want to jump down to dark after the first bold line. If anything else is spotted that could be fixed or made better, please do speak up. All criticism is welcome.
change this block:
if flee.lower() == "enter":
army = raw_input("As you enter the village, a knight hands you a sword,
assuming you are there to join the army. Join him or leave the village? ")
else:
print ("You ignore the village and continue down the road.") #jump from here
if army.lower() == "join":
print ("You head off to war and are killed almost instantly because you are an
untrained fool")
else:
print ("You are kicked out of the village")
dark = raw_input("It is getting dark, do you continue or seek shelter")
into this block:
if flee.lower() == "enter":
army = raw_input("As you enter the village, a knight hands you a sword,
assuming you are there to join the army. Join him or leave the village? ")
if army.lower() == "join":
print ("You head off to war and are killed almost instantly because you are an
untrained fool")
else:
print ("You are kicked out of the village")
else:
print ("You ignore the village and continue down the road.")
dark = raw_input("It is getting dark, do you continue or seek shelter")
This moves the army input to inside of the enter block so that it will only execute if it goes inside that statement.
A few notes:
you probably want to put this all inside a main() function and call return whenever you die so that it wont continue. Another choice, if you dont want to use a function, is to put everything inside a try block and call raise if you die, then handle death with your except block. You say you are a beginner so you might not have learned this stuff yet but it's definitely something to look into
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.
from sys import exit
haskey = 0
# start function
def start():
print "You wake up in an empty room, feels like you've been here for days. You can't remember anything from your past. All there is in the room is a digital clock. It says 3:26am, May 5, 2012. Get out of the room?"
next = raw_input("> ").lower()
if "yes" in next:
lobby()
elif "no" in next:
print "We insist"
else:
print "Try again."
def lobby():
while True:
print "You arrived at a lobby, all you can see are four doors. Which door to enter? (first, second, third, fourth)?"
next = raw_input("> ").lower()
if "first" in next:
firstdoor()
elif "second" in next:
seconddoor()
elif "third" in next:
thirddoor()
elif "fourth" in next:
fourthdoor()
else:
print "Are you dumb and you can't even follow instructions?"
def firstdoor():
print "You arrive at another empty room, examine further or exit?"
choice = raw_input("> ").lower()
if "examine" in choice:
print "A trap door opened, you fell in it and died."
exit()
elif "exit" in choice:
lobby()
else:
print "Are you dumb and you can't even follow instructions?"
def seconddoor():
print "You arrive at the study room, examine room or exit?"
choice = raw_input("> ").lower()
if "examine" in choice:
print "There is a note on the table, read it?"
secondchoice = raw_input("> ").lower()
if "yes" in secondchoice:
note()
elif "no" in secondchoice:
print "Returning to lobby."
lobby()
def note():
print """Security Log (040412): A man from the city travelling along the highway loses control of his vehicle and fell to the cliff. He was able to jump and grab a hold to the bushes growing at the side of the cliff. We were able to rescue him, but as soon as we secured him to the ground he violently reacted to our help and fainted. A few minutes later he was out of control, like he was possessed by a demon. We had no choice but to sedate him and keep him locked in our prison until authorities from the city arrive and examine him. The key to his cell is in the vault in the vault room. The keycode changes depending on the current date.
"""
print "Returning to lobby."
lobby()
def thirddoor():
if haskey == 0:
print "Door is locked, you need a key to continue."
print "%d" % haskey
lobby()
elif haskey == 1:
exit()
def exit():
print "You are now free!"
print "To be continued.."
def fourthdoor():
print "There is a vault inside the room. Use vault?"
usevault = raw_input("> ")
if "yes" in usevault:
vault()
else:
print "Returning to lobby.."
lobby()
def vault():
while True:
print "There is a security code for this door. Enter code:"
code = raw_input("> ")
if "05042012" in code:
print "Correct!"
print "Returning to lobby.."
haskey = int(1)
print "%d" % haskey
lobby()
else:
print "Code Error! Try again?"
start()
I have this mini-text game for a tutorial on python and I'm using the fourthdoor/vault function to ask the player the code and if entered correctly it changes the value of a variable to be used as a key to open the third door. The problem is even if the value of the variable is changed when the vault code is given correctly, I still can't open the door.
Can anyone help me?
When python encounters haskey = int(1) inside of vault, it creates a new local variable called haskey that you can only see inside of vault. You need to tell python that when it sees haskey in that function, you mean the global haskey that you declare at the top of the file. You can do this by adding global haskey to the beginning of vault. ie:
def vault():
global haskey
while True:
print "There is a security code for this door. Enter code:"
code = raw_input("> ")
...