Python: Lucky sevens game (Average number of dice rolls) - python

I'm trying to write a count function, to calculate the number of rolls it takes to hit 0. And it is returning me the random integer of the diceroll + 1, how do I get it to count the number of times the myroll variable occurs.
import random
def luckysevens():
mypot = int(input("Please enter the amount of money you want to in the pot: "))
while mypot > 0:
diceroll = random.randint(1, 6)
print(diceroll)
myroll = (diceroll + diceroll)
if myroll == 7:
mypot = mypot + 4
print("Your roll was a 7 you earned 4$", mypot)
else:
mypot = mypot - 1
print("Your roll was", myroll, "you lost 1$", mypot)
if mypot == 0:
print("Your out of money!")
sum = 0
for count in range(myroll + 1):
sum = sum + count
print(count)
luckysevens()

If you want to count how many rolls before the loop exits, simply add another counter variable. I also am assuming you're rolling a couple dice, so added different random calls for each one.
import random
mypot = int(input("Please enter the amount of money you want to in the pot: "))
num_rolls = 0
while mypot > 0:
die_1 = random.randint(1,6)
die_2 = random.randint(1,6)
myroll = die_1 + die_2
num_rolls += 1 # count rolls
if myroll == 7:
mypot = mypot + 4
print("Your roll was a 7 you earned 4$",mypot)
else:
mypot = mypot - 1
print("Your roll was",myroll,"you lost 1$",mypot)
if mypot == 0:
print("Your out of money!")
print 'Num rolls: {}'.format(num_rolls) # print rolls

Related

Repeated while loop with boolean

Sorry if this is considered spam, yet another issue I have is that this while loop runs unconditionally and I am not sure how to fix it.
Code:
while anotherNum == True:
playerNum = random.randint(1,10)
total = total + playerNum
print("")
print("Your number is ", str(playerNum) + ".")
print("You have " + str(total) + " in total.")
print("")
again = input("Roll another number? <Y or N> ")
print("")
if again == "Y":
anotherNum == True
else:
anotherNum == False
break
#game finished now
print("Computer got", pcNum)
print("You got", total)
#checking for winner
while anotherNum == False:
if (total <= 13) and (total > pcNum):
print("You,", name, "have won!")
elif (pcNum <= 13) and (pcNum > total):
print("The computer has bested you,", name + "!")
else:
if (total == pcNum) and (total <= 13):
print("Draw...")
elif (pcNum > 13) and (total <= 13):
print("You,", name + " have won!")
else:
print("Both of you have lost. Wow...")
Output:
Your number is 2.
You have 2 in total.
Roll another number? <Y or N> n
Your number is 3.
You have 3 in total.
Roll another number? <Y or N> N
Your number is 3.
You have 3 in total.
Roll another number? <Y or N> N
Your number is 9.
You have 9 in total.
Instead of going to the #game finished now comment's area, the while loop repeats the process whilst only disregarding the total = total + playerNum command.
You are not changing the valu
if again == "Y":
anotherNum == True
else:
anotherNum == False
break
You should use 1 equal sign as it is an assignment
if again == "Y":
anotherNum = True
else:
anotherNum = False
break
Your code (with minimal correction) is working just fine:
import random
total = 0
anotherNum = True
while anotherNum == True:
playerNum = random.randint(1,10)
total = total + playerNum
print("")
print("Your number is ", str(playerNum) + ".")
print("You have " + str(total) + " in total.")
print("")
again = input("Roll another number? <y or n> ")
print("")
if again == "y":
anotherNum = True
else:
anotherNum = False
break
print("You got", total)
The output that I get after running the code:
Your number is 7.
You have 7 in total.
Roll another number? <y or n> y
Your number is 9.
You have 16 in total.
Roll another number? <y or n> y
Your number is 10.
You have 26 in total.
Roll another number? <y or n> y
Your number is 2.
You have 28 in total.
Roll another number? <y or n> y
Your number is 6.
You have 34 in total.
Roll another number? <y or n> n
You got 34
Here's how I would do it.
while anotherNum:
playerNum = random.randint(1,10)
total += playerNum
print("")
print("Your number is ", str(playerNum) + ".")
print("You have " + str(total) + " in total.")
print("")
again = input("Roll another number? <Y or N> ")
print("")
anotherNum = (again == "Y")
this way you can avoid the if <blank> then true else false which caused you to make a mistake here (simple == instead of =)
Try to remove break and change == to =
import random
total = 0
anotherNum = True
while anotherNum == True:
playerNum = random.randint(1, 10)
total += playerNum
print("")
print(f"Your number is {playerNum}.")
print(f"You have {total} in total.")
print("")
again = input("Roll another number? <Y or N> ")
print("")
if again == "Y":
anotherNum = True # <- HERE
else:
anotherNum = False # <- HERE
OR without anotherNum variable:
import random
total = 0
while True:
playerNum = random.randint(1, 10)
total += playerNum
print("")
print(f"Your number is {playerNum}.")
print(f"You have {total} in total.")
print("")
again = input("Roll another number? <Y or N> ")
print("")
if again == 'N':
break

