迭代不迭代?

Iteration not Iterating?

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

这是我的资料:

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))

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

return roll的缩进有误。这导致函数在 1 次迭代后 return。

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

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

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 不一定要进行自己的验证。只要您获得整数输入,无论输入是否对应于“真实”芯片尺寸,工作都是相同的。 (使用 Die class 和 roll 方法将有助于防止在无效骰子上调用 roll,因为您可以防止创建 Die 的无效实例首先。)

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

然后你的循环,一旦它从 validate_date_input 得到一个值,就可以简单地用这个值调用 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))