100 days of code: Day 34 - dice

Last modified on 2020-07-12

Source: 100-days-of-code.

Getting some object-oriented practice today by writing a little program that simulates rolling dice using the random module included with the Python standard library

"""A class to represent rolling dice."""


from random import randint


class Dice:
    """A simple attempt to represent dice."""
    
    def __init__(self, rolls=10, sides=6):
        # optional arguments
        self.rolls = rolls
        self.sides = sides 

    def roll_die(self):
        """Roll the dice x times."""
        print(f"\nRoll our {self.sides}-sided dice {self.rolls} times ...")
        for roll in range(0, self.rolls):
            print(randint(1, self.sides))


# Roll the default number of times with default sides
my_dice = Dice()
my_dice.roll_die()

# Roll 12 times
my_dice = Dice(12)
my_dice.roll_die()

# Roll a 10-sided die
my_dice = Dice(sides=10)
my_dice.roll_die()

# Roll 12 times with a 20-sided die
my_dice = Dice(12, 20)
my_dice.roll_die()

Happy hacking!