# Skill: C64 Programming Practices, Patterns, Hints, and Optimization ## Use this skill when The task asks for design advice, best practices, performance improvements, code organization, hybrid BASIC/ML strategy, or C64-specific programming patterns. ## Practices ### Use the right layer - BASIC is excellent for quick control flow, menus, simple loaders, demos, and teaching. - Assembly is best for speed, graphics effects, sound engines, raster work, custom I/O, compression, and tight loops. - KERNAL calls are best for portability and standard I/O. - Direct hardware access is best when KERNAL overhead or abstraction gets in the way. ### Keep ML small and callable Build small routines with clear entry and exit conditions. Document: - Entry address. - Input registers/memory. - Output registers/memory. - Clobbered registers. - Zero-page locations used. - Whether interrupts must be enabled/disabled. ### Prefer tables Tables are often faster and simpler than computation on a 1 MHz CPU: - Screen row address tables. - Sprite animation pointer tables. - Sine/cosine movement tables. - Frequency tables for notes. - Bit masks. ### Preserve bits Hardware registers often pack unrelated settings into one byte. Use `AND`/`OR` masks instead of blind `STA`/`POKE` unless replacing the whole register is intended. ### Respect PETSCII vs screen codes - `CHROUT` expects PETSCII-style character output. - Screen RAM expects screen codes. - Key codes are different again. ### Optimize only where needed First make the code correct and stable. Then optimize hot paths: - Use zero-page addressing. - Unroll small loops when timing matters. - Avoid BASIC inside animation loops when ML is available. - Avoid multiplication/division in raster-critical paths. - Use precomputed tables. ### Keep recovery paths - Use emulator snapshots. - Keep STOP/RESTORE or reset strategy when possible. - Include a routine to restore vectors and screen colors. - Save original IRQ/NMI vectors before patching. ## Common patterns ### BASIC bootstrap + ML engine BASIC loads/starts; ML handles fast loop. ### ML service routine called by BASIC BASIC manages user interaction; ML performs fast operation. ### KERNAL I/O wrapper ML uses KERNAL jump table for file/device operations. ### Raster IRQ effect ML installs IRQ handler; handler changes VIC registers at specific raster lines. ### Double-buffered graphics data Prepare screen/sprite/bitmap data off-screen, then switch pointers/registers. ## Agent checklist 1. Choose BASIC, assembly, or hybrid explicitly. 2. Avoid magic numbers; name addresses and masks. 3. Show restore/cleanup logic. 4. Explain cycle/timing assumptions for demos/games. 5. Favor reusable routines over one-off POKEs.