sir-rollington/dice.py

47 lines
1.2 KiB
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]:
"""Randomly generates `self.count` integers in range [1,`self.sides`]"""
result = [randint(1, self.sides) for _ in range(self.count)]
print(f"rolling {self.text} => {result}")
return result
def roll_as_text(self) -> str:
"""
Randomly generates `self.count` integers in range [1,`self.sides`]
then returns a formated string.
"""
roll = self.roll()
result = f"{self.text} => {roll} = {sum(roll)}"
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): ...