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)
Related
I'm new to programming and I have a task that I can't figure out on my own.
The task is to make a program that let's you decide how many dices to throw, 1 to 5, with checking if you make a wrong input.
After every roll the number of the die will show and the total so far.
If the die rolls a 6 then it is not included in the total and you get to more rolls. This is where I'm stuck. I want my program to restart the loop if the die turns a 6 and just ad 2 rolls to the sumDices and continue the loop, but I can't get it to work.
here is my code:
import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
exit=False
reset=False
while True:
while True:
numDices=int(input("How many dices to throw? (1-5) "))
if numDices<1 or numDices>5:
print("Wrong input, try again")
break
while True:
if reset==True:
break
for i in range(numDices):
dicesArray = list(range(numDices))
dicesArray[i] = random.randint(1, 6)
print(dicesArray[i])
total += dicesArray[i]
if dicesArray[i] == 1:
print("You rolled a one, the total is: ",str(total))
elif dicesArray[i] == 2:
print("You rolled a two, the total is: ",str(total))
elif dicesArray[i] == 3:
print("You rolled a three, the total is: ",str(total))
elif dicesArray[i] == 4:
print("You rolled a four, the total is: ",str(total))
elif dicesArray[i] == 5:
print("You rolled a five, the total is: ",str(total))
elif dicesArray[i] == 6:
total-=6
numDices+=2
print("You rolled a six, rolling two new dices")
reset=True
print("The total sum is",str(total),"with",numDices,"number of rolls.")
print()
restart=(input("Do you want to restart press Enter, to quit press 9. "))
if restart=="9":
exit=True
break
else:
print()
break
if exit==True:
break
You could do it the following way, slightly modifying your code, counting the available dices. I reduced the nested loops there too
import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
start = True
while start:
numDices=int(input("How many dices to throw? (1-5) "))
if numDices<1 or numDices>5:
print("Wrong input, try again")
break
total = 0
dices_counter = 0
while numDices > 0 :
eyes = random.randint(1, 6)
dices_counter+=1
total += eyes
if eyes == 1:
print("You rolled a one, the total is: ",str(total))
numDices-=1
elif eyes == 2:
print("You rolled a two, the total is: ",str(total))
numDices-=1
elif eyes == 3:
print("You rolled a three, the total is: ",str(total))
numDices-=1
elif eyes == 4:
print("You rolled a four, the total is: ",str(total))
numDices-=1
elif eyes == 5:
print("You rolled a five, the total is: ",str(total))
numDices-=1
elif eyes == 6:
total-=6
numDices+=2
print("You rolled a six, rolling two new dices")
print("The total sum is",str(total),"with",dices_counter,"number of rolls.")
print()
start=(input("Do you want to restart press Enter, to quit press 9. "))
if start=="9":
break
else:
print()
start = True
To solve your problem I would replace your current for loop with a while loop
Moreover, I see a lot of unacessary things in your code, I will try to list them :
Why do you use so many "while True"?
Why don't you just use exit() function to exit instead of using a
variable?
Is all the if part really necessary, can't you just print the
number?
Here's my proposal:
import random
remaining_dices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
while True:
remaining_dices=int(input("How many dices to throw? (1-5) "))
if remaining_dices<1 or remaining_dices>5:
print("Wrong input, try again")
break
dicesArray = list()
while remaining_dices>0:
dice_value = random.randint(1, 6)
dicesArray.append(dice_value)
print(dice_value)
total += dice_value
remaining_dices -= 1
if(dice_value == 6):
total-=6
remaining_dices +=2
print("You rolled a 6, rolling two new dices")
else:
print("You rolled a " + str(dice_value) + ", the total is : " +str(total))
restart=(input("Do you want to restart press Enter, to quit press 9. "))
if restart=="9":
exit()
else:
print()
for i in range(numDices):
Your for loop limits the number of iterations as soon as range(numDices) is evaluated/executed. When you attempt to increase the number of iterations with numDices+=2 it does not have any effect because range(numDices) is only evaluated once.
If you want to be able to change the number of iterations, use another while loop and use i as a counter. Something like.
i = 0
while i <= numDices:
...
...
if ...:
...
elif ...:
...
i += 1
Then in the suite for elif dicesArray[i] == 6: the statement numDices += 2 will effectively increase the number of iterations.
I see another problem that you haven't mentioned. You start with a fixed length list based on the original value of numDices and you use i as an index for that list.
dicesArray = list(range(numDices))`
...
dicesArray[i]
...
If i can potentially be greater than the original numDices (greater than len(dicesArray)) you will eventually get an IndexError. You should probably start with an empty list and append to it. To get the most recent dice roll use dicesArray[-1] instead of dicesArray[i].
...
dicesArray = []
i = 0
while i <= numDices:
dicesArray.append(random.randint(1, 6))
total += dicesArray[-1]
if dicesArray[-1] == 1:
...
...
6.3.2. Subscriptions
Using a recursive function
import random
total = 0
diceRollList = []
# Define dice rolling function
def rollDice():
rollResult = random.randint(1, 6)
if rollResult == 6:
# If 6 Rolled run two more rolls and sum the results
print("Rolled a 6 Rolling 2 more")
return sum([rollDice() for _ in range(2)])
# If 6 not rolled return the result
print(f"Rolled a {rollResult}")
return rollResult
while True:
numberOfDice = int(input("How many Die to throw: "))
if numberOfDice not in range(1, 6):
print("Number of dice should be between 1 and 5")
break
for dice in range(numberOfDice):
print(f"Rolling Dice {dice}")
# Add result to the total
total += rollDice()
print(f"Running Total: {total}")
This one tracks how many it has rolled:
import random
a = int(0)
b = int(0)
c = int(0)
d = int(0)
e = int(0)
f = int(0)
limit = 101
count = 0
while True:
g = (random.randint(1, 6))
print(g)
count += 1
if g == 1:
a += 1
elif g == 2:
b += 1
elif g == 3:
c += 1
elif g == 4:
d += 1
elif g == 5:
e += 1
elif g == 6:
f += 1
if count > limit:
break
print(f"There are {a} 1's")
print(f"There are {b} 2's")
print(f"There are {c} 3's")
print(f"There are {d} 4's")
print(f"There are {e} 5's")
print(f"There are {f} 6's")
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 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.
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).
Doing a dice Rolling game in python, and whenever I start my second round I still end up getting the same dice results from the previous round.
import random
import time
#gets the dice side
def roll_dice(sides):
dice_results = list()
for side in sides:
roll_result = random.randint(1,side+1)
dice_results.append(roll_result)
return dice_results
#pulls a dice out from the list
def dice_fell(roll_result):
player1_dice = player1_dice_results
player2_dice = player2_dice_results
for item in player1_dice:
if item % 4 == 0:
player1_dice.remove(item)
return player1_dice
for item in player2_dice:
if item % 4 == 0:
player2_dice.remove(item)
return player2_dice
# variables
dice_set1=[4, 6, 8, 10, 12, 20, 100]
dice_set2=[4, 6, 8, 10, 12, 20, 100]
player1_dice_results = roll_dice(dice_set1)
player2_dice_results = roll_dice(dice_set2)
player1_final_results = dice_fell(player1_dice_results)
player2_final_results = dice_fell(player2_dice_results)
player1_total= sum(player1_dice_results)
player2_total= sum(player2_dice_results)
player1_score = 0
player2_score = 0
while player1_score < 3 or player2_score < 3:
# This part just announces what happens
exit= input(str("Press Enter to start! Press 'q' to leave after each round! \n"))
if exit != "q":
print("Let's begin! Be careful for the small table!")
elif exit == "q":
quit()
print("You are rolling...")
time.sleep(2)
print("You have rolled: ",player1_final_results)
if len(player1_final_results) < 7:
print("Sorry player 1, some of your dice have fallen off the table!")
print()
print("Your total is: ",player1_total)
print()
print("Player 2 is rolling...")
time.sleep(2)
print("Player 2 has rolled:" ,player2_final_results)
if len(player2_final_results) < 7:
print("Sorry player 2, some of your dice have fallen off the table!")
print()
print("Player 2's total is: ",player2_total)
print()
if player1_total > player2_total:
print()
print("You have won the round with,",player1_total,"!"),
player1_score += 1
print("Your score is: ",player1_score)
elif player2_total > player1_total:
print()
print("Player 2 has won the round with,",player2_total,"!"),
player2_score += 1
print("Player 2's score is: ",player2_score)
if player1_score == 3:
print("Congratulations, you won!")
elif player2_score == 3:
print("Player 2 wins! Better luck next time champ!")
I believe that I've fixed the indentation problems.
I have reproduced the problem.
As Kevin said, your immediate problem is that you roll the dice only once, before you enter your while loop. Here's what it looks like with the rolls inside the loop, but after the player decides whether to continue.
dice_set1=[4,6,8,10,12,20,100]
dice_set2=[4,6,8,10,12,20,100]
player1_score = 0
player2_score = 0
while player1_score < 3 or player2_score < 3:
# This part just announces what happens
exit = raw_input(str("Press Enter to start! Press 'q' to leave after each round! \n"))
if exit != "q":
print("Let's begin! Be careful for the small table!")
elif exit == "q":
quit()
player1_dice_results = roll_dice(dice_set1)
player2_dice_results = roll_dice(dice_set2)
player1_final_results = dice_fell(player1_dice_results)
player2_final_results = dice_fell(player2_dice_results)
player1_total= sum(player1_dice_results)
player2_total= sum(player2_dice_results)
print("You are rolling...")
... # remainder of code omitted
That said, do note that you have several other problems with the program. You won't terminate until both players have won three times -- use and instead of or in the while condition.
Most of my other comments are more appropriate for the codeReview group; you might post there when you're done debugging.