106 lines
3.0 kB
1"""Zones: the nodes of a network."""
2
3from dataclasses import dataclass
4from enum import Enum
5from typing import Final
6
7UNLIMITED: Final[int] = 10 ** 9
8"""Stand-in for an unbounded capacity, kept an int for flow arithmetic."""
9
10
11class ZoneType(Enum):
12 """Kind of a zone, together with the turn cost of entering it.
13
14 The cost is a property of the destination zone: entering a
15 restricted zone takes two turns, one of them spent in flight on
16 the connection itself.
17 """
18 label: str
19 cost: int
20
21 NORMAL = ("normal", 1)
22 PRIORITY = ("priority", 1)
23 RESTRICTED = ("restricted", 2)
24 BLOCKED = ("blocked", 0)
25
26 def __init__(self, label: str, cost: int) -> None:
27 """Unpack the member value into named attributes.
28
29 Args:
30 label: Spelling used by the zone= metadata key.
31 cost: Number of turns a drone spends entering this zone.
32 """
33 self.label = label
34 self.cost = cost
35
36 @classmethod
37 def from_label(cls, label: str) -> "ZoneType":
38 """Look a zone type up by its map-file spelling.
39
40 Args:
41 label: Value of a zone= metadata key.
42
43 Returns:
44 The matching zone type.
45
46 Raises:
47 ValueError: If no zone type carries that label.
48 """
49 for zone_type in cls:
50 if zone_type.label == label:
51 return zone_type
52 raise ValueError(f"unknown zone type {label!r}")
53
54
55class ZoneRole(Enum):
56 """Whether a zone is the start, the end, or an ordinary hub."""
57
58 START = "start_hub"
59 END = "end_hub"
60 INTERMEDIATE = "hub"
61
62
63@dataclass(frozen=True)
64class Zone:
65 """A single zone of the network.
66
67 Attributes:
68 name: Unique identifier, free of dashes and spaces.
69 x: Horizontal coordinate, used by the visual representation.
70 y: Vertical coordinate, used by the visual representation.
71 zone_type: Kind of a zone, which fixes its entry cost.
72 role: Start, end, or intermediate hub.
73 color: Display color, or None when the map gives none.
74 max_drones: Declared occupancy limit; ignored on start and end.
75 """
76
77 name: str
78 x: int
79 y: int
80 zone_type: ZoneType = ZoneType.NORMAL
81 role: ZoneRole = ZoneRole.INTERMEDIATE
82 color: str | None = None
83 max_drones: int = 1
84
85 @property
86 def capacity(self) -> int:
87 """Drones this zone may hold in a single turn.
88
89 The start and end zones are unbounded, so any max_drones
90 the map declares on them is stored but never applied.
91
92 Returns:
93 The occupancy limit, or UNLIMITED for start and end.
94 """
95 if self.role is not ZoneRole.INTERMEDIATE:
96 return UNLIMITED
97 return self.max_drones
98
99 @property
100 def is_passable(self) -> bool:
101 """Whether drones may enter this zone at all.
102
103 Returns:
104 False for blocked zones, True otherwise.
105 """
106 return self.zone_type is not ZoneType.BLOCKED