Skip to content

Commit ae285de

Browse files
committed
improved dice class logic and added validation
1 parent a4bfef6 commit ae285de

File tree

1 file changed

+29
-35
lines changed

1 file changed

+29
-35
lines changed

dice.py

Lines changed: 29 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,39 @@
1-
# Script Name : dice.py
2-
# Author : Craig Richards
3-
# Created : 05th February 2017
4-
# Last Modified :
5-
# Version : 1.0
6-
7-
# Modifications :
8-
9-
# Description : This will randomly select two numbers,
10-
# like throwing dice, you can change the sides of the dice if you wish
11-
121
import random
132

14-
15-
class Die(object):
16-
# A dice has a feature of number about how many sides it has when it's
17-
# established,like 6.
18-
def __init__(self):
19-
self.sides = 6
20-
21-
"""because a dice contains at least 4 planes.
22-
So use this method to give it a judgement when you need
23-
to change the instance attributes.
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).
249
"""
2510

26-
def set_sides(self, sides_change):
27-
if sides_change >= 4:
28-
if sides_change != 6:
29-
print("change sides from 6 to ", sides_change, " !")
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}!")
3024
else:
31-
# added else clause for printing a message that sides set to 6
32-
print("sides set to 6")
33-
self.sides = sides_change
25+
print(f"Sides already set to {num_sides}.")
26+
self.sides = num_sides
3427
else:
35-
print("wrong sides! sides set to 6")
28+
print(f"Invalid input: {num_sides}. Keeping current value: {self.sides}")
3629

3730
def roll(self):
31+
"""Returns a random integer between 1 and the number of sides."""
3832
return random.randint(1, self.sides)
3933

40-
41-
d = Die()
42-
d1 = Die()
43-
d.set_sides(4)
44-
d1.set_sides(4)
45-
print(d.roll(), d1.roll())
34+
# --- Example Usage ---
35+
if __name__ == "__main__":
36+
d1 = Die(4) # Initialize directly with 4 sides
37+
d2 = Die(12) # A Dungeons & Dragons classic
38+
39+
print(f"Roll Result: D{d1.sides} -> {d1.roll()}, D{d2.sides} -> {d2.roll()}")

0 commit comments

Comments
 (0)