Porting a Classic Bomberman-Style Game from a C++ Graphics Library to UEFI: Architecture Rewrite and Cost Assessment

    Porting a graphical game to the UEFI Shell is an extreme test of an LLM's ability to generate and refactor code. Using a classic Bomberman-style game (a 15×15 grid, destructible and indestructible walls, four-directional blasts, multiple enemy AIs, and power-ups) as a case study, this article breaks down the key difficulties of moving to UEFI, summarizes effective AI-assisted coding practices, and presents a self-testable framework for model evaluation and cost control. It covers constraint analysis, the shift from object-oriented to data-oriented architecture, building a display pipeline on the Graphics Output Protocol, replacing event callbacks with polling, game logic such as bombs, danger maps, and enemy AI, debugging techniques, and a vendor-neutral way to decide whether the effort is worth it.

    1. Introduction: Writing Code Under the Most Constrained Conditions

    Porting a graphical game to the UEFI Shell is an “extreme scenario” for testing an LLM’s code generation and refactoring ability. It demands four things from the model at once: cross-language semantic-equivalent rewriting, an understanding of low-level system interfaces, cross-file architectural consistency, and the iterative fixing of compile errors and runtime faults.

    This article takes a classic Bomberman-style game built with C++ and a cross-platform graphics library (15×15 grid map, destructible and indestructible walls, four-directional blasts, multiple enemy AIs, and power-ups) as its subject. It breaks down the key difficulties of porting to UEFI, summarizes effective methods for AI-assisted coding, and finally offers a self-testable framework for model evaluation and cost control. It mentions no specific products; the core goal is to help developers turn “can it be used” into “how to use it well and cost-effectively.”

    2. Constraint Analysis: What UEFI Actually Lacks

    A UEFI application is loaded and executed by the firmware during the power-on self-test (POST) phase and runs within the boot-services environment the firmware provides. It is not an operating system, and it lacks the following infrastructure:

    • No language runtime: What is available is mainly a C-oriented development subset; modern C++ standard library facilities cannot be relied on.
    • No high-level abstractions: There is no graphics library, window system, or threading library; you can only call protocol interfaces directly.
    • Different memory model: While boot services are available, heap memory can be allocated through pool-allocation interfaces; but once ExitBootServices is called, the firmware reclaims the pool memory entirely. All allocation must therefore be completed before entering the main loop, after which you work only with static data regions and the stack.
    • Uncertain resource acquisition: Although a file protocol exists, whether a usable file system is mounted on the boot medium depends on platform configuration, so resources cannot be assumed to be “read from disk.”

    Thus, the first step of the port is not writing code but mapping each dependency of the original project onto the new environment. The table below gives a typical mapping:

    Capability dimension Common approach in native projects Available approach in UEFI
    Containers Dynamic-array class containers Fixed-length arrays + free list, allocated once at startup
    Object lifetime Smart pointers, automatic ownership management Manual reclamation, generation tags to prevent dangling references
    Polymorphism Base class + virtual functions Type tag + function-pointer dispatch table, or inlined switch
    Graphics output Graphics-library window and drawing APIs Graphics Output Protocol + software rasterization and pixel buffer
    Input Event callbacks, window messages Polling keyboard input, combined with timer events to drive a fixed step
    Resource loading Reading image and font files at runtime Offline conversion and embedding as compile-time data
    Time base High-precision monotonic clock High-precision timer object + firmware timer events

    3. Architecture Rewrite: From Object-Oriented to Data-Oriented

    3.1 Replacing the Inheritance Hierarchy with Type Tags

    In the original project, objects such as characters, bombs, blasts, and enemies typically share a base class and implement “each with its own behavior” through virtual functions. In a C environment, virtual functions are no longer available. A more robust approach is to describe entity kinds with an enum type tag and centralize behavior into a unified dispatch function:

    1. typedef enum { ACT_IDLE, ACT_MOVE, ACT_BOMB, ACT_FUSE, ACT_BLAST } ActType;
    2. typedef struct { int x, y; } Grid;
    3. typedef struct {
    4. int alive;
    5. ActType type;
    6. Grid pos;
    7. int speed; /* move one cell every few ticks */
    8. int power; /* number of flame-extension cells */
    9. int capacity; /* max bombs that may exist at once */
    10. int timer; /* countdown or duration in frames */
    11. int dir; /* most recent heading */
    12. Grid dest; /* movement target cell */
    13. void (*update)(struct Entity *e);
    14. } Entity;
    15. /* Centralized dispatch: replaces the virtual-function table */
    16. void EntityUpdate(Entity *e) {
    17. if (e->type == ACT_BLAST) {
    18. e->timer--;
    19. if (e->timer <= 0) { e->alive = 0; return; }
    20. }
    21. if (e->update) e->update(e);
    22. }

    Putting the function pointer at the end of the struct rather than the beginning keeps the memory layout compact and makes whole-struct clearing and copying easy.

    3.2 From an Inheritance Hierarchy to Component-Style Data Organization

    The class inheritance of the original code can be summarized as a tree: “movable entity (position, speed, update logic) → character / enemy / bomb / blast,” with each branch extending further. Copying this hierarchy brings two problems: first, function-pointer members are scattered across layers, requiring layer-by-layer dereferencing to invoke; second, small structs produce substantial alignment padding in fixed-length arrays.

    This article uses a combination of a “grid static layer + entity pool dynamic layer”:

    • Static layer: map matrix (wall-type encoding), danger-cell matrix, and the object number attached to each cell. Walls are only rewritten when destroyed and do not occupy an entity slot.
    • Dynamic layer: the entity pool uniformly holds characters, enemies, bombs, and blasts, distinguished by a type field. This requires only one update dispatch and one collision-traversal logic.
    1. typedef struct {
    2. int cell[MAX_H][MAX_W]; /* wall-type encoding */
    3. int danger[MAX_H][MAX_W]; /* danger flag */
    4. int occupant[MAX_H][MAX_W]; /* entity id on this cell; -1 means empty */
    5. Entity pool[MAX_ENTITIES]; /* fixed-length entity pool */
    6. int free_head; /* head of the free list */
    7. } World;
    8. Entity *Spawn(World *w, ActType t, int cx, int cy) {
    9. if (w->free_head < 0) return 0;
    10. int id = w->free_head;
    11. w->free_head = w->pool[id].next_free;
    12. Entity *e = &w->pool[id];
    13. memset(e, 0, sizeof(*e));
    14. e->alive = 1; e->type = t; e->id = id; e->pos.x = cx; e->pos.y = cy;
    15. w->occupant[cy][cx] = id;
    16. return e;
    17. }

    3.3 The Memory Budget Must Be Computed Explicitly

    A bare-metal environment has no OS-level memory protection as a safety net; a single out-of-bounds write can directly corrupt firmware data. Before porting, the budget should be worked out clearly. For a 15×15 grid, for example:

    • The map and danger matrices take about 450 bytes;
    • With an entity-pool cap of 1024 and an estimated 64 bytes per entity, that is about 64 KB;
    • Double-buffered pixel data at 960×960, 32bpp takes about 7 MB.

    All of these must be allocated in one shot during the boot-services phase and recorded in an explicit budget table for cross-checking during later expansion.

    4. Rendering Layer: Building a Display Pipeline on the Graphics Output Protocol

    4.1 From a Window Surface to a Pixel Buffer

    A native program treats the window surface as its drawing target and presents it frame by frame via the graphics library. After porting, you must first query the Graphics Output Protocol to obtain the resolution, pixel format, and scanline byte stride. The pixel format may be 32bpp BGRA/BGRX, or 24bpp or a masked format, so every drawing function must first “normalize the format” before double buffering can even be discussed.

    4.2 The Benefits and Costs of Double Buffering

    At 960×960 full resolution, a full per-frame copy is about 3.5 MB of pixels. In a firmware environment, repeatedly copying the whole canvas creates considerable host-side bandwidth pressure. Compromises:

    • Keep the back buffer in normal (cacheable) memory and submit only the dirty rectangles that have changed to the display buffer;
    • Or use an off-screen intermediate buffer to do composition, avoiding repeated reads and writes to display memory;
    • Call the protocol’s vertical-retrace synchronization interface before submitting to reduce the chance of screen tearing.

    4.3 Sprites and Fonts: Simplifying Resource Formats

    A 32×32 TGA sprite only needs to parse three parts: “file header + optional palette + raw pixel array.” Uncompressed TGA is read byte by byte, far simpler than reimplementing the PNG decompression chain; an even more thorough approach is to convert TGA offline to a BGRA array at build time, so the program retains no image-parsing code at all. Alpha blending is done by a hand-written loop:

    1. static void BlitBlend(uint8_t *dst, int dst_stride,
    2. const uint8_t *src, int w, int h)
    3. {
    4. int x, y;
    5. for (y = 0; y < h; y++) {
    6. uint32_t *d = (uint32_t *)((uint8_t *)dst + y * dst_stride);
    7. for (x = 0; x < w; x++) {
    8. uint32_t s = src[(y * w + x) * 4 + 0]
    9. | (src[(y * w + x) * 4 + 1] << 8)
    10. | (src[(y * w + x) * 4 + 2] << 16)
    11. | (src[(y * w + x) * 4 + 3] << 24);
    12. uint8_t a = (uint8_t)(s >> 24);
    13. if (a == 0) continue;
    14. if (a == 255) { d[x] = s; continue; }
    15. uint8_t dr = (uint8_t)d[x], dg = (uint8_t)(d[x] >> 8);
    16. uint8_t db = (uint8_t)(d[x] >> 16);
    17. uint8_t sr = (uint8_t)s, sg = (uint8_t)(s >> 8);
    18. uint8_t sb = (uint8_t)(s >> 16);
    19. int ia = 255 - a;
    20. d[x] = (uint32_t)((sr * a + dr * ia) / 255)
    21. | ((uint32_t)((sg * a + dg * ia) / 255) << 8)
    22. | ((uint32_t)((sb * a + db * ia) / 255) << 16);
    23. }
    24. }
    25. }

    4.4 Text Rendering

    Bitmap fonts fit a bare-metal environment better than vector fonts: each ASCII character is stored as a 16×16 monochrome bitmap, 95 characters in total, roughly 190 bytes per font set; at draw time you simply sample points by bit and fill rectangles, which avoids a font-parsing library while guaranteeing legibility at small sizes.

    5. Input and the Main Loop: Turning Event Callbacks into Polling

    5.1 No Key-Release Events, Only an “Event Stream”

    The event-driven model of graphical games does not hold in a bare-metal environment: the console input protocol provides key codes in the form of “pollable events,” and the read interface returns success only when there is a new keypress in the buffer. Key porting points:

    • Call the read interface once per logical frame and push the returned scan code and character into an input queue;
    • Because polling can only obtain “the moment of a press,” you must maintain your own key-state table and simulate the held-down effect using the “last-pressed frame number”;
    • If the repeat interval is shorter than the logical frame length, de-duplicate in the queue to avoid one movement being consumed as several.
    1. static int key_held(int code, int now, int window) {
    2. return (now - g_key_last[code]) <= window;
    3. }

    5.2 Fixed Step + Variable Rendering

    Separate “update” from “present”: updates advance on a fixed tick (say 60 Hz), while rendering follows the current frame number, using accumulated time to decide how many ticks to run this round. This way it does not depend on an uncontrollable frame rate, and things like bomb countdowns and enemy pathfinding can be computed deterministically in units of “frames.” The timer can be polled via a high-precision timer object or driven by a periodic notification event, but avoid doing lengthy computation inside the callback, or it will slow down the firmware’s critical path.

    5.3 Collision and Movement

    Movement in grid games is measured in cells, but characters can interpolate smoothly. In implementation, separate the “target cell” from the “current cell”: only when the character reaches the cell center and the target cell is passable does the grid coordinate change; the intermediate interpolation only affects the drawing position. This way, both the bomb’s “stop as soon as you step on it” and the blast’s “extend cell by cell along a passage” can use the same cell-based logic, greatly reducing the number of logic branches.

    6. Game Logic: Blasts, Danger Cells, and Enemy AI

    6.1 Bombs and Flames

    A bomb entity contains three key fields: the countdown, the blast power, and a flag indicating “whether it can be destroyed by a bullet-type blast.” When a blast is generated, it advances cell by cell from the bomb’s cell in four directions:

    1. Stop immediately upon hitting an indestructible wall;
    2. Upon hitting a destructible wall, destroy that wall and terminate in that direction;
    3. Upon hitting the first bomb, trigger a chain detonation and terminate in that direction;
    4. In all other cases, continue advancing and mark the cell as dangerous.

    6.2 The Danger-Cell Matrix Is the Core AI Input

    The danger-cell matrix is updated whenever a blast begins and ends, and all enemy AIs read the same data. The benefit is logical decoupling: the pathfinding algorithm only cares “whether this cell is safe right now” and does not need to know how the flames are computed.

    6.3 Three Tiers of Enemy AI

    • Random walk: randomly select among passable directions, forbid immediate backtracking, and use the last-heading field to avoid jitter;
    • Wall-phasing ghost: ignores walls but is constrained by map boundaries, using “turn only at intersections” to approximate a ghost-style trajectory;
    • Shortest-path chaser: uses breadth-first search, with the queue implemented as a fixed-length ring array to avoid dynamic allocation:
    1. /* Breadth-first search: return the next cell to move to, or a sentinel if none */
    2. static int BfsNextStep(World *w, int sx, int sy, int tx, int ty) {
    3. static int prev[MAX_H][MAX_W];
    4. static int queue[MAX_H * MAX_W];
    5. int head = 0, tail = 0, x, y, k;
    6. memset(prev, 0xFF, sizeof(prev));
    7. queue[tail++] = sy * MAX_W + sx;
    8. prev[sy][sx] = sy * MAX_W + sx;
    9. while (head < tail) {
    10. int cur = queue[head++];
    11. int cx = cur % MAX_W, cy = cur / MAX_W;
    12. if (cx == tx && cy == ty) {
    13. int step = cur;
    14. while (prev[step / MAX_W][step % MAX_W] != sy * MAX_W + sx)
    15. step = prev[step / MAX_W][step % MAX_W];
    16. return step; /* next cell id */
    17. }
    18. for (k = 0; k < 4; k++) {
    19. int nx = cx + DX[k], ny = cy + DY[k];
    20. if (nx < 0 || ny < 0 || nx >= MAX_W || ny >= MAX_H) continue;
    21. if (!CanWalk(w, nx, ny)) continue;
    22. if (prev[ny][nx] != -1) continue;
    23. prev[ny][nx] = cur;
    24. queue[tail++] = ny * MAX_W + nx;
    25. }
    26. }
    27. return -1;
    28. }

    Note two implementation details: first, do not recurse, to avoid stack overflow; second, size the queue to the total number of cells and perform bounds checks during the search.

    6.4 Power-Ups

    Power-ups can be made as “overlays” rather than “standalone entities”: the cell stores the power-up type number, and when the character enters that cell it reads and applies the effect (bomb cap, flame cells, movement speed), then clears the cell. This both saves entity slots and makes collision detection require only one matrix lookup.

    7. Debugging and Verification: Turning “Invisible Failures” into Observable Ones

    The place bare-metal porting most easily goes wrong is “it looks like it’s running, but the logic is already broken.” The approach here is to move errors earlier:

    1. Separate the logic layer from the platform layer: write the world model, blasts, AI, and power-ups as pure computation modules that reference no firmware interfaces; on the host, implement a minimal stub for the three interfaces “draw / input / time,” and the same logic can then be run under unit tests and record-and-replay.
    2. Deterministic replay: store a game’s input sequence as an array and replay it frame by frame to verify blast timing, enemy pathfinding, and power-up effects, avoiding dependence on subjective “feel.”
    3. Pixel-level self-check: at startup, first fill the canvas with a solid color and then draw diagonals and text to confirm the protocol is usable and the format is correct, before attaching the game logic.
    4. State machine and boundary table: make “in progress / paused / lost / won” into an explicit state machine, and list for each state the entry condition, exit condition, and acceptable inputs; having the model implement code against this table significantly reduces missed branches.
    5. Crash handling without exception protection: a UEFI application has no OS-style exception isolation, and an out-of-bounds write often manifests as screen corruption or a direct reboot. So besides the budget table, add bounds checks after every pool allocation and every grid read/write — better to return an error than to continue executing.

    8. AI Collaboration Methods: Making the Model Produce Code That “Compiles, Runs, and Is Maintainable”

    The same model, given different prompting and workflow, can produce very different results. This article summarizes five practices:

    • Interface first, then implementation: in the first round, have the model produce only an “interface list + data structures + memory budget table”; after confirming these are correct, write implementations module by module, avoiding generating thousands of lines at once that cannot be pinpointed when problems arise.
    • Write constraints as explicit rules: for example, “no dynamic memory allocation or exceptions,” “all loop variables must have explicitly declared types,” “all array accesses carry bounds checks,” “function names and file structure follow the given list” — far more effective than vaguely saying “write it in C.”
    • Layered commits: split tasks into “rendering / input / world model / AI / main loop,” have the model handle only one file at a time, and paste back compile-error logs and runtime behavior to iterate.
    • Let the model do equivalence-class derivation: for boundary-heavy logic like blasts and collision, require it first to list equivalence classes and boundary values (empty cell, destructible wall, indestructible wall, bomb, out of bounds), then write the test table.
    • Keep key decisions with humans: architecture choices, memory budget, resource format, and performance goals — these four categories of decisions must be made by a human. The model is good at writing implementations under given constraints, but not at defining the constraints for you.

    9. Evaluating Effectiveness and Controlling Cost: Working Out Whether It’s Worth It

    After the port is complete, what is truly worth comparing is not a single vendor’s one-off quote, but the “overall cost of completing comparable tasks.” It is advisable to quantify this with a self-built benchmark table:

    Evaluation dimension Quantifiable metric Notes
    Feature completeness Percentage of requirement items implemented Check off item by item; state reasons for unimplemented items
    Compilability First-compile pass rate Reflects understanding of the constraints
    Regression stability 24 hours crash-free Memory overflows often surface only after long-running operation
    Human involvement Corrected lines / total generated lines Directly reflects “how much effort was saved”
    Cost efficiency Consumption per unit of effective code Convert credit consumption to currency, then divide by effective lines
    Iteration efficiency Average time per round trip Especially critical in long-context scenarios

    Combining these dimensions yields five general cost-optimization ideas that are independent of any specific vendor:

    1. Cheap is not necessarily economical: a low-priced model that requires much rework and easily overflows context may have a higher overall cost. Evaluation should look at “effective output.”
    2. Tiered routing: assign mechanical, pattern-based tasks (such as format conversion and stub-code generation) to low-cost tiers, and assign architecture design and difficult debugging to high-capability tiers; this significantly reduces total spending.
    3. Context slimming: do not paste all historical code every round. Replace full text with “file summary + change snippets + error logs” — this saves credits and improves the model’s attention.
    4. Prompt reuse and caching: distill the constraint list, interface definitions, and code-style conventions into reusable prefixes, and use the API’s prompt-caching mechanism to reduce repeated billing.
    5. Small sample first, then scale: before formal development, run a “small-sample test” with three to five representative snippets to confirm the model is usable under your own constraints, then invest in large-scale generation.

    10. Conclusion

    Porting a graphical game to UEFI is essentially an exercise in “rebuilding the order of software engineering in an environment stripped of both resources and abstraction.” The core capability it verifies is whether the model can, under given constraints, stably refactor an object-oriented design into a data-oriented implementation and keep converging under the dual feedback of compilation and runtime.

    For developers, there are three takeaways: first, the clearer the constraints, the more reliable the AI output — writing interfaces, budgets, and style into documentation is more effective than repeated verbal emphasis; second, the core risk of a bare-metal environment is the lifecycle of memory and resources, so the budget table and bounds checks should exist before the business logic; third, don’t stop at unit-price comparison — using a self-built benchmark to quantify the four dimensions of “functionality, stability, human effort, cost” is what makes a sustainable engineering decision.

    If needed, I can continue by adding a minimal runnable skeleton, a GOP format-adaptive drawing function, or a reusable host-stub implementation and record-and-replay scheme.