我试图使我的骰子游戏,使它不是改变一个数字的骰子每卷它改变所有的

2024-05-23 15:02:17 发布

您现在位置:Python中文网/ 问答频道 /正文

所以问题在第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”


Tags: thein列表forifrange数字score
2条回答

将所有与个人骰子卷无关的物品移出第一个循环:

  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个骰子掷骰变量,并且可以让你随心所欲地改变骰子掷骰的数量,而无需重写任何东西

改变这个

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

为了这个

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

相关问题 更多 >