​fly-in /
src / render / pygame_view.py
63 commits
08-08-2026
821 lines 29 kB
  1"""A pixel-art view of a run, drawn with pygame."""
  2
  3import os
  4from dataclasses import dataclass
  5from math import cos, radians, sin
  6from random import Random
  7from typing import Final
  8
  9from ..connection import Connection
 10from ..errors import FlyInError
 11from ..scenario import Scenario
 12from ..schedule import AtZone, InFlight, Move, Placement
 13from ..zone import Zone, ZoneRole, ZoneType
 14from .base import Renderer
 15from .layout import Bounds
 16from .palette import (
 17    DIRT,
 18    DIRT_DARK,
 19    GRASS,
 20    GRASS_DARK,
 21    GRASS_LIGHT,
 22    INK,
 23    PAPER,
 24    RAINBOW,
 25    RGB,
 26    STONE,
 27    HINT,
 28    MUTED,
 29    ember,
 30    snap,
 31    zone_rgb,
 32)
 33
 34os.environ.setdefault("PYGAME_HIDE_SUPPORT_PROMPT", "1")
 35
 36import pygame  # noqa: E402
 37
 38WIDTH: Final[int] = 640
 39HEIGHT: Final[int] = 360
 40MARGIN: Final[int] = 30
 41BAR: Final[int] = 12
 42ZONE_RADIUS: Final[int] = 8
 43DRONE_SIZE: Final[int] = 20
 44BLAST_SIZE: Final[int] = 26
 45SHOWN_PER_ZONE: Final[int] = 4
 46CROWDED: Final[int] = 20
 47OFFSETS: Final[tuple[tuple[int, int], ...]] = (
 48    (0, -12), (12, 0), (-12, 0), (0, 12),
 49)
 50LABEL_DROP: Final[int] = 12
 51RAINBOW_MS: Final[int] = 130
 52FLAP_MS: Final[int] = 110
 53BOOM_MS: Final[int] = 190
 54ASSETS: Final[str] = "assets"
 55
 56
 57@dataclass
 58class Blast:
 59    """An explosion playing where a drone was delivered.
 60
 61    Effects keep their own clock so a delivery on the final turn still
 62    plays out in full, and a paused or hurried turn never stretches or
 63    clips one.
 64
 65    Attributes:
 66        x: Horizontal pixel of the blast.
 67        y: Vertical pixel of the blast.
 68        started: Millisecond the blast began at.
 69    """
 70    x: int
 71    y: int
 72    started: int
 73
 74
 75class PygameView(Renderer):
 76    """Draws a run in a window while the text view prints it."""
 77
 78    def __init__(self, scale: int = 2, turn_seconds: float = 0.7) -> None:
 79        """ Set up a view without opening anything yet.
 80
 81        Args:
 82            scale: How many pixels wide each drawn pixel starts out.
 83            turn_seconds: How long one turn takes to play.
 84        """
 85        self._scale = scale
 86        self._turn_seconds = turn_seconds
 87        self._closed = False
 88        self._paused = False
 89        self._stepping = False
 90        self._labels = True
 91        self._fullscreen = False
 92        self._places: dict[int, Placement] = {}
 93        self._delivered: set[int] = set()
 94        self._blasts: list[Blast] = []
 95        self._points: dict[str, tuple[int, int]] = {}
 96        self._font: pygame.font.Font | None = None
 97        self._captions: list[tuple[int, int, str]] = []
 98        self._bar: list[tuple[str, RGB]] = []
 99        self._status: list[tuple[str, RGB]] = []
