MCPcopy Create free account
hub / github.com/geekcomputers/Python / Die

Class Die

dice.py:3–32  ·  view source on GitHub ↗

A class used to represent a multi-sided die. Attributes: sides (int): The number of sides on the die (default is 6).

Source from the content-addressed store, hash-verified

1import random
2
3class 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 ---
35if __name__ == "__main__":

Callers 1

dice.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected