Added comments to Python Code.
This commit is contained in:
1 parent
aa4c5f3681
commit
7bd6b9c4b8
8 files changed
+448
-24
No files matched your search
@@ -5,7 +5,13 @@ from difflib import SequenceMatcher
|
||||
import re
|
||||
from typing import Literal
|
||||
|
||||
"""
|
||||
Ядро бизнес-логики:
|
||||
- Валидация и парсинг данных
|
||||
- Расчёт баллов за тренировки (ЛУ, ЗУ), тренировки и осмотры
|
||||
"""
|
||||
|
||||
# --- Типы-константы для валидации ввода ---
|
||||
Independence = Literal["самостоятельно", "несамостоятельно"]
|
||||
Skill = Literal["ЛУ", "ЗУ"]
|
||||
Place = Literal["дупло", "расщелина"]
|
||||
@@ -14,6 +20,7 @@ _CLOCK_RE = re.compile(r"^(?:[01]\d|2[0-3]):[0-5]\d$")
|
||||
|
||||
|
||||
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(":")
|
||||
@@ -21,18 +28,21 @@ def parse_clock(value: str) -> int:
|
||||
|
||||
|
||||
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)
|
||||
@@ -40,6 +50,7 @@ def _points(value: float) -> float | int:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CoachingSession:
|
||||
"""Сессия тренировки навыка ЛУ или ЗУ."""
|
||||
date: str
|
||||
skill: Skill
|
||||
start: str
|
||||
@@ -52,6 +63,7 @@ class CoachingSession:
|
||||
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)
|
||||
@@ -82,6 +94,7 @@ class CoachingSession:
|
||||
|
||||
@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)
|
||||
@@ -89,6 +102,7 @@ class CoachingSession:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CoachingResult:
|
||||
"""Результат расчёта баллов за тренировку навыка."""
|
||||
minutes: int
|
||||
escort_points: float | int
|
||||
kitten_points: float | int
|
||||
@@ -97,6 +111,16 @@ class CoachingResult:
|
||||
|
||||
|
||||
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("Продолжительность захода должна быть больше нуля")
|
||||
@@ -124,12 +148,14 @@ def calculate_coaching(session: CoachingSession) -> CoachingResult:
|
||||
|
||||
@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 сопровождающего")
|
||||
@@ -138,15 +164,18 @@ class TrainingSession:
|
||||
|
||||
@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
|
||||
@@ -154,6 +183,7 @@ class InspectionReport:
|
||||
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 персонажа")
|
||||
@@ -168,10 +198,24 @@ class InspectionReport:
|
||||
|
||||
@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:
|
||||
@@ -195,6 +239,11 @@ def _inspection_resource_value(name: str) -> int:
|
||||
|
||||
|
||||
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)
|
||||
Reference in new issue
Block a user