I have a code that rolls two dice, for each players where they type 'roll' to roll each of their dice.
However, if they don't type in 'roll' correctly, the code doesn't work properly and instead of asking the user over and over again to enter 'roll' again/ correctly, it goes through the code regardless without validating their input.
The code is supposed to ask Player 1 to roll their first then second dice for Round 1, then move onto Player 2's two dice for round one, then round 2, until both player have gone through 5 rounds, and if they type it incorrectly, it just asks for the right input until it's right.
import random
tot1 = 0
tot2 = 0
tot2 = 0
rnd2 = 0
for i in range (1,6):
while True:
from random import randint
print()
print("Player 1")
ro1_1 = input("Type 'roll' to roll your 1st dice: ")
if ro1_1 == 'roll':
dice1_1 = (randint(1,6))
print("Player1 dice 1:", dice1_1)
else:
ro1_1 = input("Type 'roll' to roll your 1st dice: ")
ro1_2 = input("Type 'roll' to roll your 2nd dice: ")
if ro1_2 == "roll":
dice1_2 = (randint(1,6))
print("Player1 Dice 2:", dice1_2)
else:
ro1_2 = input("Type 'roll' to roll your 1st dice: ")
print()
print ("Player1's total for round",(rnd1)," is:",tot1)
print()
print ("Player 2")
ro2_1 = input("Type 'roll' to roll your 1st dice: ")
if ro2_1 == 'roll':
dice2_1 = (randint(1,6))
print("Player2 Dice 1:", dice2_1)
else:
ro1_1 = input("Type 'roll' to roll your 1st dice: ")
ro2_2 = input("Type 'roll' to roll your 2nd dice: ")
if ro2_2 == 'roll':
dice2_2 = (randint(1,6))
print("Player2 Dice 2:", dice2_2)
else:
ro2_2 = input("Type 'roll' to roll your 1st dice: ")
break
print()
print ("Player2's total for round",(rnd2)," is:",tot2)
print()
break
First, move from random import randint to the top - at least outside the while loop.
This won't solve the problem, but just saying.
Next, you want something to stop until the player types "roll".
In several places.
Write a function:
def wait_for_right_input():
while True:
if input("Type 'roll' to roll your 1st dice: ") == 'roll':
break
You can now call this where needed:
from random import randint
for i in range (1,6):
#while True: ## not sure why you have both, and this would make the indents wrong
print()
print("Player 1")
wait_for_right_input() #<-- here
dice1_1 = randint(1,6)
print("Player1 dice 1:", dice1_1)
wait_for_right_input() #<-- here
dice1_2 = randint(1,6)
print("Player1 Dice 2:", dice1_2)
# etc
If you want to loop until invalid input (I presume the reason for the while True and break) you can change the function to return a Boolean indicating whether to continue or not.
Related
I am completely new to coding and trying to write somewhat of a dice rolling program/game.
I want the program to ask how many dice the user wants to roll, and how many times they can "retry" to roll the dice per one game. After the user has rolled all of their tries the program jumps back to the first question.
So this is what i´ve got so far:
import random
def roll(dice):
i = 0
while i < dice:
roll_result = random.randint(1, 6)
i += 1
print("You got:", roll_result)
def main():
rolling = True
while rolling:
answer = input("To throw the dice press Y if you want to stop press any key")
if answer.lower() == "Y" or answer.lower() == "y":
number_of_die = int(input("How many dice do you want to throw? "))
roll(number_of_die)
else:
print("Thank you for playing!")
break
main()
This works but i am not sure though where to begin to make the program ask for how many tries one player gets per game so that if they are unhappy with the result they can roll again.
Been trying for a while to figure it out so appreciate any tips!
Here's a simpler approach-
from random import randint
def roll(n):
for i in range(n):
print(f"You got {randint(1, 6)}")
def main():
tries = int(input("Enter the number of tries each player gets: "))
dice = int(input("How many dice do you want to roll? "))
for j in range(tries):
roll(dice)
roll_again = input("Enter 'y' to roll again or anything else to quit: ")
if roll_again.lower() != 'y':
break
main()
How should I get the below loop to replay if the user types in an invalid response after being asked if they want to roll the dice again?
I can't get it to work without messing with the while loop. Here's what I have so far
# Ask the player if they want to play again
another_attempt = input("Roll dice again [y|n]?")
while another_attempt == 'y':
roll_guess = int(input("Please enter your guess for the roll: "))
if roll_guess == dicescore :
print("Well done! You guessed it!")
correct += 1
rounds +=1
if correct >= 4:
elif roll_guess % 2 == 0:
print("No sorry, it's", dicescore, "not", roll_guess)
incorrect += 1
rounds +=1
else:
print("No sorry, it's ", dicescore, " not ", roll_guess, \
". The score is always even.", sep='')
incorrect += 1
rounds +=1
another_attempt = input('Roll dice again [y|n]? ')
if another_attempt == 'n':
print("""Game Summary""")
else:
print("Please enter either 'y' or 'n'.")
I would suggest you do it with two while loops, and use functions to make the code logic more clear.
def play_round():
# Roll dice
# Compute score
# Display dice
# Get roll guess
def another_attempt():
while True:
answer = input("Roll dice again [y|n]?")
if answer == 'y':
return answer
elif answer == 'n':
return answer
else:
print("Please enter either 'y' or 'n'.")
def play_game():
while another_attempt() == 'y':
play_round()
# Print game summary
I have created a dice game which displays the scores at the end of each round. I would like to know how to separately add up the scores of both players so it displays the total score of 5 rounds.
This is the code below:
import random
import time
def bothDice():
count=0
while count<5:
count=count+1
score=0
print("Round",count)
print("Player One rolls first dice")
time.sleep(1)
dice1=(random.randint(1,6))
print("you rolled a ",dice1)
print("Player One rolls second dice")
time.sleep(1)
dice2=(random.randint(1,6))
print("you rolled a ",dice2)
score=dice1+dice2
if score%2==0:
score=score+10
if dice1==dice2:
print("You rolled a double- You get an extra roll")
for x in range (1):
print("You rolled a:")
extraDice=(random.randint(1,6))
print(extraDice)
extraScore = score+extraDice
score = extraScore
else:
score=score-5
print("======","Your combined score is ", score,"======")
score=0
print("Player Two rolls first dice")
time.sleep(1)
dice1=(random.randint(1,6))
print("you rolled a ",dice1)
print("Player Two rolls second dice")
time.sleep(1)
dice2=(random.randint(1,6))
print("you rolled a ",dice2)
score=dice1+dice2
if score%2==0:
score=score+10
if dice1==dice2:
print("You rolled a double- You get an extra roll")
for x in range (1):
print("You rolled a:")
extraDice=(random.randint(1,6))
print(extraDice)
extraScore = score+extraDice
score = extraScore
else:
score=score-5
print("======","Your combined score is ", score,"======")
def main():
bothDice()
main()
How would I make the scores of each round add together?
Thanks
I'd suggest you to re-write your code -- For instance, you can use a for loop instead of a while loop to keep track of rounds. I think use of dict or list is useful. I added two dictionaries for both players, result_p1 and result_p2 that store scores per round. The score can be negative (not sure if intended).
Here is the code below:
import random
import time
def bothDice():
count=0
# New dicts that store counts
result_p1 = {}
result_p2 = {}
while count<5:
count=count+1
score=0
print("Round",count)
print("Player One rolls first dice")
time.sleep(1)
dice1=(random.randint(1,6))
print("you rolled a ",dice1)
print("Player One rolls second dice")
time.sleep(1)
dice2=(random.randint(1,6))
print("you rolled a ",dice2)
score=dice1+dice2
if score%2==0:
score=score+10
else:
score=score-5
if dice1==dice2:
print("You rolled a double- You get an extra roll")
for x in range (1):
print("You rolled a:")
extraDice=(random.randint(1,6))
print(extraDice)
extraScore = score+extraDice
score = extraScore
print("======","Your combined score is ", score,"======")
# Store result of this round for player 1
if score != 0:
result_p1[count] = score
else:
result_p1[count] = 0
score=0
print("Player Two rolls first dice")
time.sleep(1)
dice1=(random.randint(1,6))
print("you rolled a ",dice1)
print("Player Two rolls second dice")
time.sleep(1)
dice2=(random.randint(1,6))
print("you rolled a ",dice2)
score=dice1+dice2
if score%2==0:
score=score+10
else:
score=score-5
if dice1==dice2:
print("You rolled a double- You get an extra roll")
for x in range (1):
print("You rolled a:")
extraDice=(random.randint(1,6))
print(extraDice)
extraScore = score+extraDice
score = extraScore
print("======","Your combined score is ", score,"======")
# Store result of this round for player 2
if score != 0:
result_p2[count] = score
else:
result_p2[count] = 0
# Print sum of results using f-string in python 3.
print(f"Player 1 scores: {result_p1}")
print(f"Player 2 scores: {result_p2}")
print(f"Sum of player 1 score: {sum(result_p1.values())}")
print(f"Sum of player 2 score: {sum(result_p2.values())}")
def main():
bothDice()
main()
This might be useful if my print statement didn't make sense.
Here is an output of the new print statements.
Player 1 scores: {1: 9, 2: 13, 3: 17, 4: 0, 5: 19}
Player 2 scores: {1: 17, 2: 13, 3: 13, 4: -2, 5: -2}
Sum of player 1 score: 58
Sum of player 2 score: 39
Edit: Added if statements before adding score to player dict to check if score is negative. If negative -> add 0 instead.
I am making a basic game 2 players 1-3 dice to be selectable than whoever rolls the highest number wins. How do i make this work using python
i am unsure how to loop the rolls and then be able to select quit, continue and to be able to select another number of dice to be rolled and goto the start screen. also what can be used to keep a score of this. This is the code i have.
i am also having trouble with the if commands how do i make the dice selectable from 1 to 3 without displaying all of the options
Dice = input("Please select number of dice you would like to use (1-3)")
if Dice == "1":
print("You have selected 1 dice")
import random
Roll1 = random.randrange(1,6)
print ("Player 1's Roll")
print(Roll1)
print ("Player 2's Roll")
print (Roll1)
#2 Dice Counter
if Dice == "2":
print("You have selected 2 dice")
import random
Roll2 = (random.randrange(2,12))
print ("Player 1's Roll")
print(Roll2)
print ("Player 2's Roll")
print (Roll22)
#3 Dice Counter
if Dice == "3":
print("You have selected 3 dice")
import random
Roll3 = random.randrange(3,18)
print ("Player 1's Roll")
print(Roll3)
print ("Player 2's Roll")
print (Roll3)
while invalid_input :
Dice()
Put your logic inside a function for example getDiceInput(), this will return if the user inputs a valid option, if the user inputs a valid input which is between (1-3) the result will be printed, otherwise an invalid input message will be printed, now keep calling the getDiceInput() inside the loop until user inputs -1 this will cause the loop while (inputValue != -1) to exit and goodbye message will be printed to exit, and use randint for generating random numbers, check following snippet :
from random import randint
def getDiceInput():
Roll1 = 0
Roll2 = 0
validInput = 1
Dice = input("Please select number of dice you would like to use (1-3) -1 to exit")
if Dice == "1":
print("You have selected 1 dice")
Roll1 = int(randint(1,6))
Roll2 = int(randint(1,6))
#2 Dice Counter
elif Dice == "2":
print("You have selected 2 dice")
Roll1 = int(randint(2,12))
Roll2 = int(randint(2,12))
#3 Dice Counter
elif Dice == "3":
print("You have selected 3 dice")
Roll1 = randint(3,18)
Roll2 = randint(3,18)
elif Dice == "-1":
validInput = -1
else :
print("invalid input reenter")
validInput = 0
if validInput == 1 :
print ("Player 1's Roll")
print(Roll1)
print ("Player 2's Roll")
print (Roll2)
return validInput
#Code execution will start here
inputValue = getDiceInput()
while (inputValue != -1):
inputValue = getDiceInput()
print("Goodbye")
Use the random module and the randint function.
from random import randint
Then to use it:
randint(0,10)
The above would generate a random integer between 0 and 10.
Looping
Use a while loop to loop the rolls.
condition = "play"
while condition == "play":
#Your code here
if(input("Enter 'play' to play again or 'quit' to stop the program and reveal the scores: ") == "quit"):
#Break out of the loop
break
else:
condition = "play"
For the if's
I would use some maths to generate the range of numbers in the randint or randrange. For example:
#Get input of dice to roll as integer
toRoll = int(input("Dice to roll: "))
#'Roll' the dice that many times
Roll = random.randrange(1*toRoll,6*toRoll)
Then use the Roll variable.
This will yield the same as using all the if statements (except the prints of course).
Hi i have done this random dice game and need help creating a loop that will let me when the user enters a invalid number I would like them to try again. Here is my code please help!
import random
dice = int(input("What sided dice do you want to use? (e.g. 4, 6 or 12): "))
if dice == 4:
random_number = int(random.randrange(1,4))
print ("You selected a 4 sided dice")
print ("Your dice has rolled ")
print (random_number)
elif dice == 6:
random_number2 = int(random.randrange(1,6))
print ("You selected a 6 sided dice")
print("Your dice has rolled ")
print (random_number2)
elif dice == 12:
random_number3 = int(random.randrange(1,12))
print ("You selected a 12 sided dice")
print("Your dice has rolled ")
print (random_number3)
else:
print(("You didn't select a valid sided dice, try again!"))*
You need two things for this:
A while loop, to keep going around until you get what you want; and
A collection of acceptable answers to check against.
For example, one simple solution would be to wrap your current input statement with:
dice = 0
while dice not in (4, 6, 12):
dice = ...
# continue
Use a while loop:
import random
dice = None
while dice not in (4, 6, 12):
dice = int(input("What sided dice do you want to use? (e.g. 4, 6 or 12): ")
if dice == 4:
random_number = int(random.randrange(1,4))
print ("You selected a 4 sided dice")
print ("Your dice has rolled ")
print (random_number)
elif dice == 6:
random_number2 = int(random.randrange(1,6))
print ("You selected a 6 sided dice")
print("Your dice has rolled ")
print (random_number2)
elif dice == 12:
random_number3 = int(random.randrange(1,12))
print ("You selected a 12 sided dice")
print("Your dice has rolled ")
print (random_number3)