首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >迭代不迭代?

迭代不迭代?
EN

Stack Overflow用户
提问于 2022-05-18 14:01:50
回答 2查看 39关注 0票数 1

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

以下是我所拥有的:

代码语言:javascript
复制
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))

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-05-18 14:06:45

return roll的识别是错误的。这将导致函数在1次迭代后返回。

代码语言:javascript
复制
else: # This specifically is what I need help with
    for i in range(int(pos1)):
        roll = roll + dice(die_type)
    return roll
票数 2
EN

Stack Overflow用户

发布于 2022-05-18 14:33:15

将验证输入与实际尝试滚动骰子分开处理。

代码语言:javascript
复制
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

然后,滚动一个模具实际上与滚动多个骰子没有什么不同。把所有的都卷起来,把总数加起来。

代码语言:javascript
复制
def dice_roll(dice: Tuple[int, int]) -> int:
    n, s = dice
    return sum(die_roll(s) for _ in range(n))

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

代码语言:javascript
复制
def die_roll(sides: int) -> int:
    return random.randint(1, sides)

然后,一旦从validate_date_input获得一个值,您的循环就可以简单地用该值调用dice_roll

代码语言:javascript
复制
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))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72290635

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档