New math fixes, again

This commit is contained in:
nyan404 committed 2026-08-16 23:40:15 +03:00
1 parent 92605e7a4d
commit ec5a1a197a
5 files changed
+130 -62

No files matched your search

+10 -10
View File
@@ -73,6 +73,8 @@ class CoachingSession:
_positive_id(kitten_id, "ID дополнительного котёнка")
if independence not in ("самостоятельно", "несамостоятельно"):
raise ValueError("Некорректный статус самостоятельности")
if any(independence != self.kitten_independence for _, _, independence in self.extra_kittens):
raise ValueError("Все котята в одном отчёте должны быть либо самостоятельными, либо несамостоятельными")
@staticmethod
def duration_minutes(start: str, end: str) -> int:
@@ -95,26 +97,24 @@ def calculate_coaching(session: CoachingSession) -> CoachingResult:
if minutes <= 0:
raise ValueError("Продолжительность захода должна быть больше нуля")
# The multiplier belongs to the escort (Krylan/Belka), not to the kitten.
# ZU is always treated as independent according to the calculator rules.
independence_multiplier = (
1.5
if session.skill == "ЛУ" and session.kitten_independence == "несамостоятельно"
else 1.0
)
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))
escort_multiplier = independence_multiplier * ward_multiplier
# 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 * escort_multiplier / 5),
escort_points=_points(minutes * ward_multiplier / 5 + nonself_bonus),
kitten_points=_points(minutes / 5),
kitten_count=kitten_count,
escort_multiplier=round(escort_multiplier, 4),
escort_multiplier=round(ward_multiplier, 4),
)
+52 -17
View File
@@ -65,7 +65,7 @@ def _extra_kittens(value: str) -> tuple[tuple[str, int, str], ...]:
result = []
for item in re.split(r"\s*,\s*", value):
independence = "самостоятельно"
status = re.search(r"(?i)(?:;|\s+)\s*(самостоятельно|несамостоятельно|сам|несам)\s*$", item)
status = re.search(r"(?i)(?:;|\s+)\s*(самостоятельно|самостоятельный|несамостоятельно|несамостоятельный|сам|несам)\s*$", item)
if status:
independence = "несамостоятельно" if status.group(1).lower().startswith("несам") else "самостоятельно"
item = item[:status.start()].strip()
@@ -74,6 +74,23 @@ def _extra_kittens(value: str) -> tuple[tuple[str, int, str], ...]:
return tuple(result)
def _validate_uniform_independence(primary: str, extras: tuple[tuple[str, int, str], ...] | list[tuple[str, int, str]]) -> None:
if any(independence != primary for _, _, independence in extras):
raise ValueError("Все котята в одном отчёте должны быть либо самостоятельными, либо несамостоятельными")
def _kitten_entry(value: str) -> tuple[str, int, str | None]:
"""Parse one kitten and an optional per-kitten independence status."""
value = value.strip().rstrip(".!?").strip()
status = None
match = re.search(r"(?i)\s+(самостоятельно|самостоятельный|несамостоятельно|несамостоятельный|сам|несам)\s*$", value)
if match:
status = "несамостоятельно" if match.group(1).lower().startswith("несам") else "самостоятельно"
value = value[:match.start()].strip()
name, kitten_id = _person(value)
return name, kitten_id, status
def parse_text_command(text: str) -> dict[str, Any]:
text = text.strip()
if text.lower() in ("/help", "help", "/start", "start"):
@@ -89,24 +106,27 @@ def parse_text_command(text: str) -> dict[str, Any]:
raise ValueError("Формат: /лу ДД.ММ HH:MM HH:MM | Имя [ID] | Котёнок [ID] | статус")
date, start, end = parts[0].split()
escort_name, escort_id = _person(parts[1])
kitten_entries = [_person(item) for item in parts[2].split(",") if item.strip()]
kitten_entries = [_kitten_entry(item) for item in parts[2].split(",") if item.strip()]
if not kitten_entries:
raise ValueError("Укажите имя котёнка или котят через запятую в формате Имя [ID].")
kitten_name, kitten_id = kitten_entries[0]
extras = [(name, kitten_id, "самостоятельно") for name, kitten_id in kitten_entries[1:]]
kitten_name, kitten_id, primary_status = kitten_entries[0]
extras = [(name, kitten_id, status) for name, kitten_id, status in kitten_entries[1:]]
status_part = parts[3] if len(parts) > 3 else ""
status_value = status_part.lower()
status_is_valid = status_value in ("сам", "самостоятельно", "несам", "несамостоятельно")
status_is_valid = status_value in ("сам", "самостоятельно", "самостоятельный", "несам", "несамостоятельно", "несамостоятельный")
extra_parts = parts[4:] if status_is_valid else parts[3:]
for extra_part in extra_parts:
if extra_part.strip().lower().startswith(("доп", "нет")) or "[" in extra_part:
extras.extend(_extra_kittens(extra_part))
primary_independence = ("несамостоятельно" if status_part.lower().startswith("несам") else "самостоятельно") if status_is_valid else (primary_status or "самостоятельно")
extras = [(name, kitten_id, status or primary_independence) for name, kitten_id, status in extras]
_validate_uniform_independence(primary_independence, extras)
return {
"mode": "coaching", "date": date, "skill": "ЛУ", "start": start, "end": end,
"escort_name": escort_name, "escort_id": escort_id,
"kitten_name": kitten_name, "kitten_id": kitten_id,
"kitten_independence": ("несамостоятельно" if status_part.lower().startswith("несам") else "самостоятельно") if status_is_valid else "самостоятельно",
"_independence_provided": status_is_valid,
"kitten_independence": primary_independence,
"_independence_provided": status_is_valid or primary_status is not None,
"extra_kittens": tuple(extras),
}
if command in ("/зу", "/зоркость"):
@@ -261,9 +281,10 @@ def parse_natural_bulk(text: str) -> tuple[dict[str, Any], list[str]] | None:
questions.append("Не вижу котёнка в формате Имя и ID.")
if len(people) > 2:
fields["extra_kittens"] = [(name, kitten_id, "самостоятельно") for name, kitten_id in people[2:]]
independence_match = re.search(r"(?i)\b(самостоятельно|несамостоятельно)\b", text)
independence_match = re.search(r"(?i)\b(самостоятельно|самостоятельный|несамостоятельно|несамостоятельный|сам|несам)\b", text)
if independence_match:
fields["kitten_independence"] = independence_match.group(1).lower()
value = independence_match.group(1).lower()
fields["kitten_independence"] = "несамостоятельно" if value.startswith("несам") else "самостоятельно"
else:
questions.append("Котёнок самостоятельный или несамостоятельный?")
return fields, questions
@@ -424,7 +445,7 @@ class BelkiDialog:
("start", "Укажите время начала в формате HH:MM."),
("end", "Укажите время конца (конец захода) в формате HH:MM."),
("escort", "Укажите сопровождающего в формате Имя [ID]."),
("kitten", "Укажите имя котёнка или котят через запятую в формате Имя [ID].\nНапример: Беззубик [1566767], Малыш [123456]."),
("kitten", "Укажите имя котёнка или котят через запятую в формате Имя [ID].\nНапример: Беззубик [1566767], Малыш [123456].\nДля нескольких котят укажите один общий статус: все самостоятельные или все несамостоятельные."),
("independence", "Котёнок самостоятельный или несамостоятельный?"),
),
"training": (
@@ -622,12 +643,12 @@ class BelkiDialog:
f"Ресурсы: {resources}\n"
"Подтвердить? Ответьте «да» или «нет»."
)
kittens = [(state["kitten_name"], state["kitten_id"])] + [
(name, kitten_id) for name, kitten_id, _ in state.get("extra_kittens", [])
kittens = [(state["kitten_name"], state["kitten_id"], state["kitten_independence"])] + [
(name, kitten_id, independence) for name, kitten_id, independence in state.get("extra_kittens", [])
]
kitten_lines = "\n".join(
f"Котёнок {index}: {name} [{kitten_id}]"
for index, (name, kitten_id) in enumerate(kittens, start=1)
f"Котёнок {index}: {name} [{kitten_id}] — {independence}"
for index, (name, kitten_id, independence) in enumerate(kittens, start=1)
)
return (
"Я распознал данные:\n"
@@ -739,12 +760,17 @@ class BelkiDialog:
state[key] = True
elif key == "kitten":
try:
kittens = [_person(item) for item in text.split(",") if item.strip()]
kittens = [_kitten_entry(item) for item in text.split(",") if item.strip()]
if not kittens:
raise ValueError("Укажите имя котёнка или котят через запятую в формате Имя [ID].")
state["kitten_name"], state["kitten_id"] = kittens[0]
state["kitten_name"], state["kitten_id"], primary_status = kittens[0]
if primary_status is not None:
state["kitten_independence"] = primary_status
if state.get("mode") == "coaching" and len(kittens) > 1:
state["extra_kittens"] = [(*item, "самостоятельно") for item in kittens[1:]]
primary = primary_status or state.get("kitten_independence") or "самостоятельно"
extras = [(name, kitten_id, status or primary) for name, kitten_id, status in kittens[1:]]
_validate_uniform_independence(primary, extras)
state["extra_kittens"] = extras
except ValueError as exc:
return str(exc)
state[key] = True
@@ -753,6 +779,9 @@ class BelkiDialog:
if value is None:
return "Ответьте «самостоятельный» или «несамостоятельный» (подойдут и другие формы слова)."
state["kitten_independence"] = value
state["extra_kittens"] = [
(name, kitten_id, value) for name, kitten_id, _ in state.get("extra_kittens", [])
]
state[key] = True
elif key == "place":
value = text.lower()
@@ -854,6 +883,12 @@ class BelkiDialog:
except (ValueError, IndexError) as exc:
return f"Не удалось добавить котят: {exc}"
state["extra_kittens"] = list(state.get("extra_kittens", ()))
primary = state.get("kitten_independence", "самостоятельно")
additions = [(name, kitten_id, status or primary) for name, kitten_id, status in additions]
try:
_validate_uniform_independence(primary, state["extra_kittens"] + additions)
except ValueError as exc:
return str(exc)
state["extra_kittens"].extend(additions)
return (
f"Добавлено дополнительных котят: {len(additions)}. "
@@ -106,13 +106,9 @@ independence = dependent
### Зоркость
Если прокачивается `ЗУ`/зоркость, в калькуляторе всегда используется значение:
```text
independence = independent
```
То есть надбавка за несамостоятельное лазание к ЗУ не применяется.
Для `ЗУ`/зоркости статус самостоятельности также учитывается. Все котята в
одном отчёте должны иметь одинаковый статус: либо все самостоятельные, либо
все несамостоятельные. Смешанный вариант не принимается.
### Урок
@@ -373,28 +369,10 @@ count_multiplier(n) = 1.5 * 1.15^(n - 2), n >= 3
## 10. Несколько котят + несамостоятельность
Скриншоты подтверждают отдельно:
```text
1 несамостоятельный котёнок -> ×1.5
2 самостоятельных котёнка -> ×1.5
```
Но предоставленные материалы не показывают числовой пример, где одновременно выполняются оба условия, например:
```text
2 котёнка, один из которых несамостоятельный
```
Поэтому нельзя молча выбирать один из вариантов:
```text
×1.5
×1.5 ×1.5
другая формула
```
До проверки исходной формулы таблицы такой случай должен считаться **неуточнённым правилом**, а не догадкой расчётного ядра.
Множитель второго и последующих котят применяется к базовым баллам
сопровождающего. Если все котята несамостоятельные, за каждого добавляется
отдельная надбавка `minutes * 0.5 / 5`. Смешивать статусы в одном отчёте
нельзя. Правило одинаково для `ЛУ` и `ЗУ`.
---
+38 -5
View File
@@ -47,7 +47,7 @@ class CalculationTests(unittest.TestCase):
self.assertEqual(result.kitten_points, 12)
def test_non_self_kitten_and_extra_companion(self):
result = calculate_coaching(
with self.assertRaisesRegex(ValueError, "Все котята"):
CoachingSession(
date="15.08",
skill="ЗУ",
@@ -63,9 +63,6 @@ class CalculationTests(unittest.TestCase):
("Третий", 4, "самостоятельно"),
),
)
)
self.assertEqual(result.escort_points, 20.7)
self.assertEqual(result.kitten_points, 12)
def test_non_self_30_minutes_matches_calculator(self):
result = calculate_coaching(
@@ -81,7 +78,7 @@ class CalculationTests(unittest.TestCase):
kitten_independence="несамостоятельно",
)
)
self.assertEqual(result.escort_points, 6)
self.assertEqual(result.escort_points, 9)
self.assertEqual(result.kitten_points, 6)
def test_non_self_60_minutes_gives_adult_18_and_kitten_12(self):
@@ -113,6 +110,42 @@ class CalculationTests(unittest.TestCase):
self.assertEqual(result.escort_multiplier, 1.725)
self.assertEqual(result.escort_points, 20.7)
def test_nonself_additional_ward_adds_half_base_bonus(self):
result = calculate_coaching(
CoachingSession(
"15.08", "ЛУ", "10:00", "10:55", "Белка", 1, "Первый", 2,
kitten_independence="несамостоятельно",
extra_kittens=(("Второй", 3, "несамостоятельно"),),
)
)
self.assertEqual(result.escort_points, 27.5)
self.assertEqual(result.kitten_points, 11)
def test_two_nonself_wards_add_two_bonuses(self):
result = calculate_coaching(
CoachingSession(
"15.08", "ЛУ", "10:00", "10:55", "Белка", 1, "Первый", 2,
kitten_independence="несамостоятельно",
extra_kittens=(("Второй", 3, "несамостоятельно"),),
)
)
self.assertEqual(result.escort_points, 27.5)
def test_zu_independence_matrix_matches_reported_values(self):
def points(primary, extra):
return calculate_coaching(
CoachingSession(
"16.08", "ЗУ", "10:00", "11:00", "Белка", 1, "Первый", 2,
kitten_independence=primary,
extra_kittens=(("Второй", 3, extra),),
)
).escort_points
self.assertEqual(points("самостоятельно", "самостоятельно"), 18)
with self.assertRaisesRegex(ValueError, "Все котята"):
points("самостоятельно", "несамостоятельно")
self.assertEqual(points("несамостоятельно", "несамостоятельно"), 30)
def test_training_is_fixed(self):
self.assertEqual(calculate_training(TrainingSession("Белка", 1, "Котёнок", 2)).points, 25)
+23 -1
View File
@@ -3,7 +3,7 @@ from datetime import datetime
from tempfile import TemporaryDirectory
from app.belki.identity import Identity, IdentityDirectory
from app.belki.vk_bot import HELP_TEXT, BelkiDialog, inspect_bulk_text
from app.belki.vk_bot import HELP_TEXT, BelkiDialog, inspect_bulk_text, parse_text_command
class VkConversationTests(unittest.TestCase):
@@ -62,6 +62,14 @@ class VkConversationTests(unittest.TestCase):
self.assertIn("Котёнок 2: Малыш [123456]", dialog._confirmation(dialog._states[80]))
self.assertIn("самостоятель", response.lower())
def test_multiple_kittens_reject_mixed_independence_status(self):
dialog = BelkiDialog()
dialog.handle(81, "/лу")
for answer in ("15.08", "11:00", "12:00", "Дикая Вишня [1604614]"):
dialog.handle(81, answer)
response = dialog.handle(81, "Беззубик [1] самостоятельно, Малыш [2] несамостоятельно")
self.assertIn("Все котята", response)
def test_bulk_input_is_detected_and_confirmed(self):
dialog = BelkiDialog()
confirmation = dialog.handle(
@@ -255,6 +263,20 @@ class VkConversationTests(unittest.TestCase):
dialog.handle(502, answer)
self.assertIn("скриншот", dialog.handle(502, "несам").lower())
def test_compact_command_accepts_all_independence_variants(self):
for value, expected in (
("сам", "самостоятельно"),
("самостоятельный", "самостоятельно"),
("самостоятельно", "самостоятельно"),
("несам", "несамостоятельно"),
("несамостоятельный", "несамостоятельно"),
("несамостоятельно", "несамостоятельно"),
):
parsed = parse_text_command(
f"/зу 16.08 10:00 10:10 | Белка [1] | Малыш [2] | {value}"
)
self.assertEqual(parsed["kitten_independence"], expected)
def test_keyboard_changes_with_dialog_state(self):
dialog = BelkiDialog()
menu = dialog.keyboard_for(503)