所以我需要编写一个Python程序,我需要掷2个骰子并打印2个骰子的总和。我到目前为止得到了这个:
import random
def monopoly():
x = random.randrange(1,7)
y = random.randrange(1,7)
while True:
if x != y:
print(x, '+', y, '=', x+y)
break
现在,每次2个骰子数相同(2 + 2或3 + 3等)你可以再次投掷。如果骰子连续3次相同,你需要去监狱。我以为我必须使用这样的继续使用while循环:
else:
if x == y:
print(x + y)
continue
#continuation of the code above
现在,如果我确实有一个结果,骰子是相同的,它会一遍又一遍地打印掉这笔钱,直到我自己停止程序。但我不知道为什么。
我如何解决这个问题?因为我不知道如何做到这一点。
在每次循环迭代中需要新的随机数:
while True:
x = random.randrange(1,7)
y = random.randrange(1,7)
if x != y:
print(x, '+', y, '=', x+y)
break
否则,x
和y
永远不会改变,所以你的破坏条件永远不会成立。
程序继续循环的原因是因为它在while
循环中。
因为它始终是True
,没有办法打破循环。这可能在开始时很奇怪,但是当你看起来你会看到x
和y
在循环之外被定义,它们将始终是相同的。
因此在它们相同的情况下它们总是相同的。
您必须将x
和y
重新定义为else
部分中的不同变量,或者在while
语句的开头,以便为这两个变量生成新值,否则每次都会给出相同的值。
这是一个结构,你可以用来改变玩家轮流,在滚动之间,然后发送玩家到监狱滚动3双。对于双打,我们可以使用一个运行计数,如果它达到3将print('Go to jail')
。这是一个大致的想法,供您使用
from random import choice
from itertools import cycle
die = [1, 2, 3, 4, 5, 6]
doubles = 0
players = cycle(['player1', 'player2'])
turn = iter(players)
player = next(turn)
while True:
x, y = choice(die), choice(die)
if x == y:
print(f'{player} folled {x + y}, Doubles!')
print(f'It is {player}\'s turn\n')
doubles += 1
else:
doubles = 0
print(f'{player} rolled {x + y}')
player = next(turn)
print(f'It is {player}\'s turn\n')
if doubles == 3:
print(f'{player} rolled 3 Doubles! Go to jail.\n')
player = next(turn)
break
player1 rolled 3 It is player2's turn player2 rolled 3 It is player1's turn player1 folled 12, Doubles! It is player1's turn player1 folled 10, Doubles! It is player1's turn player1 folled 2, Doubles! It is player1's turn player1 rolled 3 Doubles! Go to jail.