MrZJunior
MrZJunior

Reputation: 65

Iteration not Iterating?

I've been working a program for rolling dice. One of the things I wanted to do was have it roll a specific number of dice (i.e. 2d6). However, that part of the code does not seem to work, I think it only returns a single roll of the die.

Here is what I have:

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

So my question is, why does it not seem to iterate?

Upvotes: 1

Views: 101

Answers (2)

chepner
chepner

Reputation: 530843

Handle validating your input separately from actually trying to roll the dice.

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

Then, rolling a single die is really no different than rolling multiple dice. Roll all of them, and sum the total.

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

die_roll doesn't necessarily have to do its own validation. As long as you get an integer input, the work is the same whether the input corresponds to a "real" die size or not. (Having a Die class with a roll method would help prevent calling roll on invalid dice, as you can prevent an invalid instance of Die from being created in the first place.)

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

Then your loop, once it gets a value from validate_date_input, can simply call dice_roll with the value.

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

Upvotes: 0

Glitch__
Glitch__

Reputation: 304

The indentiation of return roll is wrong. This causes the function to return after 1 iteration.

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

Upvotes: 2

Related Questions