Trying to simulate 2 dice to know the percentage of same outcome

So, i think they is a logical error somewhere in the code.
The output keeps running 0% no matter any number i insert in the output terminal
#dice - count doubles in user - defined number of rounds.. repeated
import random
#simulate rolling a six sided die and return its value.
def rollOneDie():
#generate random numbers from 1 to 6
thisFace = random.randrange(1,7)
return thisFace
while True:
nDoubles = 0
maxRounds = input(
"how many rounds do you want to roll?(or ENTER to quit):")
if maxRounds == '':
break
try:
maxRounds = int(maxRounds)
except:
print("please an integer number")
continue
for roundNumbers in range(0, maxRounds):
die1 = rollOneDie()
die2 = rollOneDie()
if die1 == die2:
nDoubles = nDoubles + 1
percent = (nDoubles * 100.0) / maxRounds
print('out of ', maxRounds, 'you rolled',
nDoubles, 'doubles or ', percent, '%')
print('ok byeee')
The reason it prints 0% is that the if statement which checks if the dice are the same is outside the for loop that "rolls" the dice, so the nDoubles increases by 1 only if the dice are the same the last time you "roll" them.
The correct way is:
for roundNumbers in range(0, maxRounds):
die1 = rollOneDie()
die2 = rollOneDie()
if die1 == die2:
nDoubles = nDoubles + 1
Also, you can write:
nDoubles += 1
instead of
nDoubles = nDoubles + 1

How do I make the leaderboard section of the code work?

