Home > Software engineering >  How to add dice depending on a variable?
How to add dice depending on a variable?

Time:06-23

(Title is a work in progress. If you have any better suggestions, let me know.)

I am working on a Risk (board game) probability calculator. I have a generator which goes through every possible dice configuration to analyze it. I have an issue. I would like my code to be flexible enough that it can analyze many different amounts of dice. However, in order to do that, I would need to manually add a for loop for every extra die, to generate its rolls. My solution is such:

def generate_dice(dice_needed):
    # there are always at least two dice
    for first in range(1, 7):
        for second in range(1, 7):

            # if there are more, we keep going
            if dice_needed != 2:
                for third in range(1, 7):
                    if dice_needed != 3:
                        for fourth in range(1, 7):
                            if dice_needed != 4:
                                for fifth in range(1, 7):
                                    yield first, second, third, fourth, fifth
                            yield first, second, third, fourth
                    yield first, second, third
            yield first, second

There are two issues with this approach:

  • If I want to analyze more dice being thrown, I would need to physically add another for loop, which is obviously unsatisfactory.

  • This looks extremely clunky and unappealing.

Is there a better way to add dice amount flexibility into my code?

CodePudding user response:

You can use itertools.product():

from itertools import product

dice_needed = 2
for result in product(list(range(1, 7)), repeat=dice_needed):
    print(result)

This outputs (only first three / last three lines of output are shown below):

(1, 1)
(1, 2)
(1, 3)
...
(6, 4)
(6, 5)
(6, 6)
  • Related