AI-Assisted Porting of NES Fighting-Game Logic to UEFI: A Practical Guide

    This article presents a practical workflow for porting self-authored NES fighting-game logic to an x86_64 UEFI environment with AI assistance. It covers UEFI graphics configuration, 6502 code analysis, tile and palette conversion, screenshot-based validation, AI limitations, and the manual checks required to catch memory, rendering, state-machine, and gameplay-data errors. The examples are intended for original or properly authorized ROMs.

    Scope and Prerequisites

    The test ROM used in this article was written by the author. All graphics and code are original and contain no copyrighted commercial assets. The terms “disassembly” and “translation” refer to analyzing and rewriting self-authored code. They do not involve extracting another party’s game or bypassing copyright protection. When reproducing the workflow, use a self-created ROM or a ROM for which you have explicit authorization.

    Environment and Key Parameters

    The target platform is x86_64 UEFI, with the program running in the UEFI Shell. The project uses the EDK II build system and clang. Testing is performed in QEMU with OVMF firmware. Screenshots are saved as PNG files and compared pixel by pixel with reference images.

    Graphics output is one of the easiest areas to get wrong, so the geometry must be calculated first. The original NES display is 256 × 240 pixels. At 1024 × 768, the width can be scaled by 4, but the height can only be scaled by 3.2. A single integer scale factor therefore cannot fill both dimensions. Two approaches are available:

    • Option 1: Request a 1024 × 960 mode and scale the image by 4 to fill the screen. Support must be confirmed by enumerating the available GOP modes.
    • Option 2: Keep 1024 × 768 and scale by 3, producing a 768 × 720 image. Leave 128-pixel black borders on the left and right, and 24-pixel borders at the top and bottom.

    Neither approach uses fractional scaling, avoiding misaligned pixel edges.

    The code should explicitly record the following GOP parameters:

    • Mode number
    • Pixel format
    • Horizontal resolution
    • PixelsPerScanLine

    PixelsPerScanLine is the actual number of pixels allocated per row and may be greater than the visible horizontal resolution. It must be used when calculating offsets. Do not substitute the horizontal resolution.

    Common pixel formats use either BGR or RGB ordering, with 4 bytes per pixel. On x86 little-endian systems:

    • For BGRX, write the uint32 value 0x00RRGGBB.
    • For RGBX, write 0x00BBGGRR.

    A QEMU command line similar to the following can be used. Adjust the paths for the local environment:

    1. qemu-system-x86_64 -bios OVMF.fd -drive format=raw,file=fat:rw:esp -vga std -m 256M

    Record the toolchain versions—including the EDK II commit, clang, QEMU, and OVMF versions—in the repository documentation. Without fixed versions, screenshot comparisons may not be reproducible.

    Four-Stage Workflow

    The project is divided into four stages, each with defined inputs, outputs, and acceptance criteria.

    Stage Input Output Acceptance criteria
    1. Map startup and the main loop Complete disassembly text Execution paths, data-region ranges, and a basic-block control-flow graph Every basic block identifies its source and destination; code and data regions do not overlap
    2. Parse the core logic Individual basic blocks or functions Commented high-level functions Every function has a corresponding test case, and all tests pass
    3. Reconstruct graphics and palettes Pattern tables, attribute tables, and palette data Linear 32-bit framebuffer data The converted output matches the reference screenshot pixel by pixel
    4. Iterate and correct visual output Runtime screenshots and issue descriptions Corrected data or code Screenshots of the same scene match the reference image

    Stage 1: Startup and Main-Loop Analysis

    The first stage is difficult because the code contains many jumps. An AI model can easily loop between mutually dependent blocks during analysis. A more reliable approach is to split the program into basic blocks, draw a control-flow graph, and provide the blocks to the model one at a time.

    Data regions must be marked separately. Otherwise, the model may interpret data as instructions.

    Stage 2: Understanding Core Logic

    The meaning of bit flags must be established before translating the code. 6502 programs often depend heavily on bit operations and conditional branches. If the model does not know whether a bit means “facing right” or “has been hit,” it may produce a clean-looking high-level function with incorrect behavior.

    Add tests immediately after implementing each function.

    Stage 3: Converting Tiles and Palettes

    The conversion process depends on three concepts:

    1. NES pattern tables store graphics as 8 × 8 tiles, with 16 bytes per tile. Each row contains one byte for the low bit plane and one byte for the high bit plane. Combining the planes produces a per-pixel index from 0 to 3.
    2. The attribute table assigns a palette group to each 32 × 32-pixel area, effectively defining the palette for each 16 × 16 region.
    3. Palette RAM contains 32 bytes. Each entry is a 6-bit index into the 64-color master palette. Palette index 0 represents the background color for background tiles and transparency for sprites.

    A simplified conversion script is:

    1. for each tile (tx, ty) in nametable:
    2. pal = attribute_palette(tx, ty)
    3. for row in 0..7:
    4. lo = chr[tile*16 + row]
    5. hi = chr[tile*16 + row + 8]
    6. for col in 0..7:
    7. bit = 7 - col
    8. idx = (((hi >> bit) & 1) << 1) | ((lo >> bit) & 1)
    9. if idx == 0: color = backdrop
    10. else: color = master[palette_ram[pal*4 + idx] & 0x3F]
    11. write_pixel(tx*8 + col, ty*8 + row, color)

    This conversion is performed only when reading the data. The original pattern and palette data remain unchanged. When writing to the framebuffer, expand each pixel according to the integer scale factor and calculate row offsets using PixelsPerScanLine.

    Stage 4: Iteration and Visual Correction

    Common problems include misalignment, corrupted graphics, and incorrect colors. First determine whether the problem comes from data offsets, index mapping, or drawing parameters. Then correct each category separately.

    Symptom Check first Common cause
    The entire image is shifted Data start address, scale factor, and border offsets Using horizontal resolution instead of PixelsPerScanLine
    Corrupted graphics or scattered blocks Tile indices and pattern-table base address Reversed bit-plane order or out-of-range tile numbers
    Colors are globally offset Palette indices and masking Failing to mask the master-palette index to 6 bits
    Blocks appear around sprites Transparency handling Not skipping palette index 0

    What AI Tools Can and Cannot Do

    For code comprehension, AI performs relatively well on individual arithmetic functions and simple branches. Its reliability drops when global variables and cross-file control flow are involved. The problem is especially visible in character-decision logic, where many conditions exist and the model may omit a variable reset required by one branch.

    For visual comparison, a model can usually distinguish a title screen, menu, and versus screen, but its judgment of fine details is unreliable. It may miss issues such as a character’s arm spilling into the body by a few pixels or incorrectly identify which palette entry should become dark red.

    During one sprite-rendering debugging session, the model repeatedly failed to notice that the image had been split into horizontal strips. It recognized the problem only after the author marked the affected area on the screenshot.

    Visual comparisons should therefore include annotated screenshots, pixel coordinates, and an explicit description of the expected result. Prompt structure also affects the outcome.

    Question style Example Typical result
    Open-ended visual question “Why is this image corrupted?” The model guesses from the image, so the conclusion may be unreliable
    Static code review “Check whether this texture-loading function can write beyond PixelsPerScanLine × height when updating the framebuffer.” The model analyzes familiar code patterns, and the result can be verified against the code

    Static review is useful for detecting out-of-bounds access, overflow, and incomplete state cleanup. It cannot replace screenshot inspection; the two methods should be used together.

    AI is also weak at tracking cascading changes. For example, it may change how function A is called without updating function B, which still references the same address under the old assumption. A new rendering error can appear immediately.

    After every modification, search the entire codebase for all references to the changed symbol and verify them individually.

    Manual Review Checklist

    At least the following five items should be checked after every AI-generated change:

    Check Method Failure symptom Corrective action
    Memory accesses stay within the buffer Add runtime assertions that offsets are smaller than the buffer size Tearing, crashes, or overwriting other variables Correct loop bounds or offset calculations
    Palette indices are valid Assert that indices are below the palette size and that master-palette indices do not exceed 63 Incorrect colors Fix the index mask
    Structure layout matches the original Use static_assert to verify offsetof values and field sizes Incorrect fields are read Adjust field order or alignment
    State-machine resets cover every branch Add tests for each state transition and verify all variables after exit A character remains stuck in a state Add missing reset logic
    Character attributes stay within design limits Assert maximum health, initial state, and other values after initialization A character starts in an invalid condition Correct the data table and run regression tests

    In this case, the AI assigned one character an unreasonable maximum health value. The character therefore started in a stunned state. The program did not crash, and the problem appeared only during actual gameplay.

    Errors of this kind cannot be detected through compilation or static checks alone. Reproduce the issue by initializing the character, printing the maximum-health value and the value used for the stun check, and asserting that both fall within the intended design range.

    Recommendations for Debugging Records

    Record every important debugging decision. Store the screenshot filename, the pixel coordinates of marked regions, and the prompt version used for the analysis.

    This allows the team to reproduce incorrect AI judgments and compare the results of different prompts.

    Scope and Conclusion

    This workflow is suitable for self-authored ROMs and demonstration-scale programs. It does not cover commercial ROMs, complex mappers, cycle-accurate interrupt timing, or audio processing. These areas require a separate evaluation before the method is applied.

    In this example, AI accelerated disassembly analysis and the construction of code skeletons. Pixel-level fixes and numeric semantics still required manual, item-by-item verification. AI is closer to a junior engineer who needs precise instructions than to an autonomous system capable of restoring complex data independently.

    Moving from “the program runs” to “the output matches the intended result” still requires substantial human effort. If AI tools improve at visual comparison and dependency tracking, they may change how retro-game ports and compatibility layers for legacy systems are developed. That possibility requires further practical validation.