【问题标题】:Dice Roller for PythonPython的骰子滚轮
【发布时间】:2018-01-09 15:25:24
【问题描述】:

我正在尝试在 python 中制作一个掷骰子的程序,该程序根据用户在边、骰子和掷骰上的输入来掷骰子。目前这段代码或多或少有效,但我遇到的问题是说我给3 掷骰子36 边。

我的代码显示为输出:

Roll #1 6
Roll #2 5
Roll #3 1
Roll #4 6
Roll #5 4
Roll #6 6
Roll #7 3
Roll #8 1
Roll #9 1

当我需要它显示为:

Roll #1 6 5 1
Roll #2 6 4 6
Roll #3 3 1 1

到目前为止,这是我的代码。我的猜测是它必须与我的参数和参数为空有关?我不完全确定。这是我的代码:

import random

def main ():
    rolls = get_rolls()
    dice = get_dice()
    sides = get_sides()

    nrolls = 1
    for r in range (rolls):
        for d in range (dice):
            print ('Roll #', nrolls, random.randint(1,sides))
            nrolls += 1 

def get_rolls():
    rolls = int(input('Enter the number of rolls: '))
    while rolls <= 0:
        print ('Number of rolls must be higher than 0')
        rolls = int (input('Enter the number of rolls: '))
    return rolls

def get_dice():
    dice = int (input('Enter the number of dice being rolled: '))
    while dice < 1 or 5 < dice:
        print ('Number of dice being rolled must be between 1 and 5')
        dice = int (input('Enter the number of dice being rolled: '))
    return dice ()

def get_sides():
    sides = int (input('Enter the number of sides on the dice: '))
    while sides < 2 or 36 < sides:
        print ('Number of sides on dice must be between 2 and 36')
        sides = int (input('Enter the number of sides on the dice: '))
    return sides


main()        

【问题讨论】:

    标签: python nested-loops dice


    【解决方案1】:

    您的问题是您将print 语句放在内部for 循环中,这意味着您打印结果的次数过多,并且增加nrolls 的次数也过于频繁。

    nrolls = 1
    for r in range (rolls):
        roll = []
        for d in range (dice):
            roll.append(random.randint(1,sides))
        print('Roll #', nrolls, *roll)
        nrolls += 1
    >Roll # 1 3 3 1
    >Roll # 2 1 5 2
    >Roll # 3 6 5 4
    

    【讨论】:

      【解决方案2】:

      为了对您的代码进行最少的修改,请将其更改为:

      for r in range (rolls):
          print('Roll #', nrolls, end=' ')
          for d in range (dice):
              print (random.randint(1,sides), end=' ')
          print()
          nrolls += 1
      

      此外,以下行会引发错误。

      return dice ()
      

      改成:

      return dice
      

      【讨论】:

        【解决方案3】:
        import random
        
        def dice_roll(n):
        dicelist = ['\u2680','\u2681','\u2682','\u2683','\u2684','\u2685']
        dicevalue = {(dicelist[0]): 1, (dicelist[1]): 2, (dicelist[2]): 3, 
        (dicelist[3]): 4, (dicelist[4]): 5,(dicelist[5]): 6}
        result = 0
        visualresult = " "
        
        for i in range(n): 
            random_roll = random.sample((dicelist), 1)
            str1 = str(random_roll)
            str2 = str1.replace("'"," ")
            str3 = str2.replace("[", " ")
            str4 = str3.replace(']',' ')
            str5 = str4.strip()
            valueresultindex = dicelist.index(str5)
            valuelist = list(dicevalue.values())
            newvalueindex = valuelist[valueresultindex]
            result = result + newvalueindex
            visualresult = visualresult + str4
            i = i + 1
        
        rolledstring = "You rolled this much: "    
        print(visualresult)
        print((rolledstring) + str(result))
        
        Numofdice = int(input("Please enter the amount of dice you would like to 
        roll: "))
        
        if Numofdice >= 1 and Numofdice <= 6:
            ValidRollAmount = True
        else:
            ValidRollAmount = False
        
        while ValidRollAmount == False:
            Numofdice = int(input("Invalid amount of dice please re-enter: "))    
            if Numofdice >= 1 and Numofdice <= 6:
                ValidRollAmount = True
        
        while ValidRollAmount == True:
            dice_roll(Numofdice)
            ValidRollAmount = False
        

        【讨论】:

          【解决方案4】:

          您应该使用 while 循环来继续要求骰子,然后滚动该数量的骰子。

          例如

          import random
          from random import randint
          import string
          
          while True:
            str = input("What dice would you like to roll")
            prefix, d, suffix = str.partition("d")
            if str == "quit" or str == "q":
              break
            elif str.startswith("d"):
              print random.randint(1, int(suffix))
            elif str.startswith(prefix):
              for _ in range(int(prefix)):
                print (random.randint(1, int(suffix)))
            elif str.startswith("d"):
              print random.randint(1, suffix)
            else:
             print ("Keep rolling or type q or quit")
          
          print ("exiting")
          

          【讨论】:

            猜你喜欢
            • 2022-01-09
            • 2021-12-25
            • 1970-01-01
            • 2016-08-10
            • 2018-09-24
            • 1970-01-01
            • 2016-12-26
            • 2021-11-13
            • 2019-09-24
            相关资源
            最近更新 更多