Я исправил и оптимизировал некоторые из ваших кодов.Я создал 2 помощника для повторяющихся задач:
import random
def askPlayAgain(text=""):
"""Ask for y or n, loop until given. Maybe add 'text' before the message."""
t = ""
while t not in {"y","n"}:
t = input("\n" + text + 'Would you like to play? [y/n]').strip()[0].lower()
return t
def getSumDices(n=2,sides=6):
"""Get sum of 'n' random dices with 'sides' sides"""
return sum(random.choices(range(1,sides+1),k=n)) # range(1,7) = 1,2,3,4,5,6
и немного изменил логику воспроизведения:
def play():
first_roll = 0
win = 0
lost = 0
yesOrno = askPlayAgain()
while yesOrno == 'y':
# dont need the individual dices - just the sum
# you can get both rolls at once
total = getSumDices()
print('You rolled a', total)
if total in {2,12}:
lost += 1
yesOrno = askPlayAgain("You lost! ")
elif total in {7,11}:
win += 1
yesOrno == askPlayAgain("You won! ")
else:
# remember last rounds result
first_roll = total
while True:
total = getSumDices()
print('You rolled a', total)
# this is kinda unfair, if you had 3 in your first round
# you cant win the second round at all ...
if total in {2,3,7,11,12}:
lost += 1
yesOrno = askPlayAgain("You lost! ")
break
elif total == first_roll:
win += 1
yesOrno = askPlayAgain("You won! ")
break
print('Thanks for playing!')
print('{} wins vs {} lost'.format(win,lost))
play()
Вывод:
Would you like to play? [y/n]y
You rolled a 10
You rolled a 12
You lost! Would you like to play? [y/n]y
You rolled a 9
You rolled a 7
You lost! Would you like to play? [y/n]y
You rolled a 7
You won! Would you like to play? [y/n]y
You rolled a 6
You rolled a 10
You rolled a 3
You lost! Would you like to play? [y/n]y
You rolled a 8
You rolled a 9
You rolled a 11
You lost! Would you like to play? [y/n]n
Thanks for playing!
1 wins vs 4 lost