I know that a "not repeat with random from a list" is probably seen as a info you can find, but as someone who does not have a lot of knowledge of python yet, i cannot seem to understand those answers or they do not work for my problem. So I hope any of you are able to help.
as my first small project I am building a truth or dare program, and now I am at the point that I want to make it that the questions cannot be asked twice, and that if the truth questions are all done it prints that announcement, and I want the same for my dare questions.
here is my program so far, sorry if it is messy:
import random
import time
truth = ["If you could be invisible, what is the first thing you would do?",
"What is a secret you kept from your parents?",
"What is the most embarrassing music you listen to?",
"What is one thing you wish you could change about yourself?",
"Who is your secret crush?"]
dare = ["Do a free-style rap for the next minute",
"Let another person post a status on your behalf.",
"Hand over your phone to another player who can send a single text saying anything they want to anyone they want.",
"Let the other players go through your phone for one minute.",
"Smell another player's armpit."]
print("Hello, and welcome to my truth or dare show, just type truth or type dare to get a question!")
lives = 3
while lives > 0:
choice = input("truth or dare?: ").lower()
time.sleep(0.5)
if choice == "truth":
print(random.choice(truth))
time.sleep(0.5)
while True:
answer_truth = input("want to answer? type yes or no: ").lower()
if answer_truth == "yes":
input("> ").lower()
print("good answer")
time.sleep(0.5)
print(f"you have {lives} lives left")
break
elif answer_truth == "no":
print("you lost a life!")
time.sleep(1)
lives -= 1
print(f"you have {lives} lives left")
break
else:
print("that is not an option")
elif choice == "dare":
print(random.choice(dare))
time.sleep(0.5)
while True:
do_dare = input(f"did you do the dare? type yes or no: ").lower()
if do_dare == "yes":
print("well done!")
time.sleep(0.5)
print(f"you have {lives} lives left")
break
elif do_dare == "no":
print("you lost a life!")
lives -= 1
time.sleep(0.5)
print(f"you have {lives} lives left")
break
else:
print("that is not an option")
else:
print("that is not an option")
time.sleep(0.5)
print("GAME OVER!")
This should work:
choice = random.choice(truth)
time.sleep(0.5)
# inside the loop
truth.remove(choice)
if len(truth) == 0:
print("all questions are done")
do the same for dare
You probably want a construct like this:
from random import shuffle
ls = ["a", "b", "c"]
shuffle(ls)
lives = 3
while lives > 0 and ls:
current_question = ls.pop()
... # Rest of your code
So you want to select a random option, but then no longer have it in the set that you select random things from in the future.
If you imagine it physically, you have a jar list that has papers item's in it and you want to take them out at random. Obviously, any that you take out can not be taken out again.
We can accomplish this by removing the item from the list after it's 'picked'
To answer your question about having it let them know there are no more truths or no more dares, we can simply add a conditional to the whole truth segment and one to the whole dare segment as well, then further, if both run out, end the game.
while lives > 0 and (len(truth)>0 or len(dare>0)):
# Rest of the program
if choice == "truth":
if len(truth) > 0:
# Code
else:
print("there are no more truths (existential crisis), maybe try a dare instead")
elif choice == "dare":
if len(dare)>0:
# Code
else:
print("there are no more dares *sigh of releif*, maybe try a truth instead")
Related
I am making a guessing game. I wanted to create a guess counter module in a modules.py doc and import it into my main.py so i could access its instance for other modules.
The only problem is I cant get it to function.
main.py code ##
guess = Guess_Counter(0)
print("Welcome to the guessing game you have 3 guesses your first riddle is: \n")
while True and (guess) < 4:
print("I am cool as a breeze, I stop your heart with ease, seasons may be my enemy, but im part of you and you are friend to me. What am I? \n")
print("Enter your guess or type 'hint', or 'quit' below.")
answer = input()
answer = answer.upper()
guess += 1
if "sneeze" in answer.upper():
print("Great work, your next riddle is: \n")
break
elif answer == "hint":
guess.guess -= 1
print("Achoo!\n")
elif answer == "quit" or guess == 4:
print("Better luck next time! ")
quit()
else:
print("Try again!")
Testmodules.py code ##
class Guess_Counter():
def __init__(self, numguess):
self.numguess = numguess
Now, I just can't seem to figure it out
What i'm after I think is a global Boolean that'll be set to False unless door two has been accessed then it'll flip the Boolean to be True but because i'm invoking roomChoice() to go back to the start after entering room two it's all being restarted.
Just wondering the logic to achieve this.
try and ignore the horrible mess that is this code ha, I'm doing this program in an attempt to convert from Java to Python and learn Vim in the process, so just slowly learning here.
global key = False
def roomChoice():
print("It is now time to make a decision, so go on, 1, 2 or 3")
userinput = int(input())
while userinput != 1 or 2 or 3:
if(userinput == 1):
print("Doors locked")
roomChoice()
elif(userinput == 1 and key == True):
print(
"You've entered the room, it's now time to decide if you want to steal the wallet?")
userinput = input()
if(userinput == "yes"):
print("Nice move, quick lets get out of here")
elevator()
elif(userinput == "no"):
print("Well, on your way back to the elevator someone sees you coming out of the apartment, later they realise a wallet has been stolen, because you have been seen at the crime you are falsely imprisoned for burglary. 10 years, the judge really didn’t like you.")
exit()
else:
roomChoice()
elif(userinput == 2):
print("Oh look a key, I wonder if that'll get you into room one?")
key = True
roomChoice()
else:
roomChoice()
break
I figured it out, one of those fun kinds of answers, I just had to flip my if & elif around as it was meeting the requirements of the if statement so it was never getting to the elif section. Nice.
global key = False
def roomChoice():
print("It is now time to make a decision, so go on, 1, 2 or 3")
userinput = int(input())
while userinput != 1 or 2 or 3:
if(userinput == 1 and key == True):
print(
"You've entered the room, it's now time to decide if you want to steal the wallet?")
userinput = input()
if(userinput == "yes"):
print("Nice move, quick lets get out of here")
elevator()
elif(userinput == "no"):
print("Well, on your way back to the elevator someone sees you coming out of the apartment, later they realise a wallet has been stolen, because you have been seen at the crime you are falsely imprisoned for burglary. 10 years, the judge really didn’t like you.")
exit()
else:
roomChoice()
elif(userinput == 1):
print("Doors locked")
roomChoice()
elif(userinput == 2):
print("Oh look a key, I wonder if that'll get you into room one?")
key = True
roomChoice()
else:
roomChoice()
break
EDIT: You just have a logic error in your first if/elif statement, you have to check that the key is still false in the if statement, or it will always execute instead of the elif below it.
Did you try declaring the key as a global variable inside the function?
key = False
def roomChoice():
global key
userinput = int(input("It is now time to make a decision, so go on, 1, 2 or 3: ")) # you can pass the prompt string as a parameter to the input method
while userinput != 1 or userinput != 2 or userinput != 3:
if(userinput == 1 and key is False): # key has not yet been found
print("Doors locked")
roomChoice()
elif(userinput == 1 and key is True): # now key has been found
print()
userinput = input("You've entered the room, it's now time to decide if you want to steal the wallet? ")
if(userinput == "yes"):
print("Nice move, quick lets get out of here")
elevator()
elif(userinput == "no"):
print("Well, on your way back to the elevator someone sees you coming out of the apartment, later they realise a wallet has been stolen, because you have been seen at the crime you are falsely imprisoned for burglary. 10 years, the judge really didn’t like you.")
exit()
else:
roomChoice()
elif(userinput == 2):
print("Oh look a key, I wonder if that'll get you into room one?")
key = True
roomChoice()
else:
roomChoice()
break
I've been trying to return my code to the beginning after the player chooses 'yes' when asked to restart the game. How do I make the game restart?
I've tried as many solutions as possible and have ended up with this code. Including continue, break, and several other obvious options.
import time
def start():
score = 0
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurist to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
print("Type 1 to explore Atlantis alone.")
time.sleep(1.5)
print("Type 2 to talk to the resident merpeople.")
start()
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = -1
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
score = 1
print("To explore alone enter 5. To go to the surface enter 6.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 4
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
print("Type 3 to go to the castle or 4 to go to the surface.")
score = 5
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 6
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
def choice_made():
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
def choice2_made():
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
elif choice2 == "3":
castle()
elif choice2 == "yes":
start()
elif choice2 == "no":
exit()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
def choice3_made():
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
def restart_made():
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
while True:
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
while True:
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
if choice2 == "3":
castle()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
while True:
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
if choice3 == "1":
drowndeath()
if choice3 == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
while True:
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
I want for my code to restart completely when 'yes' is typed after given the option.
In general, if you want to be able to 'go back to the beginning' of something, you want to have a loop that contains everything. Like
while True:
""" game code """
That would basically repeat your entire game over and over. If you want it to end by default, and only restart in certain situations, you would do
while True:
""" game code """
if your_restart_condition:
continue # This will restart the loop
if your_exit_condition:
break # This will break the loop, i.e. exit the game and prevent restart
""" more game code """
break # This will break the loop if it gets to the end
To make things a little easier, you could make use of exceptions. Raise a RestartException whenever you want to restart the loop, even from within one of your functions. Or raise an ExitException when you want to exit the loop.
class RestartException(Exception):
pass
class ExitException(Exception):
pass
while True:
try:
""" game code """
except RestartException:
continue
except ExitException:
break
break
You have two main options.
First option: make a main function that, when called, executes your script once. Then, for the actual execution of the code, do this:
while True:
main()
if input("Would you like to restart? Type 'y' or 'yes' if so.").lower() not in ['y', 'yes']:
break
Second, less compatible option: use os or subprocess to issue a shell command to execute the script again, e.g os.system("python3 filename.py").
EDIT: Despite the fact this is discouraged on SO, I decided to help a friend out and rewrote your script. Please do not ask for this in the future. Here it is:
import time, sys
score = 0
def makeChoice(message1, message2):
try:
print("Type 1 "+message1+".")
time.sleep(1.5)
print("Type 2 "+message2+".")
ans = int(input("Which do you choose? "))
print()
if ans in (1,2):
return ans
else:
print("Please enter a valid number.")
return makeChoice(message1, message2)
except ValueError:
print("Please enter either 1 or 2.")
return makeChoice(message1, message2)
def askRestart():
if input("Would you like to restart? Type 'y' or 'yes' if so. ").lower() in ['y', 'yes']:
print()
print("Okay. Restarting game!")
playGame()
else:
print("Thanks for playing! Goodbye!")
sys.exit(0)
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
def playGame():
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurer to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
ans = makeChoice("to explore Atlantis alone", "to talk to the resident merpeople")
if ans == 1:
drowndeath()
askRestart()
merpeople()
ans = makeChoice("to go to the castle", "to return to the surface")
if ans == 2:
surface()
askRestart()
castle()
ans = makeChoice("to return to the surface", "to explore alone")
if ans == 1:
famous()
else:
alone()
askRestart()
playGame()
So I'm making a little game to teach myself how python works, and it's been okay up to this point, but now I'm completely stuck. I'm sure the logic and formatting of the if and while statement are all wrong, so I'd be happy if people could point me in the right direction - again, REALLY new to programming in general. I'll paste the code, then explain what I'm trying to make it do:
import random
import time
print("Welcome to the Dojo!")
print("You have three opponents; they are ready...")
print("Are you?")
print("*To view the rules, type 'rules' ")
print("*To view commands, type 'commands' ")
print("*To begin, type 'start' ")
while True:
userInput = (input())
# Rules
if userInput == "rules":
print("The rules in this Dojo are simple. Kill your opponent! Fight to the death! Show no mercy!")
print("Each opponent gets progressively more difficult, whether it be in terms of health or damage.")
print("To attack, type 'attack'")
print("May the better (luckier) warrior win")
# Commands - to be added
elif userInput == "commands":
print("Commands will be added soon!")
# Start
elif userInput == "start":
damage = random.randint(1, 50)
userHealth = int(100)
opponentHealth = int(100)
print("Your first opponent is Larry Schmidt. Don't sweat it, he'll be a piece of cake.")
time.sleep(3)
print("The battle will begin in")
time.sleep(1)
print("5")
time.sleep(1)
print("4")
time.sleep(1)
print("3")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
time.sleep(1)
print("Fight!")
if userInput == "attack":
int(userHealth - damage)
print("You did %(damage) to Larry!")
# Invalid response
else:
print("Enter a valid response, young grasshopper.")
if userInput == "start" is True:
continue
If you run the program for yourself, everything is okay until you reach the "5, 4, 3, 2, 1, Fight!" part. Then when you type "attack," it gives you "Enter a valid response, young grasshopper." I understand why this is happening, because "attack" doesn't fall under "rules", "commands", or "start". I just don't get how I'm supposed to format it so that after I enter "attack", it actually proceeds and outputs the damage done, etc. I apologize if this is hard to understand, but I think if you run it for yourself, you'll understand what I'm having problems with. Honestly, something tells me I've messed up the if and while statements up entirely, but hey, I'm learning and having fun :P.
Thanks for any help.
You aren't asking for more input. It's guaranteed that the userInput will still be "start" at that point.
Your code would benefit greatly from the use of functions. You could really organize the code better that way.
def intro():
print("Welcome to the Dojo!")
print("You have three opponents; they are ready...")
print("Are you?")
print("*To view the rules, type 'rules' ")
print("*To view commands, type 'commands' ")
print("*To begin, type 'start' ")
def get_user_input():
user_input = (input())
while user_input not in ['rules', 'commands', 'start']:
print("valid commands are rules, commands and start")
user_input = (input())
return user_input
intro()
returned_user_input = get_user_input()
There are a lot of ways to do these things, and you'll get better with time. Mainly note that user_input only gets updated when you do this:
user_input = (input())
Which in your code was only done once.
The code you have in the "start" branch of the if conditional will only run once, and userInput will still be "start" at that point. The solution, wrap it in a loop. Maybe something like this:
elif userInput == "start":
userHealth = 100
opponentHealth = 100
print("Your first opponent is Larry Schmidt. Don't sweat it, he'll be a piece of cake.")
time.sleep(3)
print("The battle will begin in")
time.sleep(1)
print("5")
time.sleep(1)
print("4")
time.sleep(1)
print("3")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
time.sleep(1)
print("Fight!")
while opponentHealth > 0 and userHealth > 0:
userInput = input()
if userInput == "attack":
damage = random.randint(1, 50)
opponentHealth = opponentHealth - damage
print("You did %d to Larry!" % damage)
The while loop will loop until the opponent has been defeated or until the user is defeated, but at the moment, there's no damage done to the user. I'll leave that part to you.
I am using python 2.6.6
I am simply trying to restart the program based on user input from the very beginning.
thanks
import random
import time
print "You may press q to quit at any time"
print "You have an amount chances"
guess = 5
while True:
chance = random.choice(['heads','tails'])
person = raw_input(" heads or tails: ")
print "*You have fliped the coin"
time.sleep(1)
if person == 'q':
print " Nooo!"
if person == 'q':
break
if person == chance:
print "correct"
elif person != chance:
print "Incorrect"
guess -=1
if guess == 0:
a = raw_input(" Play again? ")
if a == 'n':
break
if a == 'y':
continue
#Figure out how to restart program
I am confused about the continue statement.
Because if I use continue I never get the option of "play again" after the first time I enter 'y'.
Use a continue statement at the point which you want the loop to be restarted. Like you are using break for breaking from the loop, the continue statement will restart the loop.
Not based on your question, but how to use continue:
while True:
choice = raw_input('What do you want? ')
if choice == 'restart':
continue
else:
break
print 'Break!'
Also:
choice = 'restart';
while choice == 'restart':
choice = raw_input('What do you want? ')
print 'Break!'
Output :
What do you want? restart
What do you want? break
Break!
I recommend:
Factoring your code into functions; it makes it a lot more readable
Using helpful variable names
Not consuming your constants (after the first time through your code, how do you know how many guesses to start with?)
.
import random
import time
GUESSES = 5
def playGame():
remaining = GUESSES
correct = 0
while remaining>0:
hiddenValue = random.choice(('heads','tails'))
person = raw_input('Heads or Tails?').lower()
if person in ('q','quit','e','exit','bye'):
print('Quitter!')
break
elif hiddenValue=='heads' and person in ('h','head','heads'):
print('Correct!')
correct += 1
elif hiddenValue=='tails' and person in ('t','tail','tails'):
print('Correct!')
correct += 1
else:
print('Nope, sorry...')
remaining -= 1
print('You got {0} correct (out of {1})\n'.format(correct, correct+GUESSES-remaining))
def main():
print("You may press q to quit at any time")
print("You have {0} chances".format(GUESSES))
while True:
playGame()
again = raw_input('Play again? (Y/n)').lower()
if again in ('n','no','q','quit','e','exit','bye'):
break
You need to use random.seed to initialize the random number generator. If you call it with the same value each time, the values from random.choice will repeat themselves.
After you enter 'y', guess == 0 will never be True.