​fly-in /
src / schedule.py
63 commits
09-08-2026
206 lines 5.5 kB
  1"""The plan of a run: what every drone does on every turn."""
  2
  3from abc import ABC, abstractmethod
  4from dataclasses import dataclass
  5from typing import Iterator
  6
  7from .connection import Connection
  8from .scenario import Scenario
  9from .zone import Zone
 10
 11
 12class Placement(ABC):
 13    """Where a single drone sits at the end of a turn."""
 14
 15    @abstractmethod
 16    def label(self) -> str:
 17        """Spell this placement the way an output line does.
 18
 19        Returns:
 20            A zone name, or a dashed connection name while in flight.
 21        """
 22
 23    @abstractmethod
 24    def current_zone(self) -> Zone:
 25        """Name the zone this placement belongs to.
 26
 27        A drone in flight is already committed to its destination, so
 28        it counts as that zone for display purposes.
 29
 30        Returns:
 31            The zone occupied, or the one being entered.
 32        """
 33
 34
 35@dataclass(frozen=True)
 36class AtZone(Placement):
 37    """A drone resting in a zone.
 38
 39    Attributes:
 40        zone: The zone it occupies.
 41    """
 42
 43    zone: Zone
 44
 45    def label(self) -> str:
 46        """Spell the placement as the zone's name.
 47
 48        Returns:
 49            The zone name.
 50        """
 51        return self.zone.name
 52
 53    def current_zone(self) -> Zone:
 54        """Name the occupied zone.
 55
 56        Returns:
 57            The zone the drone rests in.
 58        """
 59        return self.zone
 60
 61
 62@dataclass(frozen=True)
 63class InFlight(Placement):
 64    """A drone crossing a connection toward a restricted zone.
 65
 66    Attributes:
 67        connection: The link it is currently on.
 68        target: The restricted zone it must reach next turn.
 69    """
 70
 71    connection: Connection
 72    target: Zone
 73
 74    def label(self) -> str:
 75        """Spell the placement as the connection's two endpoints.
 76
 77        Returns:
 78            The endpoint names joined by a dash.
 79        """
 80        return str(self.connection)
 81
 82    def current_zone(self) -> Zone:
 83        """Name the zone this drone is committed to entering.
 84
 85        Returns:
 86            The destination zone.
 87        """
 88        return self.target
 89
 90
 91@dataclass(frozen=True)
 92class Move:
 93    """One drone changing place during one turn.
 94
 95    Attributes:
 96        drone_id: 1-based identifier, printed as D1.
 97        placement: Where the drone ends the turn.
 98    """
 99
100    drone_id: int
101    placement: Placement
102
103    def label(self) -> str:
104        """Spell the move the way an output line does.
105
106        Returns:
107            The drone identifier and its placement, dash-separated.
108        """
109        return f"D{self.drone_id}-{self.placement.label()}"
110
111
112class Schedule:
113    """The ordered turns of a run.
114
115    A turn records only the drones that moved, because the output
116    format omits the others. positions_at replays those deltas
117    for callers that need every drone at once, such as a graphical
118    view.
119    """
120
121    def __init__(self, scenario: Scenario) -> None:
122        """Start an empty schedule for one scenario.
123
124        Args:
125            scenario: The map and drone count being solved.
126        """
127        self._scenario = scenario
128        self._turns: list[list[Move]] = []
129
130    @property
131    def scenario(self) -> Scenario:
132        """The scenario this schedule belongs to.
133
134        Returns:
135            The map and drone count.
136        """
137        return self._scenario
138
139    @property
140    def turns(self) -> int:
141        """How many turns the run takes, which is its score.
142
143        Returns:
144            The number of recorded turns.
145        """
146        return len(self._turns)
147
148    def add_turn(self, moves: list[Move]) -> None:
149        """Append one turn's worth of movements.
150
151        Args:
152            moves: The drones that move, at most one entry each.
153
154        Raises:
155            ValueError: If a drone identifier is out of range or
156                appears twice in the same turn.
157        """
158        seen: set[int] = set()
159        for move in moves:
160            if not 1 <= move.drone_id <= self._scenario.nb_drones:
161                raise ValueError(f"no drone D{move.drone_id}")
162            if move.drone_id in seen:
163                raise ValueError(f"D{move.drone_id} moves twice in one turn")
164            seen.add(move.drone_id)
165        self._turns.append(list(moves))
166
167    def positions_at(self, turn: int) -> dict[int, Placement]:
168        """Locate every drone once a number of turns have passed.
169
170        Args:
171            turn: How many turns to replay; 0 is the initial state,
172                with every drone still in the start zone.
173
174        Returns:
175            Each drone identifier mapped to its placement.
176
177        Raises:
178            ValueError: If the turn is outside the recorded run.
179        """
180        if not 0 <= turn <= len(self._turns):
181            raise ValueError(f"turn {turn} is outside the run")
182        start = AtZone(self._scenario.network.start)
183        positions: dict[int, Placement] = {
184            drone: start
185            for drone in range(1, self._scenario.nb_drones + 1)
186        }
187        for moves in self._turns[:turn]:
188            for move in moves:
189                positions[move.drone_id] = move.placement
190        return positions
191
192    def __iter__(self) -> Iterator[list[Move]]:
193        """Walk the turns in order.
194
195        Returns:
196            An iterator over each turn's movements.
197        """
198        return iter(self._turns)
199
200    def __len__(self) -> int:
201        """Count the turns of the run.
202
203        Returns:
204            The number of recorded turns.
205        """
206        return len(self._turns)