I asked a similar question before, except the solution did not seem to work. I am writing a dice rolling game that if any one of the player's numbers matches the computer's numbers, the player wins and a message prints "You win." If otherwise, the elif statement means the computer wins and it prints "You lose."
My problem is that the elif statement won't print "you lose." it just keeps printing "you win."
import random
die1 = 0
die2 = 0
die3 = 0
roll1 = 0
roll2 = 0
roll3 = 0
def dice_roll():
dieroll = random.randint(1, 6)*2
return dieroll
for die in range(12):
die1 = int(input(f'Choose a number between 2 and 12: '))
die2 = int(input(f'Choose a number between 2 and 12: '))
die3 = int(input(f'Choose a number between 2 and 12: '))
roll1 = dice_roll()
roll2 = dice_roll()
roll3 = dice_roll()
if die1 or die2 or die3 == roll1 or roll2 or roll3:
print(f'Roll # 1 was {roll1}')
print(f'Roll # 2 was {roll2}')
print(f'Roll # 3 was {roll3}')
print(f'You Win! - Thanks for playing!')
elif die1 or die2 or die3 != roll1 or roll2 or roll3:
print(f'Roll # 1 was {roll1}')
print(f'Roll # 2 was {roll2}')
print(f'Roll # 3 was {roll3}')
print(f'You Lose! - Thanks for playing!')
Inside of your for loop, the parameters of the if statement have been declared incorrectly. Here's an example to help clarify it:
a=1
b=3
if a or b == 2:
print(True)
else:
print(False)
The if statement in the above example will always print True because you are asking the following: "if a holds a value that is True/greater than 0 or if b is equal to 2: print True" In your case:
if die1 or die2 or die3 == roll1 or roll2 or roll3
You are declaring your parameters as "if die1, roll2, or roll3 have any True/greater than 0 values or if die3 is equal to roll1: ...", so just change this to the actual values you want them compared to as Abhigyan Jaiswal's answer says and it will work correctly.
If you want to check if any of die1, die2, die3 matches any of roll1, roll2, roll3 then you can use:
print(f'Roll # 1 was {roll1}')
print(f'Roll # 2 was {roll2}')
print(f'Roll # 3 was {roll3}')
if {die1, die2, die3} & {roll1, roll2, roll3}:
print('You win. Thanks for playing.')
else:
print('You lose. Thanks for playing.')
This checks if the set of {die1, die2, die3} and the set of {roll1, roll2, roll3} have any elements in common.
Also, and by the way, random.randint(1, 6)*2 is not equivalent to rolling two dice. It's rolling one die and doubling the result; so all the odd numbers are excluded, and the probabilities are flattened. If you want to simulate rolling two dice, you want random.randint(1,6) + random.randint(1,6).
Adding on to khelwood's answer, you can use this method if you prefer this syntax
From your code logic, it seems that the player automatically wins when they make at least 1 correct guess(which I am not sure if this is your intention).
if die1 == roll1 or die2 == roll2 or die3 == roll3:
print(f'Roll # 1 was {roll1}')
print(f'Roll # 2 was {roll2}')
print(f'Roll # 3 was {roll3}')
print(f'You Win! - Thanks for playing!')
else:
print(f'Roll # 1 was {roll1}')
print(f'Roll # 2 was {roll2}')
print(f'Roll # 3 was {roll3}')
print(f'You Lose! - Thanks for playing!')
Python evaluates each condition that is separated by the keyword. A non-null value would always return True
Hence if you are doing this method
elif die1 or die2 or die3 != roll1 or roll2 or roll3:
die1 die2 roll2 roll3 will always return True and that is what causing your program to always print "You lose"
#You can do this as well
if die1 == roll1 or die2 == roll2 or die3 == roll3:
print(f'Roll # 1 was {roll1}')
print(f'Roll # 2 was {roll2}')
print(f'Roll # 3 was {roll3}')
print(f'You Win! - Thanks for playing!')
else:
print(f'Roll # 1 was {roll1}')
print(f'Roll # 2 was {roll2}')
print(f'Roll # 3 was {roll3}')
print(f'You Loose! - Thanks for playing!')
Related
Hi all. Really, REALLY stuck here. I've updated my code below.
I'm trying to establish a counter to track games played, correct guesses and > incorrect guesses plus, when the number of consecutive correct guesses
= 4 or user stops playing, game summary is provided.
I cannot get the counter to work correctly.
Help appreciated!
import math
import dice
import random
# Print introduction and game explanation
print ("")
print ("")
print ("Would you like to play a game?")
print ("The game is...'Petals Around the Rose'. Cool eh?")
print ("Pay attention - the name of the game is important.")
print ("Each round, five dice are rolled and")
print ("You'll be asked for the score. (Hint? The score")
print ("will always be either 'zero' or an even number).")
print ("Your challenge is to deduce how the computer has")
print ("calculated the score.")
print ("You need to input your guess, after which")
print ("You'll learn if you were right. If not, you'll")
print ("be told the correct score & asked to roll again.")
print ("If you can guess correctly four times in a row,")
print ("You'll be declared the winner and receive the")
print ("majestic title of 'Potentate of the Rose'")
print ("")
# Define win count (four correct guesses in a row required)
win_count = 0
# Obtain input from user:
answer = input("Are you up for the challenge? Enter 'y' or 'n' : ")
# If answer = no, exit game
if answer == 'n':
print("Really? fine then. See ya!")
exit()
# If answer = yes, commence game
elif answer == 'y':
print("")
print ("Ok...here comes the first roll!")
print("")
# import dice representation
import dice
# Roll random dice x 5
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
die3 = random.randint(1, 6)
die4 = random.randint(1, 6)
die5 = random.randint(1, 6)
dice.display_dice(die1, die2, die3, die4, die5)
# Obtain player's guess for the roll
roll_guess = int(input("Enter your guess for this roll: "))
# Define die results for all dice for guess purposes to
# match the 'petals around the rose'. So, if roll a 2, 4 or 6,
# the result is zero. If return a 3, the result is 2. If
# return a 5, the result is 4.
def roll_result(die1):
if die1 == 1 or die1 == 2 or die1 == 4 or die1 == 6:
die1 = 0
elif die1 == 3:
die1 = 2
elif die1 == 5:
die1 = 4
return die1
def roll_result(die2):
if die2 == 1 or die2 == 2 or die2 == 4 or die2 == 6:
die2 = 0
elif die2 == 3:
die2 = 2
elif die2 == 5:
die2 = 4
return die2
def roll_result(die3):
if die3 == 1 or die3 == 2 or die3 == 4 or die3 == 6:
die3 = 0
elif die3 == 3:
die3 = 2
elif die3 == 5:
die3 = 4
return die3
def roll_result(die4):
if die4 == 1 or die4 == 2 or die4 == 4 or die4 == 6:
die4 = 0
elif die4 == 3:
die4 = 2
elif die4 == 5:
die4 = 4
return die4
def roll_result(die5):
if die5 == 1 or die5 == 2 or die5 == 4 or die5 == 6:
die5 = 0
elif die5 == 3:
die5= 2
elif die5 == 5:
die5 = 4
return die5
# tally all 5 dice rolls
a = roll_result(die1)
b = roll_result(die2)
c = roll_result(die3)
d = roll_result(die4)
e = roll_result(die5)
total_roll_result = a + b + c + d + e
# Compare user input to dice result
if roll_guess == total_roll_result:
print("")
print('Well done! You guessed it!')
print("")
elif guess % 2 == 0:
print("")
print("No sorry, it's", total_roll_result, "not", roll_guess)
print("")
else:
print("")
print ("No, sorry, it's", total_roll_result, 'not', roll_guess,"")
print ("Remember,the answer will always be an even number")
print("")
# Obtain user input if continuing to play
another_attempt = input("Are you up to play again? If so, enter y or n ")
print("")
# Commence loop and win count.
while another_attempt == 'y' and win_count <4:
# Commence win count
win_count = 0
# Commence games played count
games_played = 0
# Commence incorrect guesses count
incorrect_guesses = 0
# If user has not yet gotten 4 guesses in a row:
if win_count < 4:
die1 = random.randint(1,6)
die2 = random.randint(1,6)
die3 = random.randint(1,6)
die4 = random.randint(1,6)
die5 = random.randint(1,6)
result = dice.display_dice(die1, die2, die3, die4, die5)
a = roll_result(die1)
b = roll_result(die2)
c = roll_result(die3)
d = roll_result(die4)
e = roll_result(die5)
total_roll_result = a + b + c + d + e
roll_guess = int(input('Enter your guess for this roll: '))
print("")
if roll_guess == total_roll_result:
# Update win count
win_count += 1
# Update games played count
games_played += 1
print("")
print('Nice work - you got it right!')
elif roll_guess %2 == 0:
# reset win count
win_count = 0
# Update games played count
games_played += 1
# Update incorrect guesses count
incorrect_guesses += 1
print("")
print("Nah, sorry, it's", total_roll_result, "not", roll_guess)
else:
# Reset win count
win_count = 0
# Update games played count
games_played += 1
# Update incorrect guesses count
incorrect_guesses += 1
print("")
print ("Nah, sorry, it's", total_roll_result, 'not', roll_guess,"")
print ("Remember,the answer will always be an even number")
print("")
another_attempt = input("Are you up to play again? ")
# Quit loop if user no longer wishes to play
# Provide game summary
if another_attempt == 'n':
print ("")
print ("Game Summary")
print ("------------")
print ("")
print ("You played ", games_played, "games.")
print ("")
print ("You had ", correct_guesses, "overall and ")
print ("")
print ("a total of ", incorrect_guesses, "overall ")
print ("")
print ("Cheerio!")
exit()
if win_count == 4:
# Inform player has correctly guessed 4 in a row
# Print congratulations message
print ("")
print ("")
print ("You've done it! You've successfully guessed")
print ("Four times in a row. Looks like you worked ")
print ("out the secret. Now, stay stum & tell no one!")
print ("")
# Provide game summary
print ("Game Summary")
print ("")
# Provide tally of games played & print:
print ("You played ", games_played, "games.")
print ("")
# Provide tally of correct guesses & print:
print ("You had ", correct_guesses, "overall and ")
print ("")
# Provide tally of total incorrect guesses & print:
print ("a total of ", incorrect_guesses, "overall ")
print ("")
print ("Cheerio!")
exit()
def game_stats():
win_count
games_played
incorrect_guesses
You look very lost here. This part does not make any sense
def win_count():
win_count() == 0
correct == total_roll_result
I think you mean something like this
win_count = 0
correct = total_roll_result == roll_guess
Note
When you say
def win_count:
# some code
you are defining win_count as a function! But clearly you want win_count to be an integer counting something.
I'm a Python beginning learner. Recently our school teacher asked us to do a project with following requirements:
Randomly pick a number from 1-6 for two players.
Each player starts with 100 points.
Each player rolls one dice. The player with the lower roll loses the number of points shown on the higher dice.
Play until one of the player's score is lower or equal to zero.
The run is Python 3.7.2, and here is the code:
import random
dice1 = random.randint(1,6)
dice2 = random.randint(1,6) #random number
player1 = 100
player2 = 100 #the initial marks for both players
While player1 > 0 or player2 > 0:
if dice1 > dice2: #when the player1 has the higher number
player2 = player2 - dice1
print("player1", player1, "player2", player2)
elif dice2 > dice1: #when the player 2 has the higher number
player1 = player1 - dice2
print("player1", player1, "player2", player2)
elif dice1 == dice2: #when two player get the same number
print("It's a tie.")
if player1 <= 0:
print("player2 win")
break
elif player2 <= 0:
print("player1 win")
break
I tried several times. When I run it, there were two problems:
One of the score keeps 100 all the time while the other one is kept changing until it is lower or equal to zero.
The result just keep coming up with "It's a tie."
I was confused with the result and had no idea how to fix it...
Really appreciate any and all help! Thanks|ू・ω・` )
Your code only rolls the dice (gets a random number set) once.
Move the dice roll inside the while loop like so:
import random
player1 = 100
player2 = 100 #the initial marks for both players
while (player1 > 0 and player2 > 0):
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
if dice1 > dice2: #when the player1 has the higher number
player2 = player2 - dice1
print("player1", player1, "player2", player2)
elif dice2 > dice1: #when the player 2 has the higher number
player1 = player1 - dice2
print("player1", player1, "player2", player2)
elif dice1 == dice2: #when two player get the same number
print("It's a tie.")
if player1 <= 0:
print("player2 win")
break
elif player2 <= 0:
print("player1 win")
break
I am one week into a coding bootcamp so forgive my simplistic and probably sloppy coding, but I was wondering how I could put in a running tally of wins for my two player dice rolling game. I am able to produce the final score and loop the function back around to start again if the players want to keep playing but I would like to keep a running tally of wins so the players know how many times each player has won. Here is my function:
def DiceRoll():
Dice1 = random.randint(1, 20)
Dice2 = random.randint(1, 12)
Dice3 = random.randint(1,6)
Dice4 = random.randint(1, 20)
Dice5 = random.randint(1, 12)
Dice6 = random.randint (1, 6)
DoubleDice1 = (((Dice1 + Dice2)*2) + Dice3)
DoubleDice2 = (((Dice1 + Dice3)*2) + Dice2)
DoubleDice3 = (((Dice2 + Dice3)*2) + Dice1)
DoubleDice4 = (((Dice4 + Dice5)*2) + Dice6)
DoubleDice5 = (((Dice4 + Dice6)*2) + Dice5)
DoubleDice6 = (((Dice5 + Dice6)*2) + Dice4)
TripleDice1 = ((Dice1 + Dice2 +Dice3) * 3)
TripleDice2 = ((Dice4 + Dice5 +Dice6) * 3)
print("Player 1, Roll?")
Roll = input("Y/N?")
if Roll =="y":
print("Ok!")
if Roll == "n":
print("Goodbye!")
time.sleep(2)
sys.exit(0)
print(" ")
print(Dice1, Dice2, Dice3)
Score1 = Dice1 + Dice2 + Dice3
if Dice1 == Dice2:
Score1 = DoubleDice1
print(Score1)
elif Dice1 ==Dice3:
Score1 = DoubleDice2
print(Score1)
elif Dice2 == Dice3:
Score1 = DoubleDice3
print(Score1)
elif Dice1 == Dice2 ==Dice3:
Score1 = TripleDice1
print(Score1)
else:
print(Dice1 + Dice2 + Dice3)
print("""
""")
print("Player 2, Roll?")
Roll2 = input("Y/N?")
if Roll2 =="y":
print("Ok!")
if Roll2 == "n":
print("Goodbye!")
time.sleep(2)
sys.exit(0)
print(" ")
print(Dice4, Dice5, Dice6)
Score2 = (Dice4 + Dice5 + Dice6)
if Dice4 == Dice5:
Score2 = DoubleDice4
print(Score2)
elif Dice4 == Dice6:
Score2 = DoubleDice5
print(Score2)
elif Dice5 == Dice6:
Score2 = DoubleDice6
print(Score2)
elif Dice4 == Dice5 ==Dice6:
Score2 = TripleDice2
print(Score2)
else:
print(Dice4 + Dice5 + Dice6)
print("""
""")
if Score1 > Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Player 1 Wins!")
if Score1 < Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Player 2 Wins!")
if Score1 == Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Tie!")
Since there is no loop in your function, I assume that you have that control loop in the program that calls DiceRoll. To make a clean tally, you'll need to return the win/lose designation to that program, something like this:
if Score1 > Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Player 1 Wins!")
winner = 1
elif Score1 < Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Player 2 Wins!")
winner = 2
else:
print("Player 1:", Score1, "Player 2:", Score2)
print("Tie!")
winner = 0
Now, back in your main program, we'll have something like:
p1_wins = 0
p2_wins = 0
ties = 0
while game_on:
result = DiceRoll()
if result == 1:
p1_wins += 1
elif result = 2
p2_wins += 1
else:
ties += 1
I've kept this at the level of programming I think you're using. First you get to understand it. In a few more boot camp sessions, come back to see how you'd like to improve your coding.
The most simplistic solution would be to have the DiceRoll function return which player won.
winner = None
if Score1 > Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Player 1 Wins!")
winner = 1
elif Score1 < Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Player 2 Wins!")
winner = 2
elif Score1 == Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Tie!")
winner = 0
return winner
Then in the loop that calls DiceRoll, just check the returned result.
Now, you've got a lot of repeated code in this function. You're basically doing everything twice. This makes it a prime candidate for breaking into another function. I would suggest making a function that takes the player as a parameter, and then does the dice rolls for just that player, and returns the score. Then you could just call the function for each player, compare the results, and determine the winner from that.
One last thing. If a player chooses not to roll, it's exiting the program. That should probably be changed to be considered a forfeit, and have it exit at the outer loop so you can display the final tally.
This question already has answers here:
Ask the user if they want to repeat the same task again
(2 answers)
Closed 2 years ago.
I have a simple program that runs a game of Craps. All of the logic of the craps game is in the playOnce() method. I need to use a main() method that calls the playOnce() method in order to determine whether a user wants to play again by entering either yes or no. I need to constantly ask the user if they want to play after each round. I'm having trouble implementing that piece of the logic of asking the user. I have tried using a while loop, but so far no output. Here's a sample: http://tinypic.com/r/2las1v/8
----------------------------------------------------
import random
def playOnce():
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
roll = dice1 + dice2
print("You rolled", dice1, "+", dice2, "=", roll)
print()
if roll == 2 or roll == 3 or roll == 12:
print("You lose!")
elif roll == 7 or roll == 11:
print("You win!")
else:
print("Point is", roll)
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
roll2 = dice1 + dice2
print("You rolled ",roll2)
while roll2 != 7:
if roll == roll2:
print("You win!")
break
else:
print("Point is ", roll)
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
roll2 = dice1 + dice2
print("You rolled ",roll2)
if roll2 == 7:
print("You lose!")
def main():
playOnce()
print("Would you like to go again?")
main()
How about:
def main():
keep_playing = True
while keep_playing:
playOnce()
ans = raw_input("Would you like to go again?")
if ans != 'y':
keep_playing = False
You can use this:
import random
def playOnce():
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
roll = dice1 + dice2
print("You rolled", dice1, "+", dice2, "=", roll)
print()
if roll == 2 or roll == 3 or roll == 12:
print("You lose!")
elif roll == 7 or roll == 11:
print("You win!")
else:
print("Point is", roll)
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
roll2 = dice1 + dice2
print("You rolled ",roll2)
while roll2 != 7:
if roll == roll2:
print("You win!")
break
else:
print("Point is ", roll)
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
roll2 = dice1 + dice2
print("You rolled ",roll2)
if roll2 == 7:
print("You lose!")
def main():
playOnce()
#print("Would you like to go again?")
flag = input("Would you like to go again?")
#flag = True
while flag:
playOnce()
flag = input("Would you like to go again?")
main()
Then you need reply True or False or 1 or 0
I'm trying to use functions (something that I am inherently bad at apparentlyXD) and am trying to get the return statement info from the first and then use it in the second. Both are for rolling dice, so the first function is to have the first set returned, which is to be then used in the second function to give the user the option to reroll. What am I doing wrong in this implementation that it's not recognizing the original dieset list?
def rollDie():
die1 = 2
die2 = 2
die3 = 2
die4 = 4
die5 = 5
dieset = [die1,die2,die3,die4,die5]
print(dieset)
return dieset
def reRoll1():
rollDie()
reroll1 = input("Would you like to reroll? Yes or No: ")
if reroll1 == "no":
dieset = [die1,die2,die3,die4,die5]
else:
count = 0
times = int(input("How many die would you like to reroll? "))
while count < times:
whichreroll = input("Reroll die: ")
if whichreroll == "1":
die1 = random.randint(1,6)
else:
die1
if whichreroll == "2":
die2 = random.randint(1,6)
else:
die2
if whichreroll == "3":
die3 = random.randint(1,6)
else:
die3
if whichreroll == "4":
die4 = random.randint(1,6)
else:
die4
if whichreroll == "5":
die5 = random.randint(1,6)
else:
die5
dieset = [die1,die2,die3,die4,die5]
count += 1
print(dieset)
return dieset
reRoll1()
It's telling me "local variable 'die1' referenced before assignment" but rollDie() comes first. If anyone could explain this to me it would be greatly appreciated:D
to be able to reference the returned data from rollDie() you need to assign it to a variable i.e.:
dieset = rollDie()
However, you also have a problem at:
if reroll1 == 'no':
dieset = [die1, die2, die3, die4, die5]
Here, you are referencing the variables die1, die2... but they haven't been assigned any value.
As a workaround, you could assign these variables an arbitrary value, say 0:
dieset = [0, 0, 0, 0, 0]
BUT... then in your conditionals, you reference variables die1, die2...; which haven't actually been assigned. So you could forget all about the variable dieset, and assign die1, die2... directly:
die1, die2, die3, die4, die5 = rollDie() if reroll1 == 'yes' else [0, 0, 0, 0, 0]
this way, you can then to reference the values simply as die1 etc. in your following conditions.
Hope this helps
You are not getting the desired behavior because die1, die2, ... are not global variables, but you are treating them as such.
In other words die1 within reRoll1() is different than die1 within rollDie().
To get what you want, you should either work with return values, or initialize the variables globally by writing there definition on the same indentation level as where you call reRoll1()