Building a UEFI Graphics Application: A Snake Game Walkthrough

    UEFI applications run before any operating system loads, giving developers direct access to graphics output and keyboard input. This article walks through building a Snake game as a practical introduction to UEFI graphics development, covering the Graphics Output Protocol (GOP) and Simple Text Input Protocol, double-buffered rendering, a finite state machine for game logic, config-driven level design, particle effects with a fixed memory pool, and CJK font rendering with UEFI's CHAR16 strings. It also explains how to build, deploy, and verify the EFI image in the UEFI Shell, and shares lessons learned from iterating on the project with AI-assisted coding tools. By the end, you will understand the core patterns needed to develop graphical pre-boot applications on UEFI firmware.

    Why Write Graphics Applications at the Firmware Layer

    UEFI (Unified Extensible Firmware Interface) is the standard specification for the boot phase of modern computers. Once the firmware finishes hardware initialization, it loads and executes conformant EFI applications—before any operating system starts. Developing programs at this stage offers three immediate benefits:

    • No OS dependency: your program can access graphics output and keyboard input directly;
    • It suits hardware diagnostics, boot configuration screens, pre-boot test utilities, and similar scenarios;
    • It helps developers understand the boot process, the Protocol mechanism, and how memory allocation works.

    Snake is a well-structured beginner project. It involves four fundamental components—input handling, state updates, screen drawing, and timing control—which together cover the core problems of UEFI graphics development.

    Runtime Environment and Key Protocols

    A UEFI application accesses firmware services through the System Table, where gBS points to the Boot Services table and gST points to the System Table itself. Three pieces of this infrastructure matter for this project:

    1. Graphics Output Protocol (GOP): provides display mode queries, pixel fill operations, and block transfers (Blt).
    2. Simple Text Input Protocol: reads key presses via ReadKeyStroke. Arrow keys are reported as scan codes (ScanCode), while regular characters come through as Unicode characters (UnicodeChar).
    3. The Stall function in Boot Services: blocks execution for a given number of microseconds, useful for controlling frame intervals.

    Here is the typical way to locate GOP:

    1. EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop = NULL;
    2. Status = gBS->LocateProtocol (
    3. &gEfiGraphicsOutputProtocolGuid,
    4. NULL,
    5. (VOID **)&Gop
    6. );
    7. if (EFI_ERROR (Status)) {
    8. return Status;
    9. }

    Reading key input requires handling two kinds of input. Arrow keys are identified by ScanCode, while WASD and the pause key P are identified by UnicodeChar. Both can be handled in a single function:

    1. EFI_INPUT_KEY Key;
    2. Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
    3. if (Status == EFI_NOT_READY) {
    4. return; // No key input this frame
    5. }
    6. switch (Key.ScanCode) {
    7. case SCAN_UP: Dir = DIR_UP; break;
    8. case SCAN_DOWN: Dir = DIR_DOWN; break;
    9. case SCAN_LEFT: Dir = DIR_LEFT; break;
    10. case SCAN_RIGHT: Dir = DIR_RIGHT; break;
    11. default:
    12. break;
    13. }
    14. switch (Key.UnicodeChar) {
    15. case L'w': case L'W': Dir = DIR_UP; break;
    16. case L's': case L'S': Dir = DIR_DOWN; break;
    17. case L'a': case L'A': Dir = DIR_LEFT; break;
    18. case L'd': case L'D': Dir = DIR_RIGHT; break;
    19. case L'p': case L'P': TogglePause (); break;
    20. default:
    21. break;
    22. }

    Double-Buffered Rendering

    If you write each element directly to video memory, the screen may show intermediate states mid-draw, manifesting as tearing or flicker. The standard fix is double buffering: allocate an off-screen buffer in system memory with the same dimensions as the display, complete all drawing for a frame inside that buffer, then push it to the frame buffer with a single Blt operation.

    Note that UEFI provides no interface for synchronizing with the display refresh, so double buffering only reduces the exposure of intermediate states—it cannot completely eliminate tearing. The actual result also depends on the machine’s display hardware and firmware implementation.

    Here is how to allocate and submit the buffer:

    1. EFI_GRAPHICS_OUTPUT_BLT_PIXEL *FrameBuffer;
    2. UINTN BufferSize = Width * Height * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL);
    3. Status = gBS->AllocatePool (EfiLoaderData, BufferSize, (VOID **)&FrameBuffer);
    4. if (EFI_ERROR (Status)) {
    5. return Status;
    6. }
    7. // After drawing each frame, submit it to the display device in one operation
    8. Gop->Blt (
    9. Gop,
    10. FrameBuffer,
    11. EfiBltBufferToVideo,
    12. 0, 0, // Source origin
    13. 0, 0, // Destination origin
    14. Width, Height,
    15. 0 // Delta of 0 means the buffer is tightly packed
    16. );

    Submitting the full screen every frame is expensive. One improvement is to record only the rectangular regions that changed this frame and call Blt for those regions only. When the snake moves, the changed area is typically limited to the head, the tail, and the food’s vicinity—a technique that significantly reduces per-frame data volume.

    The Game State Machine

    Snake’s logic maps naturally onto a finite state machine. This project uses three states: running, paused, and game over.

    1. typedef enum {
    2. GAME_RUNNING,
    3. GAME_PAUSED,
    4. GAME_OVER
    5. } GAME_STATE;

    The transition rules are:

    • Pressing P while running enters the paused state; pressing P again while paused resumes;
    • The game enters the over state when the snake head hits a wall or the snake’s own body;
    • Input is processed on every loop iteration, but only the running state advances the snake’s position.

    Separating input handling from logic updates makes the pause feature trivial. While paused, the game still responds to key presses—it simply stops accumulating time steps, and the screen resumes immediately upon unpausing.

    Levels and Obstacles

    The key to level design is centralizing difficulty parameters in a configuration table. Once the score reaches a threshold, the program reads the parameters for the corresponding level—no changes to the logic code required.

    1. typedef struct {
    2. UINT32 ScoreThreshold; // Score required to enter this level
    3. UINT32 TickMs; // Interval per logic step (milliseconds)
    4. BOOLEAN HasObstacles; // Whether to spawn obstacles
    5. } LEVEL_CONFIG;
    6. STATIC CONST LEVEL_CONFIG mLevels[] = {
    7. { 0, 150, FALSE },
    8. { 50, 120, FALSE },
    9. { 120, 90, TRUE },
    10. { 250, 60, TRUE },
    11. };

    To adjust difficulty, you only need to change the values in the table. When converting TickMs to a Stall parameter, multiply by 1000, since Stall works in microseconds.

    Obstacle generation requires care: a random position may land on the snake’s body or the food, or even completely block viable paths. The safe approach is to check candidate cells before spawning and verify that a viable path still exists from the snake head to the food. If path checking is too expensive, you can alternatively use pre-designed map templates and randomly select one of them.

    Resource-Constrained Particle Effects

    The particle effect triggered by eating food looks simple, but dynamic memory allocation is costly in a firmware environment, and memory resources are limited. The recommended approach is a fixed-size particle pool—for example, pre-allocate 16 particles, each storing only position, remaining lifetime, and color. Each frame decrements the lifetime by one, and particles whose lifetime reaches zero are recycled back into the pool. No memory allocation happens inside the loop, which keeps the system stable and predictable.

    Implementing a CJK Interface

    UEFI text output is Unicode-based, but whether Chinese characters render correctly depends on the fonts built into the firmware, and most environments provide no guarantee. To achieve a full Chinese interface, common practices include:

    1. Compile the dot-matrix data for the required Chinese characters into the program, such as 16×16 or 24×24 bitmaps. The font file only needs to contain the characters used in the interface, keeping its size small.
    2. Render glyphs pixel by pixel through GOP, and implement your own line wrapping, alignment, and width calculation for strings.
    3. Use UTF-8 encoding consistently in source files. At runtime, remember that UEFI uses the CHAR16 type—essentially a 16-bit character—which cannot directly represent some characters from supplementary planes. String lengths should be counted in characters, not bytes.

    Building and Verifying the Application

    The build output is an EFI image in PE/COFF format. To run it on firmware, you have two options:

    1. Place it in the default path on the EFI System Partition (ESP), such as EFI/BOOT/BOOTX64.EFI, so the boot manager invokes it directly;
    2. Place it anywhere and execute it manually from the UEFI Shell.

    To verify the file is in place in the UEFI Shell, follow steps like these:

    1. Shell> map -r
    2. Shell> fs0:
    3. FS0:\> ls
    4. FS0:\> SnakeApp.efi

    Here, map -r lists all storage mappings, fs0: switches to the corresponding file system, and ls confirms the file exists.

    When verifying, check the following items one by one:

    • Whether the target firmware provides a UEFI Shell, or whether the application entry can be selected from the boot manager;
    • Whether the EFI image resides in a recognizable partition and path;
    • Whether the file system mapping is correct and the file name matches the execution command;
    • Whether ReadKeyStroke and GOP work on the target firmware;
    • Even after the emulated environment passes, you still need to verify on real hardware, since firmware implementations may differ.

    Engineering Lessons from the Development Process

    This project was completed in three rounds: the first implemented the basic functionality, the second added levels, obstacles, and effects, and the third handled the Chinese localization. The whole process took roughly 27 prompts and about 3 hours. The AI coding assistant deviated most often in three areas—directory management, dependency acquisition, and environment setup—which yielded the following lessons:

    1. Define write boundaries explicitly. AI coding tools may create dependencies or build artifacts in a parent directory above the working directory. State the allowed write paths in the project description, and check the directory structure and change scope after each round.
    2. Avoid flags that skip permission confirmations. Such flags amplify the impact of mistakes. Automated development should also follow the principle of least privilege, granting only the permissions needed for the task.
    3. Control dependency sources. When downloading prebuilt firmware images or toolchains, verify the source, version, and hash values, and record them for reproducibility.
    4. Validate environment assumptions. Code that compiles does not guarantee the program will boot on the target firmware. When setting up the environment, confirm boot entries and file locations first, then run functional tests.
    5. Iterate in rounds, keeping a runnable version each round. Dividing changes by round makes it easier to locate regressions and to roll back to the last working state when deviations occur.

    Conclusion

    The core of UEFI graphics programming comes down to three things: correctly invoking protocols to obtain graphics and input capabilities, using double buffering and a state machine to organize rendering and logic, and managing level parameters with configuration tables. On the engineering side, establish directory boundaries, permission scope, dependency sources, and environment verification early in development to avoid costly troubleshooting later.