So I'm relatively new to python and I'm having issues with fixing the leaderboard part of the code. I've spent a lot of time but I haven't been able to make it work. I know there are a few examples of answers to the same question on stack overflow but so far none of them have worked. Is there any way to make it work?
#task2
import random #When the user rolls the dice this will give them a random number
import time #It'll pause the sequence for a specific amount of time
enter = 0 #the number of times a user enters Username and Password
tries = 0 #this is the number of times a user fails to enter the correct verification
rolling = 0 #this is the number of rounds the game continues to loop, which is 5
i = 0 #required for for...loop
rounds = 0 #this is for last while statements where the winner is decided
p1sc = 0 #for total score of player 1 which is added or taken away each round
p2sc = 0 #for total score of player 2 which is added or taken away each round
while enter == 0: #if enter becomes anything other than 0, the game will start
try:
leaderboard_list = [0,0,0,0,0,'-','-','-','-','-']
file = open('leaderboard.txt', 'x')
for item in leaderboard_list:
file.write('%s\n' % item)
file.close
except:
print("")
code = input("Input the authorization code to play this game: ")
if code == ("password"): #Checking whether the input code is "dice" or not
print("You have entered authorization code correctly, enjoy the game!")
player1 = input("What would Player 1 like to be called? ") #asking user 1 to input the name they want to be called
player2 = input("What would Player 2 like to be called? ") #asking user 2 to input the name they want to be called
print(player1,"and",player2 +", prepare to play, the game will now start...")
time.sleep(1)
enter = 1
else:
print("\nIncorrect authorization code please try again!")
tries = 1 + tries #required for next if statement
if tries == 4: #If user enters wrong password or username 4 times than the user have to wait 1 minute and try again until the user gets username and password correct
print("You have entered incorrect authorization code too many times, please try again after 1 minute!")
time.sleep(60) #For 1 minute the user won't be able to try again
tries = 0
else:
print()
if enter == 1:
for i in range(0,5): #this will allow the upcoming code to be looped only 5 times
while rolling == 0: #if rolling is 1 then player 2 has to roll the dices this continues, until i is in range(0,5)
p1 = input("\n"+ str(player1) +", press r to roll the dice: ")
if p1!= "r":
print()
else:
p1dice1 = random.randint(1,6) #allows any number to be chosen from 1 to 6
p1dice2 = random.randint(1,6)
p1dice3 = random.randint(1,6)
print("Rolling dice 1...")
time.sleep(1)
print("Dice 1 rolled a", p1dice1)
print("Rolling dice 2...")
time.sleep(1)
print("Dice 2 rolled a", p1dice2)
p1total = p1dice1 + p1dice2
rolling = 1 #for next while loop statement which is for player 2
if p1dice1 == p1dice2: #if statements according to the game rule
print("You rolled a double.Well done! You get to roll one more die.")
time.sleep(1)
print("Rolling dice 3...")
time.sleep(1)
print("Dice 3 rolled a", p1dice3)
p1total = p1total + p1dice3
else:
p1total = p1total
if p1total%2 == 0: #To check whether the number is odd or even
p1sc = p1sc + p1total + 10
print("You have total score as an even number. So,according to the game rule;your new total score now will be added by 10. Now,you have",p1sc,"as a total score.")
elif p1total%2 == 1:
p1sc = p1sc + p1total - 5 #after it is subtracted from 5, elif statement is used as only after subtracting the number; the number can be less than, equal or greater than 0
if p1sc == 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted 5. Now,you have",p1sc,"as a total score.")
elif p1sc < 0:
p1sc = 0
print("Your total score was subtracted by 5 and went below 0 but according to the game rule, the total score can't go below 0. So, your total score remains 0.")
elif p1sc > 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted by 5. Now,you have",p1sc,"as a total score.")
else:
print()
while rolling == 1: #if rolling is 0 then player 1 has to roll the dices this continues, until i is in range(0,5)
p2 = input("\n"+ str(player2) +", press r to roll the dice: ")
if p2!= "r":
print()
else:
p2dice1 = random.randint(1,6)
p2dice2 = random.randint(1,6)
p2dice3 = random.randint(1,6)
print("Rolling dice 1...")
time.sleep(1)
print("Dice 1 rolled a", p2dice1)
print("Rolling dice 2...")
time.sleep(1)
print("Dice 2 rolled a", p2dice2)
p2total = p2dice1 + p2dice2
rolling = 0 #for player 1 to roll the dices again
rounds = rounds + 1 #for the game to loop 5 times and be checked by upcoming while rounds == 5
if p2dice1 == p2dice2:
print("You rolled a double.Well done!You get to roll one more die.")
time.sleep(1)
print("Rolling dice 3...")
time.sleep(1)
print("Dice 3 rolled a", p2dice3)
p2total = p2total + p2dice3
else:
p2total = p2total
if p2total%2 == 0:
p2sc = p2sc + p2total + 10
print("You have total score as an even number. So,according to the game rule;your new total score now will be added by 10. Now,you have",p2sc,"as a total score.")
elif p2total%2 == 1:
p2sc = p2sc + p2total - 5
if p2sc == 0:
print("You have total score as an odd number. So,according to the rule;your new total score now will be subtracted 5. Now,you have",p2sc,"as a total score.")
elif p2sc < 0:
p2sc = 0
print("Your total score was subtracted by 5 and went below 0 but according to the game rule, the total score can't go below 0. So, your total score remains 0.")
elif p2sc > 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted by 5. Now,you have",p2sc,"as a total score.")
else:
print()
while rounds == 5:
while p1sc == p2sc:
print("\nAs you both have the same score, now you both will have to keep rolling 1 dice until someone wins!")
time.sleep(2)
p1 = input("\n"+ str(player1) +", press y to roll the dices: ")
if p1 != "y":
print()
else:
p1dice1 = random.randint(1,6)
print("Rolling the dice...")
time.sleep(1)
print("The dice rolled a", p1dice1)
p1total = p1dice1
if p1total%2 == 0:
p1sc = p1sc + p1total + 10
print("You have total score as an even number. So,according to the game rule;your new total score now will be added by 10.")
elif p1total%2 == 1:
p1sc = p1sc + p1total - 5
if p1sc == 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted 5.")
elif p1sc < 0:
p1sc = 0
print("Your total score was subtracted by 5 :(;(")
elif p1sc > 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted by 5.")
else:
print()
p2 = input("\n"+ str(player2) +", press y to roll the dices: ")
if p2 !="y":
print()
else:
p2dice1 = random.randint(1,6)
print("Rolling the dice...")
time.sleep(1)
print("The dice rolled a", p2dice1)
p2total = p2dice1
if p2total%2 == 0:
p2sc = p2sc + p2total + 10
print("You have total score as an even number. So,according to the game rule;your new total score now will be added by 10.")
elif p2total%2 == 1:
p2sc = p2sc + p2total - 5
if p2sc == 0:
print("You have total score as an odd number. So,according to the rule;your new total score now will be subtracted 5.")
elif p2sc < 0:
p2sc = 0
print("Your total score was subtracted by 5 :(;(")
elif p2sc > 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted by 5.")
else:
print()
if p1sc > p2sc:
time.sleep(1)
print("\nThe scores have been added up and....")
time.sleep(3)
print(str(player1)+" is the winner with "+str(p1sc)+" points.")
print(str(player2)+", better luck next time. Your total score is "+str(p2sc)+".")
rounds = 6 #to stop the loop
else:
time.sleep(1)
print("\nThe scores have been added up and....")
time.sleep(3)
print(str(player2)+" is the winner with "+str(p2sc)+" points.")
print(str(player1)+", better luck next time. Your total score is "+str(p1sc)+".")
rounds = 6 #to stop the loop
leaderboard_list = [] # Reads the highscore list
with open('leaderboard.txt') as reader:
for line in reader:
leaderboard_list.append(line.rstrip("\r\n"))
for j in range(0,4): #Converts the scores from the list into integers
leaderboard_list[j] = int(leaderboard_list[j])
for x in range(0,4): #Shuffles the list down depending on how high the scoore was
curr = leaderboard_list[x]
if leaderboard >= curr:
for i in range(5, x + 1, -1):
leaderboard_list[i + 4] = leaderboard_list[i + 3]
leaderboard_list[i - 1] = leaderboard_list[i - 2]
leaderboard_list[x] = leaderboard
leaderboard_list[(x + 5)] = winner
break
else:
pass
file = open('score.txt', 'w+') #Writes the updated highscore list into the txt file
for item in leaderboard_list:
file.write('%s\n' % item)
file.close()
print("""The highscores for this game are """) #Prints the highscore list
for x in range(5):
print(x + 1,") ", leaderboard_list[x], " by ", leaderboard_list[x + 5])
The error message:
Traceback (most recent call last):
File "main.py", line 190, in <module>
leaderboard_list[j] = int(leaderboard_list[j])
IndexError: list out of range
Thanks! Any help would be appreciated!
The relevant part of your code is this:
leaderboard_list = [] # Reads the highscore list
with open('leaderboard.txt') as reader:
for line in reader:
leaderboard_list.append(line.rstrip("\r\n"))
for j in range(0,4): #Converts the scores from the list into integers
leaderboard_list[j] = int(leaderboard_list[j])
When posting a question here, it's probably best to keep it small like that.
Anyway, you are iterating over range(0,4). This gives you:
[0, 1, 2, 3] as values for j.
So essentially, your for-loop is doing the following:
leaderboard_list[0] = int(leaderboard_list[0])
leaderboard_list[1] = int(leaderboard_list[1])
leaderboard_list[2] = int(leaderboard_list[2])
leaderboard_list[3] = int(leaderboard_list[3])
And this crashes with an IndexError.
That means that one (or all) of these indexes do not exist. The list is probably either empty, or less than 4 lines long.
The easiest way to debug this is to simply print the list before you do this operation:
print(*leaderboard_list)
And the operation that you're trying to do (turn them all into int values) can be done like this:
leaderboard_list = map(int, leaderboard_list)
Good luck on your Python journey!

