2026-03-11 11:44:57 +01:00
|
|
|
from __future__ import annotations
|
2026-03-12 16:28:20 +01:00
|
|
|
from typing import Dict, List, Callable, Tuple
|
2026-03-11 11:44:57 +01:00
|
|
|
import random
|
|
|
|
|
|
2026-03-12 16:28:20 +01:00
|
|
|
from warchron.constants import ContextType, ScoreKind
|
2026-03-11 11:44:57 +01:00
|
|
|
from warchron.model.exception import (
|
|
|
|
|
DomainError,
|
|
|
|
|
ForbiddenOperation,
|
|
|
|
|
RequiresConfirmation,
|
|
|
|
|
)
|
|
|
|
|
from warchron.model.war import War
|
|
|
|
|
from warchron.model.round import Round
|
|
|
|
|
from warchron.model.battle import Battle
|
|
|
|
|
from warchron.model.score_service import ScoreService
|
2026-03-12 16:28:20 +01:00
|
|
|
from warchron.model.tie_manager import TieResolver, TieContext
|
|
|
|
|
from warchron.model.war_event import TieResolved
|
|
|
|
|
from warchron.model.score_service import ParticipantScore
|
|
|
|
|
|
|
|
|
|
ResolveTiesCallback = Callable[
|
|
|
|
|
["War", List["TieContext"]],
|
|
|
|
|
Dict[Tuple[str, str, int | None], Dict[str, bool]],
|
|
|
|
|
]
|
2026-03-11 11:44:57 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class Pairing:
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def check_round_pairable(
|
|
|
|
|
round: Round,
|
|
|
|
|
) -> None:
|
|
|
|
|
if round.is_over:
|
|
|
|
|
raise ForbiddenOperation("Can not resolve pairing on finished round")
|
|
|
|
|
if round.has_finished_battle():
|
|
|
|
|
raise ForbiddenOperation("Can not resolve pairing with finished battle(s)")
|
|
|
|
|
if len(round.battles) * 2 < len(round.choices):
|
|
|
|
|
raise DomainError(
|
|
|
|
|
"There are not enough sectors for all participants to battle"
|
|
|
|
|
)
|
|
|
|
|
for pid, choice in round.choices.items():
|
|
|
|
|
if choice is not None and not choice.priority_sector_id:
|
2026-03-12 16:28:20 +01:00
|
|
|
raise ForbiddenOperation(
|
|
|
|
|
f"Missing priority choice for participant {pid}"
|
|
|
|
|
)
|
2026-03-11 11:44:57 +01:00
|
|
|
if choice is not None and not choice.secondary_sector_id:
|
2026-03-12 16:28:20 +01:00
|
|
|
raise ForbiddenOperation(
|
|
|
|
|
f"Missing secondary choice for participant {pid}"
|
|
|
|
|
)
|
2026-03-11 11:44:57 +01:00
|
|
|
|
|
|
|
|
def cleanup() -> None:
|
|
|
|
|
for bat in round.battles.values():
|
|
|
|
|
bat.cleanup_battle_players()
|
2026-03-12 16:28:20 +01:00
|
|
|
# FIXME cancel TieResolved + TokenSpent
|
2026-03-11 11:44:57 +01:00
|
|
|
|
|
|
|
|
if any(
|
|
|
|
|
bat.player_1_id is not None or bat.player_2_id is not None
|
|
|
|
|
for bat in round.battles.values()
|
|
|
|
|
):
|
|
|
|
|
raise RequiresConfirmation(
|
|
|
|
|
"Battle(s) already have player(s) assigned for this round.\n"
|
|
|
|
|
"Battle players will be cleared.\n"
|
|
|
|
|
"Do you want to continue?",
|
|
|
|
|
action=cleanup,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def assign_battles_to_participants(
|
|
|
|
|
war: War,
|
|
|
|
|
round: Round,
|
2026-03-12 16:28:20 +01:00
|
|
|
resolve_ties_callback: ResolveTiesCallback,
|
2026-03-11 11:44:57 +01:00
|
|
|
) -> None:
|
|
|
|
|
campaign = war.get_campaign_by_round(round.id)
|
|
|
|
|
if campaign is None:
|
|
|
|
|
raise DomainError(f"Campaign for round {round.id} doesn't exist")
|
|
|
|
|
scores = ScoreService.compute_scores(
|
|
|
|
|
war,
|
|
|
|
|
ContextType.CAMPAIGN,
|
|
|
|
|
campaign.id,
|
|
|
|
|
)
|
2026-03-12 16:28:20 +01:00
|
|
|
|
|
|
|
|
def value_getter(score: ParticipantScore) -> int:
|
|
|
|
|
return score.victory_points
|
|
|
|
|
|
|
|
|
|
score_groups = ScoreService.group_participants_by_score(scores, value_getter)
|
2026-03-11 11:44:57 +01:00
|
|
|
sector_to_battle: Dict[str, Battle] = {
|
|
|
|
|
b.sector_id: b for b in round.battles.values()
|
|
|
|
|
}
|
|
|
|
|
for group in score_groups:
|
2026-03-12 16:28:20 +01:00
|
|
|
score_value = value_getter(scores[group[0]])
|
|
|
|
|
remaining: List[str] = [
|
|
|
|
|
campaign.war_to_campaign_part_id(pid) for pid in group
|
|
|
|
|
]
|
|
|
|
|
Pairing._run_phase(
|
|
|
|
|
war,
|
|
|
|
|
round,
|
|
|
|
|
remaining,
|
|
|
|
|
sector_to_battle,
|
|
|
|
|
resolve_ties_callback,
|
|
|
|
|
use_priority=True,
|
|
|
|
|
score_value=score_value,
|
|
|
|
|
)
|
|
|
|
|
Pairing._run_phase(
|
|
|
|
|
war,
|
|
|
|
|
round,
|
|
|
|
|
remaining,
|
|
|
|
|
sector_to_battle,
|
|
|
|
|
resolve_ties_callback,
|
|
|
|
|
use_priority=False,
|
|
|
|
|
score_value=score_value,
|
|
|
|
|
)
|
|
|
|
|
Pairing._assign_fallback(round, remaining)
|
2026-03-11 11:44:57 +01:00
|
|
|
|
|
|
|
|
@staticmethod
|
2026-03-12 16:28:20 +01:00
|
|
|
def _run_phase(
|
|
|
|
|
war: War,
|
2026-03-11 11:44:57 +01:00
|
|
|
round: Round,
|
2026-03-12 16:28:20 +01:00
|
|
|
remaining: List[str],
|
2026-03-11 11:44:57 +01:00
|
|
|
sector_to_battle: Dict[str, Battle],
|
2026-03-12 16:28:20 +01:00
|
|
|
resolve_ties_callback: ResolveTiesCallback,
|
|
|
|
|
*,
|
|
|
|
|
use_priority: bool,
|
|
|
|
|
score_value: int,
|
2026-03-11 11:44:57 +01:00
|
|
|
) -> None:
|
2026-03-12 16:28:20 +01:00
|
|
|
demand = Pairing._build_sector_demand(
|
|
|
|
|
round,
|
|
|
|
|
remaining,
|
|
|
|
|
use_priority,
|
|
|
|
|
)
|
|
|
|
|
for sector_id, participants in demand.items():
|
|
|
|
|
battle = sector_to_battle.get(sector_id)
|
2026-03-11 11:44:57 +01:00
|
|
|
if not battle:
|
|
|
|
|
continue
|
2026-03-12 16:28:20 +01:00
|
|
|
places = len(battle.get_available_places())
|
|
|
|
|
if places <= 0:
|
|
|
|
|
continue
|
|
|
|
|
winners = Pairing._resolve_sector_allocation(
|
|
|
|
|
war,
|
|
|
|
|
round,
|
|
|
|
|
sector_id,
|
|
|
|
|
participants,
|
|
|
|
|
places,
|
|
|
|
|
resolve_ties_callback,
|
|
|
|
|
score_value,
|
|
|
|
|
)
|
|
|
|
|
for pid in winners:
|
|
|
|
|
battle.assign_participant(pid)
|
|
|
|
|
remaining.remove(pid)
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _build_sector_demand(
|
|
|
|
|
round: Round,
|
|
|
|
|
participants: List[str],
|
|
|
|
|
use_priority: bool,
|
|
|
|
|
) -> Dict[str, List[str]]:
|
|
|
|
|
demand: Dict[str, List[str]] = {}
|
|
|
|
|
for pid in participants:
|
|
|
|
|
choice = round.choices.get(pid)
|
|
|
|
|
if not choice:
|
|
|
|
|
continue
|
|
|
|
|
sector_id = (
|
|
|
|
|
choice.priority_sector_id
|
|
|
|
|
if use_priority
|
|
|
|
|
else choice.secondary_sector_id
|
|
|
|
|
)
|
|
|
|
|
if not sector_id:
|
|
|
|
|
continue
|
|
|
|
|
demand.setdefault(sector_id, []).append(pid)
|
|
|
|
|
return demand
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _resolve_sector_allocation(
|
|
|
|
|
war: War,
|
|
|
|
|
round: Round,
|
|
|
|
|
sector_id: str,
|
|
|
|
|
participants: List[str],
|
|
|
|
|
places: int,
|
|
|
|
|
resolve_ties_callback: ResolveTiesCallback,
|
|
|
|
|
score_value: int,
|
|
|
|
|
) -> List[str]:
|
|
|
|
|
if len(participants) <= places:
|
|
|
|
|
return participants
|
|
|
|
|
campaign = war.get_campaign_by_round(round.id)
|
|
|
|
|
if campaign is None:
|
|
|
|
|
raise DomainError("Campaign not found for round {round.id}")
|
|
|
|
|
context = TieContext(
|
|
|
|
|
context_type=ContextType.CHOICE,
|
|
|
|
|
context_id=round.id,
|
|
|
|
|
participants=[
|
|
|
|
|
campaign.campaign_to_war_part_id(pid) for pid in participants
|
|
|
|
|
],
|
|
|
|
|
score_kind=ScoreKind.VP,
|
|
|
|
|
sector_id=sector_id,
|
|
|
|
|
)
|
|
|
|
|
# ---- resolve tie loop ----
|
|
|
|
|
while not TieResolver.is_tie_resolved(war, context):
|
|
|
|
|
if not TieResolver.can_tie_be_resolved(war, context, context.participants):
|
|
|
|
|
war.events.append(
|
|
|
|
|
TieResolved(
|
|
|
|
|
None,
|
|
|
|
|
context.context_type,
|
|
|
|
|
context.context_id,
|
|
|
|
|
score_value=score_value,
|
|
|
|
|
sector_id=sector_id,
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
break
|
|
|
|
|
bids_map = resolve_ties_callback(war, [context])
|
|
|
|
|
bids = bids_map[context.key()]
|
|
|
|
|
TieResolver.apply_bids(war, context, bids)
|
|
|
|
|
TieResolver.resolve_tie_state(war, context, bids)
|
|
|
|
|
ranked_groups = TieResolver.rank_by_tokens(
|
|
|
|
|
war,
|
|
|
|
|
context,
|
|
|
|
|
context.participants,
|
2026-03-11 11:44:57 +01:00
|
|
|
)
|
2026-03-12 16:28:20 +01:00
|
|
|
ordered: List[str] = []
|
|
|
|
|
for group in ranked_groups:
|
|
|
|
|
shuffled_group = list(group)
|
|
|
|
|
random.shuffle(shuffled_group)
|
|
|
|
|
ordered.extend(
|
|
|
|
|
campaign.war_to_campaign_part_id(pid) for pid in shuffled_group
|
|
|
|
|
)
|
|
|
|
|
return ordered[:places]
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _assign_fallback(
|
|
|
|
|
round: Round,
|
|
|
|
|
remaining: List[str],
|
|
|
|
|
) -> None:
|
|
|
|
|
for pid in list(remaining):
|
|
|
|
|
available = round.get_battles_with_places()
|
|
|
|
|
if not available:
|
|
|
|
|
raise DomainError("No available battle remaining")
|
|
|
|
|
if len(available) == 1:
|
|
|
|
|
available[0].assign_participant(pid)
|
|
|
|
|
remaining.remove(pid)
|
|
|
|
|
continue
|
|
|
|
|
raise DomainError(f"Ambiguous fallback for participant {pid}")
|