100        self._fly: list[pygame.Surface] = []
101        self._boom: list[pygame.Surface] = []
102
103    def begin(self, scenario: Scenario) -> None:
104        """Open the window and draw the ground.
105
106        Args:
107            scenario: The map about to be replayed.
108
109        Raises:
110            FlyInError: If no window can be open.
111        """
112        self._scenario = scenario
113        try:
114            pygame.init()
115            self._window = pygame.display.set_mode(
116                (WIDTH * self._scale, HEIGHT * self._scale),
117                pygame.RESIZABLE,
118            )
119        except pygame.error as err:
120            raise FlyInError(f"cannot open a window: {err}") from err
121        pygame.display.set_caption("fly-in")
122        self._clock = pygame.time.Clock()
123        self._open_font()
124        self._canvas = pygame.Surface((WIDTH, HEIGHT))
125        self._load_sprites()
126        self._measure()
127        self._ground = self._bake()
128        self._labels = len(scenario.network) <= CROWDED
129        self._places = {
130            drone: AtZone(scenario.network.start)
131            for drone in range(1, scenario.nb_drones + 1)
132        }
133
134    def show_turn(self, index: int, moves: list[Move]) -> None:
135        """Play one turn of the run.
136
137        Args:
138            index: 1-based number of the turn.
139            moves: The drones that moved this turn.
140        """
141        if self._closed:
142            return
143        before = dict(self._places)
144        for move in moves:
145            self._places[move.drone_id] = move.placement
146        self._play(index, before)
147        self._deliver()
148
149    def finish(self, total_turns: int) -> None:
150        """Hold the last picture until the explosions are done.
151
152        Args:
153            total_turns: Length of the run.
154        """
155        if self._closed:
156            return
157        ends = pygame.time.get_ticks() + 2500
158        while not self._closed and pygame.time.get_ticks() < ends:
159            self._pump()
160            if self._closed:
161                break
162            self._paint(total_turns, dict(self._places), 1.0)
163            self._clock.tick(60)
164        self._shut()
165
166    def _open_font(self) -> None:
167        """Fetch a font and carry on without labels if there is none."""
168        factor = self._factor()
169        try:
170            self._font = pygame.font.Font(None, 7 * factor + 6)
171        except (pygame.error, NotImplementedError, ImportError):
172            self._font = None
173        self._font_factor = factor
174
175    def _load_sprites(self) -> None:
176        """Read the drone artwork, if it is there to read."""
177        names = (("drone0", "drone1"), ("droneexplode0", "droneexplode1"))
178        for target, group in zip((self._fly, self._boom), names):
179            for name in group:
180                path = os.path.join(ASSETS, f"{name}.png")
181                try:
182                    image = pygame.image.load(path)
183                except (pygame.error, OSError):
184                    target.clear()
185                    break
186                if target is self._boom:
187                    target.append(
188                        self._pixelate(image, BLAST_SIZE, burning=True)
189                    )
190                else:
191                    target.append(
192                        self._halo(self._pixelate(image, DRONE_SIZE))
193                    )
194
195    @staticmethod
196    def _halo(sprite: pygame.Surface) -> pygame.Surface:
197        """Trace a pale outline around a sprite.
198
199        The artwork is drawn in near-black, which disappears against
200        the grass. A one pixel outline keeps the silhouette readable
201        where the drone happens to be.
202
203        Args:
204            sprite: The sprite to outline.
205
206        Returns:
207            A sprite two pixels larger, outlined.
208        """
209        width, height = sprite.get_size()
210        lifted = pygame.Surface((width + 2, height + 2), pygame.SRCALPHA)
211        for x in range(width):
212            for y in range(height):
213                if sprite.get_at((x, y))[3] < 128:
214                    continue
215                for dx, dy in ((1, 0), (0, 1), (2, 1), (1, 2)):
216                    lifted.set_at((x + dx, y + dy), (*PAPER, 255))
217        lifted.blit(sprite, (1, 1))
218        return lifted
219
220    @staticmethod
221    def _pixelate(
222            image: pygame.Surface, size: int, burning: bool = False
223    ) -> pygame.Surface:
224        """Shrink a drawing and force it back onto the palette.
225
226        Args:
227            image: The artwork as it was loaded.
228            size: Width and height to shrink it to.
229            burning: Whether to recolor the grays as flame.
230
231        Returns:
232            The shrunken, palette-bound sprite.
233        """
234        small = pygame.transform.smoothscale(
235            image.convert_alpha(), (size, size)
236        )
237        for x in range(size):
238            for y in range(size):
239                red, green, blue, alpha = small.get_at((x, y))
240                if alpha < 128:
241                    small.set_at((x, y), (0, 0, 0, 0))
242                    continue
243                gray = (red, green, blue)
244                shade = ember(gray) if burning else snap(gray)
245                small.set_at((x, y), (*shade, 255))
246        return small
247
248    def _measure(self) -> None:
249        """Work out where each zone sits on the drawing surface."""
250        zones = list(self._scenario.network.zones.values())
251        bounds = Bounds.around(zones)
252        for zone in zones:
253            self._points[zone.name] = bounds.place(
254                zone.x, zone.y, WIDTH, HEIGHT - BAR, MARGIN
255            )
256
257    def _bake(self) -> pygame.Surface:
258        """Draw the ground once, to be blitted every frame.
259
260        Returns:
261            The grass, the dirt paths and the landing paths.
262        """
263        ground = pygame.Surface((WIDTH, HEIGHT))
264        seed = sum(
265            sum(ord(letter) for letter in name)
266            for name in self._scenario.network.zones
267        )
268        rng = Random(seed)
269        self._sow(ground, rng)
270        for link in self._scenario.network.connections.values():
271            self._tread(ground, link, rng, DIRT_DARK, 1)
272        for link in self._scenario.network.connections.values():
273            self._tread(ground, link, rng, DIRT, 0)
274        for zone in self._scenario.network.zones.values():
275            spot = self._points[zone.name]
276            pygame.draw.circle(ground, DIRT_DARK, spot, ZONE_RADIUS + 3)
277            pygame.draw.circle(ground, STONE, spot, ZONE_RADIUS + 2)
278        return ground
279
280    @staticmethod
281    def _sow(ground: pygame.Surface, rng: Random) -> None:
282        """Fill the surface with speckled grass.
283
284        Args:
285            ground: The surface to cover.
286            rng: The source of speckles, seeded from the map so the
287                same map always grows the same grass.
288        """
289        ground.fill(GRASS)
290        for _ in range(WIDTH * HEIGHT // 9):
291            x = rng.randrange(WIDTH)
292            y = rng.randrange(HEIGHT)
293            ground.set_at((x, y), rng.choice((GRASS_DARK, GRASS_LIGHT)))
294        for _ in range(WIDTH * HEIGHT // 400):
295            x = rng.randrange(WIDTH)
296            y = rng.randrange(2, HEIGHT)
297            ground.set_at((x, y), GRASS_LIGHT)
298            ground.set_at((x, y - 1), GRASS_LIGHT)
299            ground.set_at((x, y - 2), GRASS_DARK)
300
301    def _tread(
302        self,
303        ground: pygame.Surface,
304        link: Connection,
305        rng: Random,
306        color: RGB,
307        swell: int
308    ) -> None:
309        """Wear a dirt path between two zones.
310
311        The path is a run of small circles rather than a straight band:
312        a clean-edged band reads as a drawn line, and the whole point
313        of the generated ground is that it does not.
314
315        Args:
316            ground: The surface to draw on.
317            link: The connection to wear a path for.
318            rng: The source of the ragged edges.
319            color: The dirt shade to lay down.
320            swell: Extra width, used to lay a darker edge first.
321        """
322        start = self._points[link.a]
323        end = self._points[link.b]
324        thickness = min(1 + link.max_link_capacity, 7) + swell
325        steps = max(
326            abs(end[0] - start[0]), abs(end[1] - start[1]), 1
327        )
328        for step in range(steps + 1):
329            along = step / steps
330            x = round(start[0] + (end[0] - start[0]) * along)
331            y = round(start[1] + (end[1] - start[1]) * along)
332            radius = thickness + rng.choice((0, 0, 0, 1))
333            pygame.draw.circle(ground, color, (x, y), radius)
334
335    def _play(self, index: int, before: dict[int, Placement]) -> None:
336        """Animate one turn, honoring pauses and steps.
337
338        Args:
339            index: 1-based number of the turn.
340            before: Where every drone stood when the turn began.
341        """
342        frames = max(1, round(60 * self._turn_seconds))
343        frame = 0
344        while frame < frames and not self._closed:
345            self._pump()
346            if self._closed:
347                break
348            if self._paused and not self._stepping:
349                self._paint(index, before, frame / frames)
350                self._clock.tick(60)
351                continue
352            frame += 1
353            self._paint(index, before, frame / frames)
354            self._clock.tick(60)
355        self._stepping = False
356
357    def _deliver(self) -> None:
358        """Blow up the drones that reached the end zone this turn."""
359        now = pygame.time.get_ticks()
360        for drone, place in self._places.items():
361            if drone in self._delivered:
362                continue
363            if not isinstance(place, AtZone):
364                continue
365            if place.zone.role is not ZoneRole.END:
366                continue
367            self._delivered.add(drone)
368            spot = self._points[place.zone.name]
369            self._blasts.append(Blast(spot[0], spot[1], now))
370
371    def _pump(self) -> None:
372        """Read the keyboard and the window buttons."""
373        for event in pygame.event.get():
374            if event.type == pygame.QUIT:
375                self._shut()
376            elif event.type == pygame.VIDEORESIZE:
377                self._window = pygame.display.set_mode(
378                    event.size, pygame.RESIZABLE
379                )
380            elif event.type == pygame.KEYDOWN:
381                self._press(event.key)
382
383    def _press(self, key: int) -> None:
384        """Act on one key.
385
386        Args:
387            key: The pygame key code that went down.
388        """
389        if key in (pygame.K_q, pygame.K_ESCAPE):
390            self._shut()
391        elif key == pygame.K_SPACE:
392            self._paused = not self._paused
393        elif key == pygame.K_RIGHT:
394            self._paused = True
395            self._stepping = True
396        elif key in (pygame.K_PLUS, pygame.K_EQUALS, pygame.K_KP_PLUS):
397            self._turn_seconds = max(0.05, self._turn_seconds / 1.5)
398        elif key in (pygame.K_MINUS, pygame.K_KP_MINUS):
399            self._turn_seconds = min(3.0, self._turn_seconds * 1.5)
400        elif key == pygame.K_l:
401            self._labels = not self._labels
402        elif key in (pygame.K_f, pygame.K_F11):
403            self._toggle_fullscreen()
404
405    def _toggle_fullscreen(self) -> None:
406        """Swap between a window and the whole screen."""
407        self._fullscreen = not self._fullscreen
408        if self._fullscreen:
409            self._window = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
410        else:
411            self._window = pygame.display.set_mode(
412                (WIDTH * self._scale, HEIGHT * self._scale),
413                pygame.RESIZABLE,
414            )
415
416    def _shut(self) -> None:
417        """Close the window and stop drawing."""
418        if not self._closed:
419            self._closed = True
420            pygame.quit()
421
422    def _paint(
423        self, index: int, before: dict[int, Placement], along: float
424    ) -> None:
425        """Draw one frame and put it on the screen.
426
427        Args:
428            index: 1-based number of the turn being played.
429            before: Where every drone stood when the turn began.
430            along: How far through the turn this frame sits, 0 to 1.
431        """
432        self._captions.clear()
433        self._canvas.blit(self._ground, (0, 0))
434        self._draw_zones()
435        self._draw_drones(before, along)
436        self._draw_blasts()
437        self._draw_bar(index)
438        self._show()
439
440    def _draw_zones(self) -> None:
441        """Draw every zone and its name when labels are on."""
442        held = self._occupancy()
443        for zone in self._scenario.network.zones.values():
444            spot = self._points[zone.name]
445            if zone.zone_type is ZoneType.BLOCKED:
446                self._draw_rocks(spot)
447            else:
448                self._draw_pad(zone, spot)
449            if self._labels:
450                self._draw_name(zone, spot, held.get(zone.name, 0))
451
452    def _draw_pad(self, zone: Zone, spot: tuple[int, int]) -> None:
453        """Draw one zone the drones may stand in.
454
455        The fill is the map's own color and the outline is the zone
456        type, so the two never fight over the same pixels.
457
458        Args:
459            zone: The zone to draw.
460            spot: Where is sits on the surface.
461        """
462        radius = ZONE_RADIUS + (
463            1 if zone.role is not ZoneRole.INTERMEDIATE else 0
464        )
465        pygame.draw.circle(self._canvas, self._fill_of(zone), spot, radius)
466        pygame.draw.circle(self._canvas, INK, spot, radius, 1)
467        if zone.zone_type is ZoneType.PRIORITY:
468            pygame.draw.circle(self._canvas, PAPER, spot, radius + 2, 1)
469        elif zone.zone_type is ZoneType.RESTRICTED:
470            for step in range(8):
471                angle = step * 45
472                self._dot_ring(spot, radius + 2, angle)
473
474    @staticmethod
475    def _fill_of(zone: Zone) -> RGB:
476        """Pick the color a zone is filled with this frame.
477
478        A zone that calls itself rainbow names an animation rather
479        than a color, so it walks the bright end of the palette
480        instead of settling on one entry.
481
482        Args:
483            zone: The zone being drawn.
484
485        Returns:
486            The color to fill it with.
487        """
488        if zone.color is not None and zone.color.lower() == "rainbow":
489            step = pygame.time.get_ticks() // RAINBOW_MS
490            return RAINBOW[step % len(RAINBOW)]
491        return zone_rgb(zone.color)
492
493    def _dot_ring(
494        self, spot: tuple[int, int], radius: int, angle: int
495    ) -> None:
496        """Put one dot of a dashed ring around a zone.
497
498        Args:
499            spot: Center of the ring.
500            radius: How far out the dot sits.
501            angle: Where around the ring it sits, in degrees.
502        """
503        x = round(spot[0] + radius * cos(radians(angle)))
504        y = round(spot[1] + radius * sin(radians(angle)))
505        self._canvas.set_at((max(0, min(WIDTH - 1, x)),
506                             max(0, min(HEIGHT - 1, y))), PAPER)
507
508    def _draw_rocks(self, spot: tuple[int, int]) -> None:
509        """Draw a blocked zone as a heap of stones.
510
511        The lumps are measured from the zone radius rather than fixed,
512        so a blocked zone always fills as much room as a passable one
513        and reads as terrain instead of as a hole in the map.
514
515        Args:
516            spot: Where the zone sits on the surface.
517        """
518        pygame.draw.circle(self._canvas, DIRT_DARK, spot, ZONE_RADIUS)
519        big = max(3, ZONE_RADIUS * 3 // 5)
520        step = max(2, ZONE_RADIUS // 2)
521        lumps = (
522            (-step, step // 2, big),
523            (step, step // 2, big - 1),
524            (0, -step, big),
525        )
526        for dx, dy, size in lumps:
527            middle = (spot[0] + dx, spot[1] + dy)
528            pygame.draw.circle(self._canvas, STONE, middle, size)
529            pygame.draw.circle(self._canvas, INK, middle, size, 1)
530
531    def _draw_name(
532        self, zone: Zone, spot: tuple[int, int], held: int
533    ) -> None:
534        """Write a zone's name, and how full it is.
535
536        Args:
537            zone: The zone being labelled.
538            spot: Where it sits on the surface.
539            held: How many drones stand there right now.
540        """
541        text = zone.name
542        if zone.role is ZoneRole.INTERMEDIATE and held:
543            text = f"{text} {held}/{zone.max_drones}"
544        self._captions.append((spot[0], spot[1] + LABEL_DROP, text))
545
546    def _occupancy(self) -> dict[str, int]:
547        """Count the drones standing in each zone.
548
549        Returns:
550            Zone names mapped to how many drones they hold.
551        """
552        held: dict[str, int] = {}
553        for drone, place in self._places.items():
554            if drone in self._delivered or not isinstance(place, AtZone):
555                continue
556            held[place.zone.name] = held.get(place.zone.name, 0) + 1
557        return held
558
559    def _draw_drones(
560        self, before: dict[int, Placement], along: float
561    ) -> None:
562        """Draw every drone partway between its two positions.
563
564        Only drones standing still are ever left out. A crowded zone
565        would otherwise be a pile of sprites, so past a handful the
566        rest are counted instead of drawn. A drone on its way
567        somewhere is at a place of its own for the whole turn, so it
568        is always drawn however many share its destination.
569
570        Args:
571            before: Where every drone stood when the turn began.
572            along: How far through the turn this frame sits, 0 to 1.
573        """
574        crowds: dict[str, list[int]] = {}
575        for drone, place in sorted(self._places.items()):
576            if drone not in self._delivered:
577                crowds.setdefault(place.label(), []).append(drone)
578        for label, drones in crowds.items():
579            hidden = 0
580            for rank, drone in enumerate(drones):
581                resting = before[drone] == self._places[drone]
582                if rank >= SHOWN_PER_ZONE and resting:
583                    hidden += 1
584                    continue
585                self._draw_drone(
586                    drone, before, along, rank, len(drones)
587                )
588            if hidden and self._labels:
589                self._draw_crowd(label, hidden)
590
591    def _draw_drone(
592        self,
593        drone: int,
594        before: dict[int, Placement],
595        along: float,
596        rank: int,
597        crowd: int,
598    ) -> None:
599        """Draw one drone at its place in this frame.
600
601        Args:
602            drone: Identifier of the drone.
603            before: Where every drone stood when the turn began.
604            along: How far through the turn this frame its, 0 to 1.
605            rank: Its place in the queue sharing the same spot.
606            crowd: How many drones share that spot.
607        """
608        was = self._spot_of(before[drone])
609        now = self._spot_of(self._places[drone])
610        shift = (0, 0)
611        if crowd > 1:
612            shift = OFFSETS[rank % len(OFFSETS)]
613        x = round(was[0] + (now[0] - was[0]) * along) + shift[0]
614        y = round(was[1] + (now[1] - was[1]) * along) + shift[1]
615        if not self._fly:
616            pygame.draw.circle(self._canvas, PAPER, (x, y), 3)
617            pygame.draw.circle(self._canvas, INK, (x, y), 3, 1)
618            return
619        frame = (pygame.time.get_ticks() // FLAP_MS) % len(self._fly)
620        sprite = self._fly[frame]
621        self._canvas.blit(
622            sprite,
623            (x - sprite.get_width() // 2, y - sprite.get_height() // 2)
624        )
625
626    def _draw_crowd(self, label: str, extra: int) -> None:
627        """Say how many drones a spot holds beyond those drawn.
628
629        Args:
630            label: The placement the crowd shares.
631            extra: How many drones are not drawn.
632        """
633        spot = self._points.get(label)
634        if spot is None or self._font is None:
635            return
636        self._captions.append(
637            (spot[0] + ZONE_RADIUS + 8, spot[1] - 12, f"+{extra}")
638        )
639
640    def _spot_of(self, place: Placement) -> tuple[int, int]:
641        """Find the pixel a placement sits on.
642
643        A drone in flight hangs halfway along its connection, which is
644        what the placement already describes.
645
646        Args:
647            place: Where the drone is.
648
649        Returns:
650            The pixel to draw it at.
651        """
652        if isinstance(place, InFlight):
653            first = self._points[place.connection.a]
654            second = self._points[place.connection.b]
655            return ((first[0] + second[0]) // 2,
656                    (first[1] + second[1]) // 2)
657        return self._points[place.current_zone().name]
658
659    def _draw_blasts(self) -> None:
660        """Draw the explosion still playing, and drop the finished."""
661        now = pygame.time.get_ticks()
662        alive: list[Blast] = []
663        for blast in self._blasts:
664            frame = (now - blast.started) // BOOM_MS
665            if not self._boom:
666                continue
667            if frame >= len(self._boom):
668                continue
669            alive.append(blast)
670            sprite = self._boom[int(frame)]
671            self._canvas.blit(
672                sprite,
673                (blast.x - BLAST_SIZE // 2, blast.y - BLAST_SIZE // 2)
674            )
675        self._blasts = alive
676
677    def _draw_bar(self, index: int) -> None:
678        """Lay out the strip of numbers and keys along the bottom.
679
680        The bar ignores the label switch: it is the only thing telling
681        you which keys exist, so hiding it would hide the way to bring
682        it back.
683
684        Args:
685            index: 1-based number of the turn being played.
686        """
687        pygame.draw.rect(
688            self._canvas, INK, pygame.Rect(0, HEIGHT - BAR, WIDTH, BAR)
689        )
690        pygame.draw.line(
691            self._canvas, MUTED,
692            (0, HEIGHT - BAR), (WIDTH, HEIGHT - BAR),
693        )
694        delivered = f"{len(self._delivered)}/{self._scenario.nb_drones}"
695        self._status = [
696            ("turn ", MUTED),
697            (str(index), PAPER),
698            ("   delivered ", MUTED),
699            (delivered, PAPER),
700        ]
701        self._bar = []
702        keys = (
703            ("space", "resume" if self._paused else "pause"),
704            ("right", "step"),
705            ("+/-", "speed"),
706            ("l", "labels"),
707            ("f", "fullscreen"),
708            ("q", "quit"),
709        )
710        for key, action in keys:
711            if self._bar:
712                self._bar.append(("    ", MUTED))
713            self._bar.append((key.upper() + " ", HINT))
714            self._bar.append((action, MUTED))
715
716    def _show(self) -> None:
717        """Blow the drawing up to the window and flip it.
718
719        The scale is kept whole so every drawn pixel stays a square
720        block; whatever does not divide evenly becomes a border.
721        """
722        window = self._window.get_size()
723        factor = self._factor()
724        size = (WIDTH * factor, HEIGHT * factor)
725        corner = ((window[0] - size[0]) // 2, (window[1] - size[1]) // 2)
726        self._window.fill(INK)
727        self._window.blit(
728            pygame.transform.scale(self._canvas, size), corner
729        )
730        self._write_captions(corner, factor)
731        self._write_bar(corner, factor)
732        pygame.display.flip()
733
734    def _factor(self) -> int:
735        """Work out how many screen pixels one drawn pixel takes.
736
737        Returns:
738            The whole number the drawing is blown up by.
739        """
740        window = self._window.get_size()
741        return max(1, min(window[0] // WIDTH, window[1] // HEIGHT))
742
743    def _write_captions(
744        self, corner: tuple[int, int], factor: int
745    ) -> None:
746        """Write the queued text straight onto the window.
747
748        Args:
749            corner: Where the blown-up drawing starts on the window.
750            factor: How many screen pixels one drawn pixel takes.
751        """
752        if self._font is None:
753            return
754        if factor != self._font_factor:
755            self._open_font()
756            if self._font is None:
757                return
758        for x, y, text in self._captions:
759            drawn = self._font.render(text, True, PAPER, INK)
760            top = corner[1] + y * factor
761            middle = corner[0] + x * factor - drawn.get_width() // 2
762            self._window.blit(drawn, (middle, top))
763
764    def _write_bar(self, corner: tuple[int, int], factor: int) -> None:
765        """Write the status bar across the bottom of the window.
766
767        The keys sit in the middle and the running totals in the right
768        corner, so the numbers never shuffle the keys sideways as they
769        grow. On a narrow window the keys give way rather than run
770        into the totals.
771
772        Args:
773            corner: Where the blown-up drawing starts on the window.
774            factor: How many screen pixels one drawn pixel takes.
775        """
776        if self._font is None:
777            return
778        keys = self._render(self._bar)
779        totals = self._render(self._status)
780        keys_width = sum(piece.get_width() for piece in keys)
781        totals_width = sum(piece.get_width() for piece in totals)
782        strip = corner[1] + (HEIGHT - BAR) * factor
783        y = strip + (BAR * factor - self._font.get_height()) // 2
784        width = WIDTH * factor
785        right = corner[0] + width - totals_width - 4 * factor
786        middle = corner[0] + (width - keys_width) // 2
787        middle = min(middle, right - keys_width - 6 * factor)
788        self._blit_run(keys, max(corner[0] + 2 * factor, middle), y)
789        self._blit_run(totals, right, y)
790
791    def _render(
792        self, pieces: list[tuple[str, RGB]]
793    ) -> list[pygame.Surface]:
794        """Draw each colored piece of the bar on its own.
795
796        Args:
797            pieces: The text and color of each piece.
798
799        Returns:
800            One surface per piece, in order.
801
802        Raises:
803            ValueError: If no font was opened.
804        """
805        if self._font is None:
806            raise ValueError("no font to write the bar with")
807        return [self._font.render(text, True, tone) for text, tone in pieces]
808
809    def _blit_run(
810        self, pieces: list[pygame.Surface], x: int, y: int
811    ) -> None:
812        """Lay a row of pieces down side by side.
813
814        Args:
815            pieces: The surfaces to place.
816            x: Where the row starts.
817            y: The top of the row.
818        """
819        for piece in pieces:
820            self._window.blit(piece, (x, y))
821            x += piece.get_width()