87 lines
2.6 kB
1"""Fitting a map's coordinates onto the drawing surface."""
2
3from dataclasses import dataclass
4from typing import Iterable
5
6from ..zone import Zone
7
8
9@dataclass(frozen=True)
10class Bounds:
11 """The rectangle a map's zones occupy in map coordinates.
12
13 Attributes:
14 min_x: Leftmost coordinate used by a zone.
15 min_y: Topmost coordinate used by a zone.
16 max_x: Rightmost coordinate used by a zone.
17 max_y: Bottommost coordinate used by a zone.
18 """
19
20 min_x: int
21 min_y: int
22 max_x: int
23 max_y: int
24
25 @classmethod
26 def around(cls, zones: Iterable[Zone]) -> "Bounds":
27 """Measure the rectangle a group of zones spans.
28
29 Args:
30 zones: The zones to measure.
31
32 Returns:
33 Their bounding rectangle.
34
35 Raises:
36 ValueError: If there are no zones to measure.
37 """
38 xs = [zone.x for zone in zones]
39 ys = [zone.y for zone in zones]
40 if not xs:
41 raise ValueError("a map needs at least one zone")
42 return cls(min(xs), min(ys), max(xs), max(ys))
43
44 def place(
45 self, x: int, y: int, width: int, height: int, margin: int
46 ) -> tuple[int, int]:
47 """Convert one map coordiante into a pixel on the surface.
48
49 A map laid out in a single row or column spans nothing in that
50 direction, so it is centered rather than divided by zero.
51
52 Args:
53 x: Horizontal map coordinate.
54 y: Verical map coordinate.
55 width: Width of the surface in pixels.
56 height: Height of the surface in pixels.
57 margin: Pixels to keep clear along each edge.
58
59 Returns:
60 The pixel to draw that coordinate at.
61 """
62 return (
63 self._along(x, self.min_x, self.max_x, width, margin),
64 self._along(y, self.min_y, self.max_y, height, margin)
65 )
66
67 @staticmethod
68 def _along(
69 value: int, low: int, high: int, size: int, margin: int
70 ) -> int:
71 """Spread one axis of the map across one axis of the surface.
72
73 Args:
74 value: The map coordinate.
75 low: Smallest coordinate on this axis.
76 high: Largest coordinate on this axis.
77 size: Length of this axis in pixels.
78 margin: Pixels to keep clear at each end.
79
80 Returns:
81 The pixel this coordinate falls on.
82 """
83 span = high - low
84 if span == 0:
85 return size // 2
86 usable = size - 2 * margin
87 return margin + round((value - low) * usable / span)