string = "Your NEW name is ALBY. You have 3 minutes to get to your shelter or you get RIPPED APART by gamma radiation and A MASSIVE FIREBALL. Do you RUN, SHELTER, or WAIT?"
for char in string:
print(char, end='')
time.sleep(.05)
print("")
time.sleep(5)
answer1 = input("What do you do?")
while True:
if answer1 == "RUN":
print("")
print ("You choose to RUN. Within minutes of running you see a massive
FIREBALL behind you, say your PRAYERS and DIE.")
print("")
time.sleep(5)
print("You Died! The creator of this game can't use 'While True'
statements and therefore you must restart.")
elif answer1 == "WAIT":
print("This is certainly not YOUR BEST IDEA. You WAIT for the bomb to drop
and DIE a hot death.")
print("")
time.sleep(5)
print("")
print("You Died! The creator of this game can't use 'While True' statements and therefore you must restart.")
elif answer1 == "SHELTER":
def slowprint(s):
for c in s + '\n':
sys.stdout.write(c)
sys.stdout.flush() # defeat buffering
time.sleep(random.random() * 0.1)
slowprint('Hello, world.')
Above is the code snippet, i have the typewriter effect going for a little text adventure. When I run the code all that happens is i get a blank loop, or the first letter of the line.
[EDIT: This isn't a duplicate of a flushing issue. I didn't want to flush slowprint i just needed to redefine it.]
Related
I'm very new to Python, and I'm just having a play with making some very simple little programs to get a feel for it, so probably best to keep any explanations really simple haha!
I'm currently making a little program that asks if you want to roll a dice, rolls it, gives you the answer and asks if you want to roll again.
The issue I'm having trouble figuring out is the following (copied from console):
What is your name: Nasicus
Greetings Nasicus!
Would you like to roll the dice? [Y/N]? : Y
Let's do this!
Rolling...
You rolled a 3!
Do you want to roll again? [Y/N]?: Y
Yahoo!
Would you like to roll the dice? [Y/N]? : N
Oh, Okay. Maybe next time.
Would you like to roll the dice? [Y/N]? : N
Oh, Okay. Maybe next time.
Process finished with exit code 0
As you can see, it prompts twice when you select N before it closes.
I'm probably missing something incredibly simple, so could anyone advise how I can either A. Stop it prompting twice or (preferably for the sake of simplicity) B. Stop it asking if You want to roll the dice after you have already selected Y to roll again, and just go straight from the Let's do this! line.
Here is my code, any pointers on how to keep things tidier/more pythonic always appreciated too! I appreciated the time.sleep() probably look a little messy, but I do like the way it paces things when I run it:
import random
import time
def diceroll():
while True:
diceyn = input ("Would you like to roll the dice? [Y/N]? : ")
if diceyn == "Y":
print ("Let's do this!")
time.sleep(0.5)
print ("Rolling...")
time.sleep(1)
rand = random.randint(1, 6)
print ('You rolled a ',rand,'!', sep='')
time.sleep(0.5)
again = str(input("Do you want to roll again? [Y/N]?: "))
if again == "Y":
print ('Yahoo!')
time.sleep(0.5)
diceroll()
else:
time.sleep(0.3)
print ('Okay, bye!')
break
elif diceyn == "N":
print ("Oh, Okay. Maybe next time.")
break
input_name = input ("What is your name: ")
print ("Greetings ",input_name,"!", sep='')
time.sleep(1)
diceroll()
Thank you for your time, and I look forward to learning more :D
The problem is in this section of code:
if again == "Y":
print ('Yahoo!')
time.sleep(0.5)
diceroll()
You're recursively calling the diceroll() function, so when that recursive call finally finishes, the iteration of the current call still continues.
You're already in a while True loop, so you don't even need the recursive call. Just take it out, and let the loop continue.
You are calling diceroll recursively.
if again == "Y":
print ('Yahoo!')
time.sleep(0.5)
diceroll()
So you call diceroll() and then whenever the user is asked
Do you want to roll again
You call diceroll() again.
Here is what is happening. You have a top level diceroll().
diceroll()
Then you have another diceroll() under it like this:
diceroll()
-- diceroll()
And then you have yet another diceroll() inside it.
diceroll()
-- diceroll()
---- diceroll()
When you call the break statement, all you are doing is breaking out of that inner diceroll() loop, not the loop where you called it.
A break in the third row sends you to
diceroll()
-- diceroll()
I would just break out your actual rolling into a separate function in your diceroll() function, that way you won't confuse the paths.
import random
import time
def diceroll():
def rollIt():
time.sleep(0.5)
print ("Rolling...")
time.sleep(1)
rand = random.randint(1, 6)
print ('You rolled a ',rand,'!', sep='')
time.sleep(0.5)
while True:
diceyn = input ("Would you like to roll the dice? [Y/N]? : ")
if diceyn == "Y":
print ("Let's do this!")
rollIt()
again = str(input("Do you want to roll again? [Y/N]?: "))
if again == "Y":
print ('Yahoo!')
rollIt()
else:
time.sleep(0.3)
print ('Okay, bye!')
break
elif diceyn == "N":
print ("Oh, Okay. Maybe next time.")
break
input_name = input ("What is your name: ")
print ("Greetings ",input_name,"!", sep='')
time.sleep(1)
diceroll()
Here is the Object Oriented approach:
import random
import time
class Rolling_Dice_Game () :
def startup (self) :
prompt = ("Would you like to roll the dice? [Y/N]? : ")
if self.query_user (prompt) == 'Y' :
self.run_the_game ()
return True
else : return False
def run_the_game (self) :
print ("Let's do this")
print ('Rolling...')
time.sleep (1)
rand = random.randint (1, 6)
print ('You rolled a ', rand, '!')
time.sleep (0.5)
return True
def query_user (self, prompt) :
return input (prompt) [0].upper ()
def continue_the_game (self) :
prompt = ("Do you want to roll again? [Y/N]?: ")
if self.query_user (prompt) != 'Y' :
print ('Oh, Okay. Maybe next time.')
return False
else : return True
my_dice = Rolling_Dice_Game ()
if my_dice.startup () == True :
while my_dice.continue_the_game () == True :
my_dice.run_the_game ()
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 made the beginning of a basic text adventure game, and I want it to loop whenever you die, but any examples of code I see aren't working, and thorugh research i still cant find something that could work.
print("A tale of time version 0.0.1. by Tylan Merriam")
print("you awaken, the room is dark and you cannot see. the sheets on your
bed are damp, and you hear a faint dripping sound.")
ch0pg1 = input('>: ')
if ch0pg1 == 'turn on light':
print("you flip the light on, it turns out the dripping was from a leaky
pipe above you. you see a dresser(outisde of bed) a chair with something
glinting on it(outside of bed) and a window(outisde of bed)")
ch1p1 = input('>: ')
if ch1p1 == 'stand':
print('you stand up, the game isnt finished so this is all there is,
try saying stand at the first choice or anything else')
else:
print('sorry, but i have no fricking clue what that means')
elif ch0pg1 == 'stand':
print('since you cannot see, you bump your head on a brick and collapse.
as you think of your last words you realize the only thing that comes to
mind is wushtub.')
diemessage = input('>: ')
if diemessage == 'lol':
print('i agree, now shut up, your dead')
else:
print('shut it, your dead')
else:
print('I have no clue what that means,')
You can try embedding a while loop within a while loop kind of like this.
while(1):
while(1):
# some code
# also some code
diemessage = input('>: ')
if diemessage == 'lol':
print('i agree, now shut up, your dead')
chc = input("play again? (y,n): ")
if chc == "y":
break # break this while loop which just starts again
elif chc == "n":
exit() # exit the game entirely
else:
# You can set this bit to your liking.
print("thats no answer, bye")
exit()
else:
print('shut it, your dead')
chc = input("play again? (y,n): ")
if chc == "y":
break # break this while loop which just starts again
elif chc == "n":
exit() # exit the game entirely
else:
# You can set this bit to your liking.
print("thats no answer, bye")
exit()
It simply creates a while loop for the game inside of a while loop. Break breaks out of the while loop while being ran, so it just exits and starts again. If the user chooses to quit, it stops the whole program.
You would think that we could create a function to make it easier, but when I tried breaking with a function it won't break, so you are going to have to keep pasting this in as of what I know. :P
Could do:
while (true)
{
//print statements
//whenever you die:
continue;
}
Well, you first need to define what you want to loop. Make a function called game() with your included code. Then this would work:
if diemessage == "lol":
print("something")
else:
print("Shut it, your dead")
game()
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
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).