0

我应该为以下问题编写代码:

玩家掷出两个六面骰子。如果两个骰子的总和不是 7,则总和将被添加到玩家的总分中,玩家可以再次滚动。当玩家掷出七的总和时,游戏结束。

这是我到目前为止所拥有的:

def main():
  dice1 = randrange(1, 7,)
  dice2 = randrange(1, 7,)

  roll = dice1 + dice2
  score = 0
  count = 0
  while roll != 7:
    count = count + 1
    score = score + roll
    if roll == 7:
     break
  print count
  print score

main()

然而,当它应该滚动骰子时,它只会给我一个无限循环,直到骰子的总和为 7。

我如何解决它?

4

4 回答 4

2

你没有更新roll;确保在循环中再次滚动:

roll = randrange(1, 7) + randrange(1, 7)
score = count = 0

while roll != 7:
    score += roll
    count += 1
    # re-roll the dice for the next round
    roll = randrange(1, 7) + randrange(1, 7)

一旦您分配dice1 + dice2roll,它本身不会在每个循环后“重新掷骰子”。

于 2013-10-06T00:34:26.580 回答
1

您需要在roll每次迭代时更新 的值。现在,roll永远不会改变,所以它永远不会等于 7(这意味着循环将永远运行)。

我想你希望你的代码是这样的:

from random import randrange
def main():

  # Note that the following two lines can actually be made one by doing:
  # score = count = 0
  score = 0
  count = 0

  # There is really no need to define dice1 and dice2
  roll = randrange(1, 7,) + randrange(1, 7,)

  # This takes care of exiting the loop when roll = 7
  # There is no need for that if block
  while roll != 7:

    # Note that this is the same as count = count + 1
    count += 1

    # And this is the same as score = score + roll
    score += roll

    # Update the value of roll
    # This is actually the line that fixes your problem
    roll = randrange(1, 7,) + randrange(1, 7,)

  print count
  print score

main()

另外,请注意我对脚本进行了一些更改以提高效率。

于 2013-10-06T00:34:01.483 回答
0

这是您问题的优雅解决方案:

from random import randint

count, score = 0, 0
while True:
    roll = randint(1,6) + randint(1,6)
    if roll == 7:
        break
    count += 1
    score += roll

print count, score
于 2013-10-06T06:11:31.190 回答
0

您必须在while循环 中获得新的骰子数量

def main():
      dice1 = randrange(1, 7,)
      dice2 = randrange(1, 7,)

      roll = dice1 + dice2
      score = 0
      count = 0
      while roll != 7:
        count = count + 1
        score = score + roll
        if roll == 7:
          break
        dice1 = randrange(1, 7,)
        dice2 = randrange(1, 7,)
        roll = dice1 + dice2
      print count    
      print score

main()
于 2013-10-06T00:34:21.487 回答