A class used to represent a multi-sided die. Attributes: sides (int): The number of sides on the die (default is 6).
| 1 | import random |
| 2 | |
| 3 | class Die: |
| 4 | """ |
| 5 | A class used to represent a multi-sided die. |
| 6 | |
| 7 | Attributes: |
| 8 | sides (int): The number of sides on the die (default is 6). |
| 9 | """ |
| 10 | |
| 11 | def __init__(self, sides=6): |
| 12 | """Initializes the die. Defaults to 6 sides if no value is provided.""" |
| 13 | self.sides = 6 # Internal default |
| 14 | self.set_sides(sides) |
| 15 | |
| 16 | def set_sides(self, num_sides): |
| 17 | """ |
| 18 | Validates and sets the number of sides. |
| 19 | A physical die must have at least 4 sides. |
| 20 | """ |
| 21 | if isinstance(num_sides, int) and num_sides >= 4: |
| 22 | if num_sides != self.sides: |
| 23 | print(f"Changing sides from {self.sides} to {num_sides}!") |
| 24 | else: |
| 25 | print(f"Sides already set to {num_sides}.") |
| 26 | self.sides = num_sides |
| 27 | else: |
| 28 | print(f"Invalid input: {num_sides}. Keeping current value: {self.sides}") |
| 29 | |
| 30 | def roll(self): |
| 31 | """Returns a random integer between 1 and the number of sides.""" |
| 32 | return random.randint(1, self.sides) |
| 33 | |
| 34 | # --- Example Usage --- |
| 35 | if __name__ == "__main__": |