python - 迭代不迭代?

我一直在做一个掷骰子的程序。我想做的一件事是让它掷出特定数量的骰子(即 2d6)。但是,那部分代码似乎不起作用,我认为它只返回一个骰子。

这是我所拥有的:

import random


# Format die rolls like so:  n dice d die size.  i.e. "4d6" will roll 4 six sided dice.
# You can also leave off the number of dice if you want to roll just one.

def die_roll(input_1):  # This is the dice rolling function
    roll = 0
    if "d" not in input_1:  # Should weed out most strings
        return "Not a valid die"
    splitter = input_1.split("d")  # should split the die roll into number of dice and die type
    die_type = splitter[1]  # Grabs the second item from the list created above and sets it to the type of die used
    pos1 = splitter[0]  # Tells you how many die to roll
    if pos1 == "":  # Puts a 1 in the multiplication place so that the math works in cases such as "d6" or "d4"
        pos1 = "1"
    if die_type not in ["4", "6", "8", "10", "12", "20", "100"]:  # Checks whether a valid die was indicated
        return "Not a valid die"
    else:
        if pos1 == "1":
            roll = dice(die_type)
            return roll
        else: # This specifically is what I need help with
            for i in range(int(pos1)):
                roll = roll + dice(die_type)
                return roll


def dice(roller):  # Rolls the actual dice.  Splitting it off here, theoretically, makes handling iteration.
    output = 0
    if roller == "4":
        output = random.randrange(1, 4)
    if roller == "6":
        output = random.randrange(1, 6)
    if roller == "8":
        output = random.randrange(1, 8)
    if roller == "10":
        output = random.randrange(1, 10)
    if roller == "12":
        output = random.randrange(1, 12)
    if roller == "20":
        output = random.randrange(1, 20)
    if roller == "100":
        output = random.randrange(1, 100)
    return output


while True:
    thing = input("What would you like to roll?")
    print(die_roll(thing))

所以我的问题是,为什么它似乎没有迭代?

回答1

return roll 的缩进是错误的。这会导致函数在 1 次迭代后返回。

else: # This specifically is what I need help with
    for i in range(int(pos1)):
        roll = roll + dice(die_type)
    return roll

回答2

与实际尝试掷骰子分开处理验证您的输入。

def validate_dice_input(s: str) -> Tuple[int, int]:
    try:
        n_dice, n_sides = s.split("d")
        n_dice = int(n_dice)
        n_sides = int(n_sides)
    except Exception:
        raise ValueError(f"Invalid dice input {s}")
    if n_dice < 0:
        raise ValueError(f"Cannot roll a negative number of dice ({n_dice})")

    if n_sides not in [4, 6, 8, 10, 12, 20, 100]:
        raise ValueError(f"Unknown die size '{n_sides}'")

    return n_dice, n_sides

那么,掷一个骰子实际上与掷多个骰子没有什么不同。将它们全部滚动,并将总数相加。

def dice_roll(dice: Tuple[int, int]) -> int:
    n, s = dice
    return sum(die_roll(s) for _ in range(n))

die_roll 不一定要进行自己的验证。只要您获得整数输入,无论输入是否对应于“真实”模具尺寸,工作都是相同的。 (拥有一个带有 roll 方法的 Die 类将有助于防止在无效骰子上调用 roll,因为您可以首先防止创建一个无效的 Die 实例。)

def die_roll(sides: int) -> int:
    return random.randint(1, sides)

然后你的循环,一旦它从 validate_date_input 得到一个 value,就可以简单地用 value 调用 dice_roll

while True:
    thing = input("What would you like to roll?")
    try:
        dice = validate_dice_input(thing)
    except ValueError as exc:
        print(exc)
        print("Try again")
        continue

    print(dice_roll(dice))

相似文章