我正在尝试制作我的骰子游戏,这样它就不会改变每次掷骰子的一个数字,而是改变所有的骰子

I am trying to make my dice game so that instead of it changing one of numbers of the dice each roll it changes all of them

所以问题出在第 9 行到第 32 行。它输出“3 0 0”,然后是“3 4 0”,然后是“3 4 6”。相反,它应该说“3 4 6”然后它可能是“6 1 2”。我知道这与 numRolled 变量及其循环方式有关,但我想不出还能把它放在哪里。

我试过将 numRolled = 0 放在 "for i in range(3)" 的末尾,但这只会让第一个数字发生变化。我试过将数字放入单个变量列表中,但我对列表中的编码不太有信心,所以我决定使用这里的内容。

def DiceGame():

  numRolled = 1
  RunScore = 0
  Roll1 = 0
  Roll2 = 0
  Roll3 = 0
  #rolls the 3 dice 100 times
  for x in range(100): 
    numRolled = 0
    #rolls the 3 dice
    for i in range(3):
      score = rdm.randint(1,6)
      numRolled += 1
      #assigns score to each die
      if numRolled == 1:
        Roll1 = score
      if numRolled == 2:
        Roll2 = score
      if numRolled == 3:
        Roll3 = score

      if Roll1 == Roll2 and Roll1 == Roll3:
        RunScore += 100
      else:
        DiceTot = Roll1 + Roll2 + Roll3
      # If Total of Die MOD 2 == 0 then Running score += Dice Total 
      if DiceTot % 2 == 0:
        RunScore += DiceTot
      else:
        RunScore -= DiceTot  
      print(Roll1, Roll2, Roll3)
      print(RunScore)

正如我上面所说,它输出“3 0 0”,然后是“3 4 0”,然后是“3 4 6”。相反,它应该说“3 4 6”然后它可能是“6 1 2”

改变这个

def game: 
    forlopp:
        forloop:
            print()
            print()

到这个

def game: 
    forlopp:
        forloop:
        print()
        print()

移动与个人无关的所有骰子滚出第一个循环:

  for x in range(100): 
    numRolled = 0
    #rolls the 3 dice
    for i in range(3):
      score = rdm.randint(1,6)
      numRolled += 1
      #assigns score to each die
      if numRolled == 1:
        Roll1 = score
      if numRolled == 2:
        Roll2 = score
      if numRolled == 3:
        Roll3 = score

    ####
    # Here the code below has been un-indented and removed from the range(3) loop
    ####

    if Roll1 == Roll2 and Roll1 == Roll3:
      RunScore += 100
    else:
      DiceTot = Roll1 + Roll2 + Roll3


      #####
      # Note: I have indented the following block to put it inside
      #       this "else" clause, so that it can use "DiceTot" reliably.
      #####

      # If Total of Die MOD 2 == 0 then Running score += Dice Total 
      if DiceTot % 2 == 0:
        RunScore += DiceTot
      else:
        RunScore -= DiceTot  
    print(Roll1, Roll2, Roll3)
    print(RunScore)

这应该可以修复代码。

但是,使用列表会更容易。您可以像这样生成 3 个骰子的列表:

rolls = []
for _ in range(3):
  rolls.append(rdm.randint(1,6))

也可以改写成列表推导式:

rolls = [rdm.randint(1,6) for _ in range(3)]

无论您做什么,都可以更轻松地生成统计信息:

if all(roll == rolls[0] for roll in rolls):
  RunScore += 100
else:
  DiceTot = sum(rolls)
  if DiceTot % 2 == 0:
    RunScore += DiceTot
  else:
    RunScore -= DiceTot

并且您可以使用 join 函数进行打印:

print(" ".join(rolls))

使用这样的列表可以让您摆脱 3 个掷骰子变量,并允许您随心所欲地更改掷骰子的数量而无需重写任何内容。