# SPDX-License-Identifier: MIT """Saved pictures: the board's frame as the player sees it, written as PNG. The LCD is 160 x 102 (landscape). Some carts are played with the console turned on its side; the cart (not the hardware) says so in its rotation field (LNX header byte 58: 0 none, 1 left, 2 right; or the cart table: docs/cartridge.md). The board never rotates anything (start-here.md "Output"); a host that shows or saves the picture turns it so the game reads upright. Direction. Looked at on this board's own pictures, 2026-11-14 (docs/validation.md "Saved pictures follow the cart's rotation"): Klax (table: right) reads upright after a quarter turn clockwise and upside down after a quarter turn anticlockwise; Centipede (Proto) (table: left) the other way round. No document defines the field's direction (HYPOTHESIS for carts whose text cannot be looked at: the same rule). """ from __future__ import annotations import struct import zlib from pathlib import Path WIDTH, HEIGHT = 160, 102 def rotate(rgb: bytes, rotation: str, width: int = WIDTH, height: int = HEIGHT): """Turn an RGB picture for the cart's rotation; returns (rgb, width, height). ``right``: a quarter turn clockwise; ``left``: a quarter turn anticlockwise; ``none``: unchanged (see the module text for the evidence). """ if rotation not in ("left", "right"): return bytes(rgb), width, height out = bytearray(len(rgb)) for y in range(height): for x in range(width): if rotation == "right": # clockwise: (x, y) -> (height - 1 - y, x) nx, ny = height - 1 - y, x else: # anticlockwise: (x, y) -> (y, width - 1 - x) nx, ny = y, width - 1 - x src = 3 * (y * width + x) dst = 3 * (ny * height + nx) out[dst : dst + 3] = rgb[src : src + 3] return bytes(out), height, width def scale(rgb: bytes, width: int, height: int, factor: int) -> bytes: """Nearest-neighbour enlargement (for looking at a picture, not for judging).""" out = bytearray() for y in range(height): row = bytearray() for x in range(width): row += rgb[3 * (y * width + x) : 3 * (y * width + x) + 3] * factor out += bytes(row) * factor return bytes(out) def write_png(path: Path, rgb: bytes, width: int = WIDTH, height: int = HEIGHT) -> None: """An 8-bit RGB PNG (the format's own chunks; no library).""" rows = b"".join(b"\x00" + rgb[y * width * 3 : (y + 1) * width * 3] for y in range(height)) def chunk(kind: bytes, data: bytes) -> bytes: body = kind + data return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body)) header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) png += chunk(b"IDAT", zlib.compress(rows, 9)) + chunk(b"IEND", b"") path.write_bytes(png) def save(path: Path, rgb: bytes, rotation: str = "none") -> None: """Save the frame as the player sees it: turned for the cart's rotation.""" turned, width, height = rotate(rgb, rotation) write_png(path, turned, width, height)