I am trying to create a game where you choose how many players there will be, name those players, and then one player is chosen at random.
From there, that chosen player would pick a number in between 1 and 10 that they DON'T want to land on.
Then, the dice rolls and if they land on that number, everyone else gets to pick a dare for him/her. If it doesn't, the game just randomly picks another player and the process begins again.
The problem is though, the program doesn't get past the part where it asks you which number you don't want to land on. This is weird, as it works fine with one person.
Here is the full code, you are looking for line 23:
# Pass Or Dare
from random import randint
firsttry = True
def playerpicked(list):
listwords = len(list)
numpicked = randint(0, listwords - 1)
userpicked = list[numpicked]
return userpicked
while firsttry:
try:
playercount = int(input('How many players will there be?\n'))
except ValueError:
print("That isn't a number. Please enter a number without decimals.")
else:
firsttry = False
playernames = [input("Name of Player {}: ".format(i)) for i in range(1, playercount + 1)]
while True:
playerturn = playerpicked(playernames)
print("The Player picked is:",playerturn)
while True:
try:
darenum = int(input(playerturn + ", which number do you NOT want to land on?\n"))
except ValueError:
print("Please enter a number.")
else:
if darenum > 10 or darenum < 1:
print("Please enter a number between 1 and 10.\n")
else:
break
print("Okay. Rolling the dice...")
numpick = randint(1, 10)
print("The number chosen is " + str(numpick) + ".")
if numpick == darenum:
print("Whoops! The number you chose was the one that we landed on! Everyone agree on a dare for " + playerturn + "!\n\n")
input("Press Enter once " + playerturn + " has done a dare...\n")
else:
print(playerturn + " has escaped! Moving on to the next person.\n\n")
Here is a fast review of the algorithm, the problem was that the break you used while checking if the darenumber was between the desired range, causing to loop back again and never getting out of there.
Also, it's recommended that you check your control structure because it´s what made the problem.
Lastly, I strongly recommend an exit feature of your game because in some point in has to end. Hope it helps:
from random import randint
def playerpicked(list):
listwords = len(list)
numpicked = randint(0, listwords - 1)
userpicked = list[numpicked]
return userpicked
playercount = 0
while playercount < 1:
try:
playercount = int(input('How many players will there be?\n'))
except ValueError:
print("That isn't a number. Please enter a number without decimals.")
playernames = [input("Name of Player {}: ".format(i)) for i in range(1, playercount + 1)]
print("Press 0 while it's your turn to finish the game")
while True:
playerturn = playerpicked(playernames)
print("The Player picked is:",playerturn)
darenum = -1
while (darenum > 10 or darenum < 0):
try:
darenum = int(input(playerturn + ", which number do you NOT want to land on?\n"))
if darenum > 10 or darenum < 1:
print("Please enter a number between 1 and 10.\n")
except ValueError:
print("Please enter a number.")
if darenum == 0:
break
print("Okay. Rolling the dice...")
numpick = randint(1, 10)
print("The number chosen is " + str(numpick) + ".")
if numpick == darenum:
print("Whoops! The number you chose was the one that we landed on! Everyone agree on a dare for " + playerturn + "!\n\n")
input("Press Enter once " + playerturn + " has done a dare...\n")
else:
print(playerturn + " has escaped! Moving on to the next person.\n\n")
print("Game Over")
Your original code, with errors sinalization (read the code's comments):
# Pass Or Dare
from random import randint
firsttry = True
def playerpicked(list):
listwords = len(list)
numpicked = randint(0, listwords - 1)
userpicked = list[numpicked]
return userpicked
while firsttry:
try:
playercount = int(input('How many players will there be?\n'))
except ValueError:
print("That isn't a number. Please enter a number without decimals.")
else:
firsttry = False
playernames = [input("Name of Player {}: ".format(i)) for i in range(1, playercount + 1)]
while True:
playerturn = playerpicked(playernames)
print("The Player picked is:",playerturn)
while True:
try:
darenum = int(input(playerturn + ", which number do you NOT want to land on?\n"))
except ValueError:
print("Please enter a number.")
else: #there is no if for this else
if darenum > 10 or darenum < 1:
print("Please enter a number between 1 and 10.\n")
else:
break #this break would break the while True above
print("Okay. Rolling the dice...")
numpick = randint(1, 10)
print("The number chosen is " + str(numpick) + ".")
if numpick == darenum:
print("Whoops! The number you chose was the one that we landed on! Everyone agree on a dare for " + playerturn + "!\n\n")
input("Press Enter once " + playerturn + " has done a dare...\n")
else:
print(playerturn + " has escaped! Moving on to the next person.\n\n")
#there should be a break in here, otherwise the function would be stuck in the second while True
The fixed code, changing what I mentioned in the comments above:
# Pass Or Dare
from random import randint
firsttry = True
def playerpicked(list):
listwords = len(list)
numpicked = randint(0, listwords - 1)
userpicked = list[numpicked]
return userpicked
while firsttry:
try:
playercount = int(input('How many players will there be?\n'))
except ValueError:
print("That isn't a number. Please enter a number without decimals.")
else:
firsttry = False
playernames = [input("Name of Player {}: ".format(i)) for i in range(1, playercount + 1)]
while True:
playerturn = playerpicked(playernames)
print("The Player picked is:",playerturn)
while True:
try:
darenum = int(input(playerturn + ", which number do you NOT want to land on?\n"))
except ValueError:
print("Please enter a number.")
if darenum > 10 or darenum < 1:
print("Please enter a number between 1 and 10.\n")
else:
print("Okay. Rolling the dice...")
numpick = randint(1, 10)
print("The number chosen is " + str(numpick) + ".")
if numpick == darenum:
print("Whoops! The number you chose was the one that we landed on! Everyone agree on a dare for " + playerturn + "!\n\n")
input("Press Enter once " + playerturn + " has done a dare...\n")
else:
print(playerturn + " has escaped! Moving on to the next person.\n\n")
break
Related
How would I ask the user if they want to play and then start the simulation? And if they don't the program prints a goodbye message. And print the total number of times the coin was flipped at the end.
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
while True:
try:
time_flip= int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
else:
break
return time_flip
def random_flip():
return random.randint(0, 1)
def count_for_sides():
count_head=0
count_tail=0
times=num_of_input()
while True:
if count_head + count_tail == times:
break
else:
if random_flip()==0:
count_head+=1
else:
count_tail+=1
print()
print(str(count_head) + " came up Heads")
print(str(count_tail) + " came up Tails")
count_for_sides()
You can get input from the user before calling the count_for_sides method and call it if they opt in.
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
while True:
try:
time_flip = int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
else:
break
return time_flip
def random_flip():
return random.randint(0, 1)
def count_for_sides():
count_head=0
count_tail=0
times=num_of_input()
while True:
if count_head + count_tail == times:
break
else:
if random_flip()==0:
count_head+=1
else:
count_tail+=1
print()
print(str(count_head) + " came up Heads")
print(str(count_tail) + " came up Tails")
userWantsToPlay = input("Do you want to play this game? (Y/n): ")
if (userWantsToPlay == 'Y'):
count_for_sides()
My code keeps crashing after I put in the 1st guess I make. I've looked at syntax and dont think that's a problem how do I make it so it goes past the 1st guess and executes it. When I put the guess in it just puts in all the prompts at once, and how do I call the function properly at the end? Any help would be appreciated.
Import time,os,random
def get_int(message):
while True:
user_input = input(message)
try:
user_input = int(user_input)
print('Thats an integer!')
break
except:
print('That does not work we need an integer!')
return user_input
def game_loop():
fin = False
while not fin:
a = get_int('give me a lower bound:')
b = get_int('give me a upper bound:')
if a < 0:
print("that doesn't work")
if a > b:
a, b = b, a
print(a,b)
os.system('clear')
print("The number you guess has to be between " + str(a) + "and " + str(b) + '.')
num_guesses = 0
target = random.randint(a,b)
time_in = time.time()
while True:
print('You have guessed ' + str(num_guesses) + " times.")
print()
guess_input = get_int('guess a number')
if guess_input == target:
print("Congrats! You guessed the number!")
time_uin = time.time()
break
elif guess_input < a or guess_input > b:
print("guess was out of range... + 1 guess")
elif guess_input < target:
print("Your guess was too low")
else:
print("Your guess was to high")
num_guesses = num_guesses + 1
if num_guesses<3:
print('Einstein?')
else:
print('you should be sorry')
time_t = time_uin - time_in
print('it took' + str(time_t) + 'seconds for you to guess a number')
print()
time_average = time_t / (num_guesses+1)
print('It took an average of' + str(time_average)+"seconds per question")
print()
while True:
play_again = input ('Type y to play again or n to stop')
print()
if play_again == 'n':
fin = True
print('Thank God')
time.sleep(2)
os.system('clear')
break
elif play_again == 'y':
print('here we go again')
time.sleep(2)
os.system('clear')
break
else:
print('WRONG CHOCICE')
break
game_loop()
If guess_input != target on the first iteration of the loop, time_uin is referenced before assignment. Hence the error:
UnboundLocalError: local variable 'time_uin' referenced before assignment
Solution is to run the following only if guess_input == target.
if num_guesses<3:
print('Einstein?')
else:
print('you should be sorry')
time_t = time_uin - time_in
print('it took' + str(time_t) + 'seconds for you to guess a number')
print()
time_average = time_t / (num_guesses+1)
print('It took an average of' + str(time_average)+"seconds per question")
print()
Please follow coppereyecat's link to learn how to debug a basic Python program.
I am trying to reply to this game and store the count in the passed memory but, any time I run the code again the game starts from scratch and the previous score is lost.
How can I store and continue from the past round.
import random
MAX_GUESSES = 5 #max number of guesses allowed
MAX_RANGE = 20 #highest possible number
#show introductionpygame
print("welcome to my franchise guess number game")
print("guess any number between 1 and", MAX_RANGE)
print("you will have a range from", MAX_GUESSES, "guesses")
#choose random target
target = random.randrange(1, MAX_RANGE + 1)
#guess counter
guessCounter = 0
#loop fovever
while True:
userGuess = input("take a guess:")
userGuess =int(userGuess)
#increment guess counter
guessCounter = guessCounter + 1
#if user's guess is correct, congratulate user, we're done
if userGuess == target:
print("you got it la")
print("it only took you",guessCounter, "guess(es)")
break
elif userGuess < target:
print("try again, your guess is too low.")
else:
print(" your guess was too high")
#if reached max guesses, tell answer correct answer, were done
if guessCounter == MAX_GUESSES:
print(" you didnt get it in ", MAX_GUESSES, "guesses")
print("the number was", target)
break
print("Thanks for playing ")
#main code
while True:
playOneRound() #call a function to play one round of the game
goAgain = input("play again?(press ENTER to continue, or q to quit ):")
if goAgain == "q":
break
you forgot to mention the function name playOneRound. The code below works fine.
import random
MAX_GUESSES = 5 # max number of guesses allowed
MAX_RANGE = 20 # highest possible number
# show introductionpygame
print("welcome to my franchise guess number game")
print("guess any number between 1 and", MAX_RANGE)
print("you will have a range from", MAX_GUESSES, "guesses")
def playOneRound():
# choose random target
target = random.randrange(1, MAX_RANGE + 1)
# guess counter
guessCounter = 0
# loop fovever
while True:
userGuess = input("take a guess:")
userGuess = int(userGuess)
# increment guess counter
guessCounter = guessCounter + 1
# if user's guess is correct, congratulate user, we're done
if userGuess == target:
print("you got it la")
print("it only took you", guessCounter, "guess(es)")
break
elif userGuess < target:
print("try again, your guess is too low.")
else:
print(" your guess was too high")
# if reached max guesses, tell answer correct answer, were done
if guessCounter == MAX_GUESSES:
print(" you didnt get it in ", MAX_GUESSES, "guesses")
print("the number was", target)
break
print("Thanks for playing ")
# main code
while True:
playOneRound() # call a function to play one round of the game
goAgain = input("play again?(press ENTER to continue, or q to quit ):")
if goAgain == "q":
break
Hey I'm trying to add a variable for "won" or "loss", I already have a variable for players name and guesses allowed.
Any help would be kind thanks. This is the code I have so far:
import random
number = random.randint(1, 100)
player_name = input("Hello, What's your name?: ")
number_of_guesses = 0
print("Okay! "+ player_name+ " I am guessing a number between 1 and 100:")
max_guesses = random.randint(1, 6)
print("You have " + str(max_guesses) + " guesses. ")
while number_of_guesses < max_guesses:
guess = int(input())
number_of_guesses += 1
if guess < number:
print("Your guess is too low")
if guess > number:
print("Your guess is too high")
if guess == number:
break
if guess == number:
print("You guessed the number in " + str(number_of_guesses) + " tries!")
else:
print("You did not guess the number, the number was " + str(number))
f = open("statistics.txt", "a")
f.write =(player_name) (max_guesses)
f.close()
f = open("statistics.txt", "r")
print(f.read())
Maybe add befor you loop the variable won = False
And in the loop
if guess == number:
won = True
break
After the loop if the player don't find the nulber won will be false.
In the oter case it will be True
For saving
f.write( str(won) ) # convert to string
Subtracting or adding doesnt work in this loop
Tried changing into return but it didnt work for me . Im a noob ...
from random import randint
import time
def Guess2(n):
randomNo=randint(0,n)
print("This time you will choose a number, and the Computer will attempt to guess your number!")
print("Hello, what is your name:")
myName=str(input())
print("Alright "+myName+", "+"I will start to guess your number now!"+"\nchoose it, I will close my eyes.")
number=int(input())
time.sleep(2)
print("Okay, I will open my eyes now!")
time.sleep(2)
print("Can I start guessing now? Just answer with 'no' , 'yes'")
Answer=str(input())
if Answer[0:]=="no":
time.sleep(1)
print("all this for nothing.. bye")
if Answer[0:]=="yes":
time.sleep(1)
print("Alright let's go!")
time.sleep(1)
print("my first guess is: ",randomNo)
while number !=randomNo:
Userinput=input()
if Userinput=="too big":
print("okay, ",randomNo-1)
if Userinput=="too small":
print("okay, ",randomNo+1)
if Userinput=="richtig":
print("I win!")
It should add up +1 or -1 to the result from before. Maybe you could give me some advice aswell how to get to the number to be guessed faster :)
This is the refined version, but with a zoning algorithm. Try it.
import time
from random import randint
def Guess2():
toosmall = []
toobig = []
print("This time you will choose a number, and the Computer will attempt to guess your number!")
print("Hello, what is your name:")
myName=str(input())
print("Alright "+myName+", "+"I will start to guess your number now!"+"\nchoose it, I will close my eyes.")
number = int(input())
time.sleep(2)
print("Okay, I will open my eyes now!")
time.sleep(2)
print("Can I start guessing now? Just answer with 'no' , 'yes'")
Answer=str(input())
if Answer[0:]=="no":
time.sleep(1)
print("all this for nothing.. bye")
if Answer[0:]=="yes":
time.sleep(1)
print("Alright let's go!")
time.sleep(1)
if number > 0:
randomNo = randint(-1 * number, number + int(number/2))
elif number > -14 and number < 0:
randomNo = randint(0, number + (-2 * number))
else:
randomNo = randint(number - int(number/2), -1 * number)
print("my first guess is: ",randomNo)
while number !=randomNo:
Userinput=input()
toobig.append(number + 10000)
toosmall.append(number - 10000)
if min(toobig) - 2 == max(toosmall):
print(f"Your number is {max(toosmall) + 1}")
exit()
else:
if Userinput=="too big":
toobig.append(randomNo)
randomNo = randomNo - randint(1, int(abs(number/2)))
if randomNo <= max(toosmall):
randomNo = max(toosmall) + 2
print("okay, ", randomNo)
else:
print("okay, ", randomNo)
if min(toobig) - 2 == max(toosmall):
print(f"Your number is {max(toosmall) + 1}")
exit()
elif Userinput=="too small":
toosmall.append(randomNo)
randomNo = randomNo + randint(1, int(abs(number/2)))
if randomNo >= min(toobig):
randomNo = min(toobig) - 2
print("okay, ", randomNo)
else:
print("okay, ", randomNo)
if min(toobig) - 2 == max(toosmall):
print(f"Your number is {max(toosmall) + 1}")
exit()
elif Userinput=="richtig":
print("I win!")
Guess2()
nvm it works now. I overwrote my randomNo after each loop and now it finally takes the new RandomNo each time now.
from random import randint
import time
def Guess2(n):
randomNo=randint(0,n)
print("This time you will choose a number, and the Computer will attempt to guess your number!")
print("Hello, what is your name:")
myName=str(input())
print("Alright "+myName+", "+"I will start to guess your number now!"+"\nchoose it, I will close my eyes.")
number=int(input())
time.sleep(2)
print("Okay, I will open my eyes now!")
time.sleep(2)
print("Can I start guessing now? Just answer with 'no' , 'yes'")
Answer=str(input())
if Answer[0:]=="no":
time.sleep(1)
print("all this for nothing.. bye")
if Answer[0:]=="yes":
time.sleep(1)
print("Alright let's go!")
time.sleep(1)
print("my first guess is: ",randomNo)
while number!=randomNo:
Userinput=input()
if Userinput=="too big":
x1=randomNo-1
print(x1)
randomNo=x1
if Userinput=="too small":
x1=randomNo+1
print(x1)
randomNo=x1
if Userinput=="richtig":
print("I win!")