【发布时间】:2020-08-11 14:28:57
【问题描述】:
我的代码用于骰子游戏。它有五轮,并在每轮结束时将总数相加。我想找到一种方法,能够在玩家结束时将所有五个回合的总数相加。我在想最简单的方法是在每个循环结束时更改总变量的名称,例如。 roundtotal1、roundtotal2 等。但我不确定,我想看看你的想法。谢谢:)
我的代码:
import random
import time
p1 = ('Bob')
p2 = ('Larry')
#PLAYER 1'S TURN
print('Welcome to Dice Game,',p1)
#Prints round number of 5 rounds
for x in range (1,6):
round = ('%s' % x)
print('Round %s' % x)
time.sleep(0.5)
print()
#Rolls the first die
input('Press ENTER to roll your first die...')
num1 = random.randint(1,6)
time.sleep(0.5)
print('...')
time.sleep(1)
print('You scored a',num1,'on your first roll!\n')
#Rolls the second die
time.sleep(2)
input('Press ENTER to roll your second die...')
num2 = random.randint(1,6)
time.sleep(0.5)
print('...')
time.sleep(1)
print('You scored a',num2,'on your second roll!\n')
#If dice rolls 1 and 2 are the same, roll a third die
time.sleep(1)
num3 = 0
if num1 == num2:
num3 = random.randint(1,6)
print('As you rolled a double, you get a third die!')
input('Press enter to roll your third die...')
time.sleep(0.5)
print('...')
time.sleep(1)
print('You scored a',num3,'on your third roll!\n')
else:
pass
#Print the total for the round
time.sleep(1)
roundtotal = num1+num2+num3
print('ROUND TOTAL:',roundtotal)
print()
print()
print('GAME TOTAL:',) #Round totals from rounds 1-5 added together
#How do I do this?
【问题讨论】:
-
收集列表中的所有值?
-
在主循环之前的代码顶部,创建一个变量
grandtotal = 0。作为主循环的最后一步,将roundtotal 添加到grandtotal。
标签: python loops for-loop variables