Dice rolling program with counter

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")

keeping final point

I'm trying to write a program that allows the user to roll 2 dice and keep a running total of the points they have gained.
Update: Thank you so much, I figured it out :)
This solution worked:
import random
def roll_dice():
total = 0
while(True):
print ("Enter '1' to roll 2 dice, enter '2' to stop rolling")
user_input = input()
if user_input == '1':
d1 = random.randint(1,6)
d2 = random.randint(1,6)
print (d1, d2)
score = 0 # score this round
if d1 == d2:
score = 10
elif d1 == 6 or d2 == 6:
score = 4
elif d1 + d2 == 7:
score = 7
total += score # update total
print ("The score this round is ", score)
print ("The total number of points is", total)
elif user_input == '2':
print ("Thanks for playing!")
break
roll_dice()
Your line total = 0 resets total back to zero every time the two dice are rolled. Try putting total = 0 outside of your while loop.
subtotal = sum(both_dice) What is the purpose of this variable both_dice? Why is it a list? In your code, it can only contain one number or nothing at all.
This program should work. Please reason carefully line-by-line why this program works. Ask if anything is unclear.
import random
def roll_dice():
total = 0
while(True):
print ("Enter '1' to roll 2 dice, enter '2' to stop rolling")
user_input = str(input()) # str() needed for Python 2
if user_input == '1':
d1 = random.randint(1,6)
d2 = random.randint(1,6)
print (d1, d2)
score = 0 # score this round
if d1 == d2:
score = 10
elif d1 == 6 or d2 == 6:
score = 4
elif d1 + d2 == 7:
score = 7
total += score # update total
print ("The score this round is ", score)
print ("The total number of points is", total)
elif user_input == '2':
print ("Thanks for playing!")
break
roll_dice()
You can write the code in this manner.
import random
def roll_dice():
total = 0
while True:
print ("Enter '1' to roll 2 dice, enter '2' to stop rolling")
user_input = input()
if user_input == 1:
# Get die_one and die_two entry
die_one, die_two = random.randint(1,6), random.randint(1,6)
print ("Got %d in die_one and %d in die_two" % (die_one, die_two))
score = 0
if die_one == die_two:
score = 10
elif die_one == 6 or die_two ==6:
score = 4
elif die_one + die_two == 7:
score = 7
print ("The current score is %d" % score)
total += score
print ("The total score is %d " % total)
elif user_input == 2:
print ("Thanks for playing!")
break
if __name__ == "__main__":
roll_dice()
Without break statement.
import random
def roll_dice():
total = 0
flag = True
while flag:
print ("Enter '1' to roll 2 dice, enter '2' to stop rolling")
user_input = input()
if user_input == 1:
# Get die_one and die_two entry
die_one, die_two = random.randint(1,6), random.randint(1,6)
print ("Got %d in die_one and %d in die_two" % (die_one, die_two))
score = 0
if die_one == die_two:
score = 10
elif die_one == 6 or die_two ==6:
score = 4
elif die_one + die_two == 7:
score = 7
print ("The current score is %d" % score)
total += score
print ("The total score is %d " % total)
elif user_input == 2:
print ("Thanks for playing!")
flag = False
if __name__ == "__main__":
roll_dice()
Refactored using itertools to create the die and hoisting the scoring logic.
import random
import itertools as it
import collections as ct
def roll(n=2):
"""Return a random result of two die."""
return random.choice(list(it.product(range(1,7), repeat=n)))
def score(die):
"""Return a score for a given rule."""
if len(set(die)) == 1:
return 10
elif 6 in die:
return 4
elif sum(die) == 7:
return 7
else:
return 0
def dice_game():
"""Run game."""
total = 0
while True:
user_input = input("Enter '1' to roll two die. Enter '2' to stop rolling. ")
if user_input == "1":
result = roll()
pts = score(result)
total += pts
print("Result:", result)
print ("The score this round is", pts)
print ("The total number of points is", total)
print()
elif user_input == "2":
print ("Thanks for playing!")
return
dice_game()

Categories

Resources