319 lines
15 KiB
Python
319 lines
15 KiB
Python
from __future__ import annotations
|
||
|
||
from dataclasses import dataclass, field
|
||
from difflib import SequenceMatcher
|
||
from math import ceil, isfinite
|
||
import re
|
||
from typing import Literal
|
||
|
||
"""
|
||
Ядро бизнес-логики:
|
||
- Валидация и парсинг данных
|
||
- Расчёт баллов за тренировки (ЛУ, ЗУ), тренировки и осмотры
|
||
"""
|
||
|
||
# --- Типы-константы для валидации ввода ---
|
||
Independence = Literal["самостоятельно", "несамостоятельно"]
|
||
Skill = Literal["ЛУ", "ЗУ"]
|
||
Place = Literal["дупло", "расщелина"]
|
||
|
||
_CLOCK_RE = re.compile(r"^(?:[01]\d|2[0-3]):[0-5]\d$")
|
||
|
||
# The goal calculator is public. These limits keep accidental and hostile
|
||
# values from turning a simple estimate into an unbounded exponentiation.
|
||
MAX_GOAL_MINUTES_PER_SESSION = 24 * 60
|
||
MAX_GOAL_KITTENS = 50
|
||
MAX_COACHING_KITTENS = 50
|
||
MAX_INSPECTIONS = 100_000
|
||
MAX_INSPECTION_RESOURCES = 100
|
||
MAX_RESOURCE_AMOUNT = 100_000
|
||
|
||
|
||
def parse_clock(value: str) -> int:
|
||
"""Преобразует строку 'HH:MM' в количество минут от начала суток."""
|
||
if not isinstance(value, str) or not _CLOCK_RE.fullmatch(value):
|
||
raise ValueError("Время должно быть в формате HH:MM, например 05:07")
|
||
hours, minutes = value.split(":")
|
||
return int(hours) * 60 + int(minutes)
|
||
|
||
|
||
def format_clock(minutes: int) -> str:
|
||
"""Преобразует количество минут от начала суток обратно в строку 'HH:MM'."""
|
||
if not isinstance(minutes, int) or not 0 <= minutes < 24 * 60:
|
||
raise ValueError("Время должно быть минутами внутри суток")
|
||
return f"{minutes // 60:02d}:{minutes % 60:02d}"
|
||
|
||
|
||
def _positive_id(value: int, label: str) -> int:
|
||
"""Проверяет, что значение — положительное целое число."""
|
||
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
||
raise ValueError(f"{label} должен быть положительным целым числом")
|
||
return value
|
||
|
||
|
||
def _points(value: float) -> float | int:
|
||
"""Округляет баллы до двух знаков после запятой; целые — возвращает int."""
|
||
if value.is_integer():
|
||
return int(value)
|
||
return round(value, 2)
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class CoachingSession:
|
||
"""Сессия тренировки навыка ЛУ или ЗУ."""
|
||
date: str
|
||
skill: Skill
|
||
start: str
|
||
end: str
|
||
escort_name: str
|
||
escort_id: int
|
||
kitten_name: str
|
||
kitten_id: int
|
||
kitten_independence: Independence = "самостоятельно"
|
||
extra_kittens: tuple[tuple[str, int, Independence], ...] = field(default_factory=tuple)
|
||
|
||
def __post_init__(self) -> None:
|
||
"""Валидирует данные сессии при создании."""
|
||
if self.skill not in ("ЛУ", "ЗУ"):
|
||
raise ValueError("Навык должен быть ЛУ или ЗУ")
|
||
parse_clock(self.start)
|
||
parse_clock(self.end)
|
||
for value, label in (
|
||
(self.escort_name, "Имя сопровождающего"),
|
||
(self.kitten_name, "Имя котёнка"),
|
||
(self.date, "Дата"),
|
||
):
|
||
if not isinstance(value, str) or not value.strip():
|
||
raise ValueError(f"{label} не может быть пустым")
|
||
_positive_id(self.escort_id, "ID сопровождающего")
|
||
_positive_id(self.kitten_id, "ID котёнка")
|
||
if self.kitten_independence not in ("самостоятельно", "несамостоятельно"):
|
||
raise ValueError("Некорректный статус самостоятельности")
|
||
for name, kitten_id, independence in self.extra_kittens:
|
||
if not name.strip():
|
||
raise ValueError("Имя дополнительного котёнка не может быть пустым")
|
||
_positive_id(kitten_id, "ID дополнительного котёнка")
|
||
if independence not in ("самостоятельно", "несамостоятельно"):
|
||
raise ValueError("Некорректный статус самостоятельности")
|
||
if 1 + len(self.extra_kittens) > MAX_COACHING_KITTENS:
|
||
raise ValueError(f"В одном заходе может участвовать не более {MAX_COACHING_KITTENS} котят")
|
||
statuses = (self.kitten_independence,) + tuple(independence for _, _, independence in self.extra_kittens)
|
||
nonself_count = sum(status == "несамостоятельно" for status in statuses)
|
||
if self.skill == "ЗУ" and any(s != "самостоятельно" for s in statuses):
|
||
raise ValueError("Для ЗУ все котята должны быть самостоятельными")
|
||
if self.skill == "ЛУ" and nonself_count > 1:
|
||
raise ValueError("Для ЛУ допускается только один несамостоятельный котёнок")
|
||
|
||
@staticmethod
|
||
def duration_minutes(start: str, end: str) -> int:
|
||
"""Вычисляет длительность сессии в минутах (учитывает переход через полночь)."""
|
||
start_minutes = parse_clock(start)
|
||
end_minutes = parse_clock(end)
|
||
return (end_minutes - start_minutes) % (24 * 60)
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class CoachingResult:
|
||
"""Результат расчёта баллов за тренировку навыка."""
|
||
minutes: int
|
||
escort_points: float | int
|
||
kitten_points: float | int
|
||
kitten_count: int = 1
|
||
escort_multiplier: float = 1.0
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class GoalResult:
|
||
"""Результат обратного расчёта цели по баллам."""
|
||
current_points: float | int
|
||
target_points: float | int
|
||
remaining_points: float | int
|
||
minutes_per_session: int
|
||
points_per_session: float | int
|
||
sessions: int
|
||
total_minutes: int
|
||
total_hours: float | int
|
||
|
||
|
||
def calculate_goal(
|
||
*,
|
||
current_points: float,
|
||
target_points: float,
|
||
minutes_per_session: int,
|
||
skill: Skill = "ЛУ",
|
||
kitten_independence: Independence = "самостоятельно",
|
||
kitten_count: int = 1,
|
||
) -> GoalResult:
|
||
"""Рассчитывает, сколько времени нужно до целевого числа баллов."""
|
||
for value, label in ((current_points, "Текущие баллы"), (target_points, "Целевые баллы")):
|
||
if isinstance(value, bool) or not isinstance(value, (int, float)) or not isfinite(value):
|
||
raise ValueError(f"{label} должны быть конечным числом")
|
||
if skill not in ("ЛУ", "ЗУ"):
|
||
raise ValueError("Навык должен быть ЛУ или ЗУ")
|
||
if kitten_independence not in ("самостоятельно", "несамостоятельно"):
|
||
raise ValueError("Некорректный статус самостоятельности")
|
||
if current_points < 0 or target_points < 0:
|
||
raise ValueError("Баллы не могут быть отрицательными")
|
||
if isinstance(minutes_per_session, bool) or not isinstance(minutes_per_session, int) or not 0 < minutes_per_session <= MAX_GOAL_MINUTES_PER_SESSION:
|
||
raise ValueError(f"Продолжительность захода должна быть целым числом от 1 до {MAX_GOAL_MINUTES_PER_SESSION} минут")
|
||
if isinstance(kitten_count, bool) or not isinstance(kitten_count, int) or not 0 < kitten_count <= MAX_GOAL_KITTENS:
|
||
raise ValueError(f"Количество котят должно быть целым числом от 1 до {MAX_GOAL_KITTENS}")
|
||
if skill == "ЗУ" and kitten_independence != "самостоятельно":
|
||
raise ValueError("Для ЗУ котёнок должен быть самостоятельным")
|
||
|
||
ward_multiplier = 1.0 if kitten_count == 1 else 1.5 * (1.15 ** (kitten_count - 2))
|
||
nonself_bonus = minutes_per_session * 0.5 / 5 if kitten_independence == "несамостоятельно" else 0
|
||
points_per_session = _points(minutes_per_session * ward_multiplier / 5 + nonself_bonus)
|
||
remaining = _points(max(target_points - current_points, 0))
|
||
sessions = 0 if remaining == 0 else ceil(remaining / points_per_session)
|
||
total_minutes = sessions * minutes_per_session
|
||
total_hours_value = total_minutes / 60
|
||
total_hours = int(total_hours_value) if total_hours_value.is_integer() else round(total_hours_value, 2)
|
||
return GoalResult(
|
||
current_points=_points(current_points), target_points=_points(target_points),
|
||
remaining_points=remaining, minutes_per_session=minutes_per_session,
|
||
points_per_session=points_per_session, sessions=sessions,
|
||
total_minutes=total_minutes, total_hours=total_hours,
|
||
)
|
||
|
||
|
||
def calculate_coaching(session: CoachingSession) -> CoachingResult:
|
||
"""
|
||
Рассчитывает баллы за сессию тренировки.
|
||
|
||
Множитель зависит от самостоятельности котёнка:
|
||
- самостоятельно → 2.0x к базовому расчёту
|
||
- несамостоятельно → 1.5x к базовому расчёту
|
||
|
||
Если котят несколько, каждый дополнительный получает
|
||
сниженный множитель (1.5x для второго, 1.15x для каждого следующего).
|
||
"""
|
||
minutes = session.duration_minutes(session.start, session.end)
|
||
if minutes <= 0:
|
||
raise ValueError("Продолжительность захода должна быть больше нуля")
|
||
|
||
kitten_count = 1 + len(session.extra_kittens)
|
||
# Several wards share one report: the second ward pays 1.5x, and each
|
||
# following ward adds a further 1.15x multiplier instead of another full
|
||
# base payout.
|
||
ward_multiplier = 1.0 if kitten_count == 1 else 1.5 * (1.15 ** (kitten_count - 2))
|
||
# The independence bonus applies to every skill, including зоркость (ЗУ),
|
||
# and is calculated separately for each non-independent kitten.
|
||
nonself_count = (session.kitten_independence == "несамостоятельно") + sum(
|
||
independence == "несамостоятельно" for _, _, independence in session.extra_kittens
|
||
)
|
||
nonself_bonus = minutes * 0.5 * nonself_count / 5
|
||
|
||
return CoachingResult(
|
||
minutes=minutes,
|
||
escort_points=_points(minutes * ward_multiplier / 5 + nonself_bonus),
|
||
kitten_points=_points(minutes / 5),
|
||
kitten_count=kitten_count,
|
||
escort_multiplier=round(ward_multiplier, 4),
|
||
)
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class TrainingSession:
|
||
"""Сессия тренировки (обучения)."""
|
||
escort_name: str
|
||
escort_id: int
|
||
kitten_name: str
|
||
kitten_id: int
|
||
|
||
def __post_init__(self) -> None:
|
||
"""Валидирует данные сессии тренировки."""
|
||
if not self.escort_name.strip() or not self.kitten_name.strip():
|
||
raise ValueError("Имена участников не могут быть пустыми")
|
||
_positive_id(self.escort_id, "ID сопровождающего")
|
||
_positive_id(self.kitten_id, "ID котёнка")
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class TrainingResult:
|
||
"""Результат тренировки — фиксированные 25 баллов."""
|
||
points: int = 25
|
||
|
||
|
||
def calculate_training(session: TrainingSession) -> TrainingResult:
|
||
"""Тренировка всегда даёт 25 баллов."""
|
||
return TrainingResult()
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class InspectionReport:
|
||
"""Отчёт об осмотре локации (дупло или расщелина)."""
|
||
character_name: str
|
||
character_id: int
|
||
place: Place
|
||
inspections: int
|
||
resources: tuple[tuple[str, int], ...] = field(default_factory=tuple)
|
||
|
||
def __post_init__(self) -> None:
|
||
"""Валидирует данные отчёта об осмотре."""
|
||
if not self.character_name.strip():
|
||
raise ValueError("Имя персонажа не может быть пустым")
|
||
_positive_id(self.character_id, "ID персонажа")
|
||
if self.place not in ("дупло", "расщелина"):
|
||
raise ValueError("Место должно быть дуплом или расщелиной")
|
||
if isinstance(self.inspections, bool) or not isinstance(self.inspections, int) or not 0 <= self.inspections <= MAX_INSPECTIONS:
|
||
raise ValueError(f"Количество осмотров должно быть целым числом от 0 до {MAX_INSPECTIONS}")
|
||
if len(self.resources) > MAX_INSPECTION_RESOURCES:
|
||
raise ValueError(f"В одном отчёте может быть не более {MAX_INSPECTION_RESOURCES} ресурсов")
|
||
for name, amount in self.resources:
|
||
if not name.strip() or not isinstance(amount, int) or not 0 <= amount <= MAX_RESOURCE_AMOUNT:
|
||
raise ValueError(f"Ресурс должен иметь название и количество от 0 до {MAX_RESOURCE_AMOUNT}")
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class InspectionResult:
|
||
"""Результат расчёта баллов за осмотр."""
|
||
points: int
|
||
|
||
|
||
def _inspection_resource_value(name: str) -> int:
|
||
"""
|
||
Определяет ценность ресурса для осмотра.
|
||
|
||
Правила оценки:
|
||
- Назидательные надписи и ядовитые предметы = 0
|
||
- Обычная змея = 0 (опасно)
|
||
- Щитомордник, аспид = 0 (ядовитые змеи)
|
||
- Паук/паутинная нить = 7 баллов
|
||
- Водяной мох = 2 балла
|
||
- Обычный мох = 3 балла
|
||
- Луговая змея = 1 балл (неядовитая)
|
||
- Остальные = 1 балл
|
||
"""
|
||
normalized = " ".join(name.casefold().replace("ё", "е").split())
|
||
letters = re.sub(r"[^а-я]", "", normalized)
|
||
if "надпис" in letters or "ядовит" in letters:
|
||
return 0
|
||
if "лугов" in normalized and "зме" in normalized:
|
||
return 1
|
||
if (
|
||
"щитоморд" in letters
|
||
or "аспид" in letters
|
||
or letters in ("змея", "змеи")
|
||
or SequenceMatcher(None, letters, "змея").ratio() >= 0.8
|
||
):
|
||
return 0
|
||
if "паутин" in letters or "паутн" in letters:
|
||
return 7
|
||
if "обычн" in normalized and "мох" in normalized:
|
||
return 3
|
||
if "водян" in normalized and "мох" in normalized:
|
||
return 2
|
||
return 1
|
||
|
||
|
||
def calculate_inspection(report: InspectionReport) -> InspectionResult:
|
||
"""
|
||
Рассчитывает баллы за осмотр.
|
||
|
||
Формула: осмотры × 2 + сумма (количество × ценность_ресурса)
|
||
"""
|
||
points = report.inspections * 2
|
||
points += sum(amount * _inspection_resource_value(name) for name, amount in report.resources)
|
||
return InspectionResult(points=points)
|