37 lines
866 B
Python
37 lines
866 B
Python
import re
|
|
from typing import Iterable
|
|
from random import randint
|
|
|
|
|
|
class Dice:
|
|
text: str
|
|
count: int
|
|
sides: int
|
|
|
|
def __init__(self, text: str):
|
|
self.text = text
|
|
parsed_text = self.parse_text(text)
|
|
if parsed_text is None:
|
|
raise DiceTextError(f"Could not parse {text}")
|
|
|
|
(self.count, self.sides) = parsed_text
|
|
|
|
def roll(self) -> Iterable[int]:
|
|
result = [randint(1, self.sides) for _ in range(self.count)]
|
|
print(f"rolling {self.text} => {result}")
|
|
return result
|
|
|
|
@staticmethod
|
|
def parse_text(text: str) -> tuple[int, int] | None:
|
|
match = re.match(r"^(\d*)d(\d+)$", text)
|
|
if match is None:
|
|
return None
|
|
|
|
count = match.group(1)
|
|
sides = match.group(2)
|
|
|
|
return (int(count), int(sides))
|
|
|
|
|
|
class DiceTextError(RuntimeError): ...
|