219. Mapper000 chr rom

add

Lesson 219 of 356 · tests/chapter_02_rom_loading/test_219_mapper000_chr_rom.py

add emulator/cartridge/mapper000.py::Mapper000.read_chr.

Why this step exists

This stabilizes access to NROM's 8 KiB graphics payload before a PPU bus exists. Lesson 218's PRG mapping and Mapper000 structure are prerequisites.

Complete example implementation after this lesson

from dataclasses import dataclass

PRG_ROM_START = 0x8000
PRG_ROM_END = 0xFFFF
NROM_128_SIZE = 16 * 1024
NROM_256_SIZE = 32 * 1024
CHR_ROM_START = 0x0000
CHR_ROM_END = 0x1FFF
CHR_ROM_SIZE = 8 * 1024


@dataclass(frozen=True)
class Mapper000:
    prg_rom: bytes
    chr_rom: bytes

    def read_prg(self, addr: int) -> int:
        if not (PRG_ROM_START <= addr <= PRG_ROM_END):
            raise ValueError(
                f"Address out of PRG ROM range: {addr:04X}"
            )
        if len(self.prg_rom) == NROM_128_SIZE:
            offset = (addr - PRG_ROM_START) % NROM_128_SIZE
        elif len(self.prg_rom) == NROM_256_SIZE:
            offset = addr - PRG_ROM_START
        else:
            raise ValueError(
                "Mapper000 supports only 16KB or 32KB PRG ROM"
            )
        return self.prg_rom[offset]

    def read_chr(self, addr: int) -> int:
        if not (CHR_ROM_START <= addr <= CHR_ROM_END):
            raise ValueError(
                f"Address out of CHR ROM range: {addr:04X}"
            )
        if len(self.chr_rom) != CHR_ROM_SIZE:
            raise ValueError("Mapper000 expects 8KB CHR ROM")
        offset = addr - CHR_ROM_START
        return self.chr_rom[offset]

Invariants: accept only PPU $0000-$1FFF, require exactly 8 KiB CHR ROM, and map endpoints to offsets 0 and 8191 without changing lesson 218's PRG behavior. Do not confuse this PPU-side range with CPU PRG $8000-$FFFF.

Out of scope for this step

1. Lesson 220 creates mappers from cartridge metadata.
2. PPU/PpuBus wiring and writable CHR RAM come later.
3. Mapper writes, nametable mirroring, and bank switching come later.

Run this lesson

uv run pytest tests/chapter_02_rom_loading/test_219_mapper000_chr_rom.py -v