Claude Code in Action: Building an Embedded Tetris Game with AI in 3 Hours

Using Claude Code to build an embedded Tetris game from scratch in under 3 hours.
This hands-on case study shows how the author used Claude Code with the LVGL graphics library to build a Tetris game that runs on a real embedded development board in under 3 hours—covering requirements clarification, Workflow rule design, automatic compilation loops, and the full PC-to-hardware migration process.
Starting from Scratch: Building a Real, Runnable Game with AI
In this advanced Claude Code hands-on tutorial, the author presents a compelling case study: in under three hours, they built a Tetris game from scratch with AI's help—one that actually runs on an embedded development board. This isn't a browser-based demo, but a complete project built on LVGL (a lightweight graphics library), which was ultimately compiled and deployed to a real hardware board.
About LVGL: LVGL (Light and Versatile Graphics Library) is an open-source graphics library designed specifically for microcontrollers and embedded systems. It can run with as little as 64KB of Flash and 16KB of RAM, and supports a wide range of display devices—from simple monochrome OLEDs to high-resolution RGB screens. It offers a rich set of built-in widgets (buttons, lists, charts, animations, etc.), is implemented in pure C, and has cross-platform portability. LVGL was born in 2016, originally named LittlevGL, and was developed by Hungarian engineer Gábor Kiss-Vámosi. Today it has become one of the most widely used open-source frameworks in the embedded GUI space, officially integrated into the development ecosystems of chip vendors like STMicroelectronics and NXP.
LVGL's architecture borrows the concepts of Object Tree and Style System from web frontend development—each UI element is abstracted as an lv_obj object, and style properties (color, margin, font) are applied through a CSS-like cascading mechanism. This allows developers to describe interface requirements in near-declarative UI semantics. The hierarchical relationships of the object tree determine rendering order and event bubbling paths, while the cascading mechanism of the style system makes unified theme changes possible—modifying a parent object's style automatically propagates to all child objects, with no need for adjusting each one individually. This design philosophy shares a common lineage with React's component tree and Flutter's widget tree, but is deeply trimmed down for extremely resource-constrained embedded environments: LVGL removes the virtual DOM diffing algorithm and instead adopts a "Dirty Rectangle" mechanism that redraws only the regions of the screen that have changed—preserving the semantic development experience while pushing rendering overhead to the limit. The essence of the dirty rectangle mechanism is a form of spatial locality optimization—each frame only triggers a redraw for the rectangular areas where pixels have actually changed, while the rest retains the previous frame's framebuffer content. This is especially critical on microcontrollers with CPU clock speeds of only a few hundred MHz and no GPU acceleration, reducing actual draw calls to just 5%–20% of a full-screen refresh.
This abstraction layer is crucial for AI involvement: AI can directly process semantic descriptions like "create a score panel with rounded borders" and map them to specific LVGL API calls, without needing to understand low-level framebuffer operations or DMA transfer details—this is precisely the technical prerequisite that enabled AI to intervene efficiently in this case.
The entire project's initial environment was created via a UI Builder-generated LVGL project. Once the scaffolding was set up, the author handed off nearly all of the subsequent coding work to the AI. This "human builds the framework, AI fills in the flesh" division of labor is precisely the typical workflow for AI-assisted development today.

The Critical First Step: Requirements Clarification Matters More Than Writing Code
Throughout the process, the author repeatedly emphasizes one core point—most of the time was spent communicating with the AI, while the actual coding time was quite short. This is extremely valuable guidance for developers new to AI programming.
This observation has deep roots in software engineering theory. Barry Boehm's research shows that if an error introduced during the requirements phase is only discovered after coding, the cost of fixing it will multiply 10 to 100 times. This principle is known as the "exponential growth law of defect repair cost," a distillation of decades of industrial practice data, later repeatedly confirmed by research from institutions such as NIST. The essence of requirements clarification is transforming high-entropy (vague, ambiguous) natural language descriptions into low-entropy (structured, verifiable) specification documents—a process that is itself the highest information-density phase of the entire project. From an information-theory perspective, a precise requirements spec is equivalent to greatly compressing the "constraint set" of the subsequent implementation space—the more precise the requirements, the smaller the state space the AI can explore during generation, and the smaller the semantic distance between the output and expectations. In the language of Shannon information theory: vague requirements have high uncertainty entropy, equivalent to allowing the AI to wander freely through a broad solution space; precise requirements, on the other hand, dramatically reduce this entropy, constraining the AI's generation path to a small neighborhood near the expected solution.
In the context of AI programming, this principle is further amplified: AI's generative capability is extremely strong, but its direction is entirely determined by the initial spec. Vague input causes the AI to fill in numerous "reasonable but unexpected" assumptions, and every erroneous assumption the AI accepts gets amplified along the code generation path. Notably, large language models tend to choose the "default option" that appears most frequently in their training data when facing ambiguity—for a classic game like Tetris, the AI is highly likely to default to reproducing the standard Nintendo rules (including the Super Rotation System and the classic NES line-clear scoring algorithm). The Super Rotation System (SRS) is the modern rotation rule standardized by The Tetris Company in 2001, defining the "Wall Kick" offset sequences for each piece when its rotation is blocked by walls or other pieces. The NES scoring system calculates scores based on the number of lines cleared at once (1–4 lines) and the current level, with specific formulas: single clear 40×(level+1) points, double clear 100×(level+1) points, triple clear 300×(level+1) points, and quadruple clear (Tetris) 1200×(level+1) points. These are all implicit conventions the AI will automatically reproduce in the absence of explicit instructions. If a developer has any customization requirements—such as different wall-kick logic, custom piece shapes, or non-standard scoring rules—these must be explicitly stated during the requirements phase; otherwise these implicit assumptions will be deeply encoded into the implementation details, and the cost of changing them afterward far exceeds expectations.
When the project began, the requirements description was quite concise: "I need to write a Tetris game. Help me design the basic interface and easy-to-operate buttons." But Claude Code didn't immediately start writing code—instead, it first threw out a series of questions for the author to answer one by one. The author specifically points out that the final implementation was "strongly correlated" with these questions the AI raised—the clearer the answers during the requirements clarification phase, the closer the output would be to expectations. Therefore, having the AI proactively ask questions and output a structured plan before coding is essentially performing "requirements quality assurance"—the highest-leverage step in an AI-native development workflow.
After the Q&A concluded, the AI output a complete plan covering the overall architecture, visual design, and game layout. The value of this step lies in transforming vague ideas into a structured, reviewable specification document.

Workflow Rules: The Key to Making AI Self-Constrain
A highlight of this case study is the author's introduction of custom Workflow rules. After adding the workflow rules, the AI proactively evaluates whether the previously formulated plan has any questions, further investigates the existing code, and ultimately produces a more detailed and specific implementation plan.
Workflow rules are essentially "system-level constraints" on AI behavior—an advanced form of Prompt Engineering in engineering practice. Ordinary prompts describe "what to do," while Workflow rules define "how to do it" and "what to check after doing it." From a prompt engineering perspective, Workflow rules are a form of "Meta-Prompt"—they don't directly guide task execution, but rather define the behavioral protocol the AI must follow when executing any task. The concept of the meta-prompt was first systematized around 2022 with the widespread adoption of GPT-3. Its core insight is: rather than repeatedly stating behavioral expectations in each conversation, it's better to encode these expectations as persistent higher-level constraints, so the model maintains consistent behavior patterns across the entire session and even across sessions. In practice, meta-prompts are typically injected as System Prompts, with priority higher than the user's individual instructions—equivalent to setting up non-overridable "constitutional-level constraints" in the model's decision-making process.
This is highly analogous to the concept of "Coding Standards" in software engineering: the standards themselves don't produce functional code, but they constrain how all functional code is produced, thereby ensuring overall consistency and maintainability. A deeper analogy is the operating system's "system call convention"—applications need not understand kernel implementation details; they only need to follow the prescribed calling interface. Similarly, developers don't need to explain the workflow to the AI each time; they define it once in the Workflow rules, and the AI automatically follows it in all subsequent tasks.
From a broader perspective, Workflow rules are a core component of the "AI-Native development workflow." They enable different developers and different projects to share the same set of AI collaboration standards, rather than relying each time on verbal agreements or ad-hoc prompts. Teams can bring validated Workflow rule files under version control, iterating and optimizing the AI's behavioral norms just like managing code—recording change history, conducting code reviews, and rolling back ineffective rules. This is the critical path for turning individual best practices into organizational-level assets. Versioned management of rule files also brings another benefit: when the AI model is upgraded or switched, A/B testing can be used to compare the performance of old and new rules across different model versions, systematically finding the optimal rule set rather than starting from scratch each time.
The author particularly emphasizes: once the plan is confirmed, be sure to save it as a file. Grounding the plan into a document not only serves as a reference baseline for subsequent development, but also provides a stable point of reference when the AI's context is lost or multiple iterations are needed. Although the context windows of today's mainstream large language models have expanded to hundreds of thousands or even millions of tokens, the model's attention weight for early information decays significantly under extremely long contexts (the so-called "lost in the middle" problem, systematically quantified by Nelson Liu et al. of Stanford in a 2023 study: the model's recall rate for information located in the middle of the context can drop by 30%–50% compared to information at the beginning and end). External document anchors effectively compensate for this deficiency.
The AI then began breaking down the task, creating a series of subtasks and implementing them one by one in code.

Automatic Compilation Verification: The Power of the Closed Loop
Because the Workflow explicitly wrote in the rule "after modifying code, verify by compiling," the AI automatically enters the compilation verification phase after completing the coding. When it encounters errors, the AI automatically locates and fixes them, all without human intervention.
Writing "after modifying code, verify by compiling" into the rules is equivalent to instilling in the AI the Continuous Integration (CI) philosophy from software engineering—every change must pass build verification to be considered complete. Continuous Integration was first proposed by the Extreme Programming (XP) community in the late 1990s. Martin Fowler and Kent Beck systematized it into a set of engineering practices: every developer integrates code into the main branch at least once a day, and each integration passes automated build and test verification. The core idea is to use high-frequency, small-batch integration verification to spread integration risk across the entire development process rather than concentrating it at the project's end, thereby avoiding "Integration Hell"—discovering large numbers of incompatibilities between modules only at the project's end. CI's value is further amplified in the context of AI programming: AI can generate hundreds of lines of code at once, and without an instant verification mechanism, errors will pile up layer by layer across multiple rounds of generation, ultimately forming untraceable "error debt." Researchers call this phenomenon "Hallucination Propagation"—an erroneous assumption introduced by the AI in the first round of generation becomes context input for the second round, then gets further "rationalized" and amplified, forming a self-reinforcing chain of errors.
In traditional CI workflows, this relies on independent toolchains like Jenkins and GitHub Actions to execute. In the context of AI programming, Workflow rules internalize the CI logic into the AI's behavioral constraints, achieving an atomic closed loop where "every code generation comes with its own verification." This automatic "code–compile–fix" closed loop is the watershed moment where AI programming moves from "generating code snippets" to "delivering runnable results." The AI is no longer just a code completion tool, but is capable of taking responsibility for its own output, continuously iterating until it passes verification. The value of this constraint lies in externalizing the best practices of human engineers into reusable, transferable rule files.
The Separation Strategy Between PC Development and Embedded Deployment
The author adopted a pragmatic development strategy: first develop and debug on a PC, detached from the embedded environment; then, once the game logic and interface were basically stable, compile it to run on the development board.
"Verify on PC first, deploy to hardware later" is an effective layered testing strategy in the field of embedded software development, commonly known in industry as "Host-Target separated development." The debugging cost of embedded hardware is far higher than that of a PC environment: flashing firmware, connecting a debugger, viewing serial logs—each step introduces additional time overhead. Meanwhile, using a simulator on a PC (such as the SDL simulator officially provided by LVGL) allows verification of UI rendering and interaction logic at the millisecond level. In safety-critical fields such as aviation and automotive, the Host-Target separation strategy is even explicitly required by certification standards like DO-178C and ISO 26262—its importance has been thoroughly validated in embedded engineering practice. These standards require that before software runs on the target hardware, it must complete unit testing and integration testing in the Host environment, ensuring that hardware-related defects do not contaminate verification conclusions at the software logic level—in other words, it's an institutionalized embodiment of the "separation of concerns" principle in the safety engineering field.
SDL (Simple DirectMedia Layer) is a cross-platform multimedia abstraction library, originally developed by Sam Lantinga in 1998, widely used for cross-platform porting of games and multimedia applications. LVGL redirects graphics rendering to a PC window through the SDL backend—low-level drawing calls like lv_draw_sw_blend are redirected to SDL Surface operations, and touch input is simulated through SDL's mouse events—allowing the same business code to switch between PC and embedded targets without modification. SDL itself adopts a HAL design philosophy similar to LVGL's, using a unified API to mask the differences in graphics systems across platforms like Windows GDI, Linux X11/Wayland, and macOS Cocoa—which is the fundamental reason it can serve as LVGL's PC simulation backend. SDL's cross-platform capability stems from its Driver Abstraction Layer design: each platform's concrete implementation is encapsulated as an independent "backend driver," dynamically bound at runtime through function pointer tables, completely decoupling upper-layer API calls from lower-layer implementations. This design pattern is architecturally identical to LVGL's Display Driver Interface (lv_disp_drv_t). This "Hardware Abstraction Layer" (HAL) design isolates platform-specific code, keeping the business logic layer unaware of the underlying hardware—precisely the technical foundation that enables the Host-Target strategy.
The value of this strategy multiplies when AI programming is introduced: the AI generates code at an extremely high frequency, and if each iteration required flashing to verify, iteration efficiency would be greatly diminished. By incorporating PC-side verification into the AI's automatic closed loop, over 90% of errors can be eliminated before reaching real hardware, so the embedded deployment phase only needs to handle platform-specific issues—dramatically reducing debugging complexity.
The first generated interface "didn't feel attractive enough," so the author had the AI continue optimizing. After several rounds of iteration, the pieces no longer overlapped, and the interface gradually became cleaner.

Real Pitfalls in the Embedded Environment
The process of migrating from PC to development board was not entirely smooth, and the problems exposed are precisely the most valuable part of AI programming in real-world engineering:
-
Font path problem: After deploying to the board, text didn't display. The author told the AI "text doesn't display" and pointed out the code location. Upon inspection, the AI found that the font path had been written as a relative path—the UI Builder path did not match the actual Lubanite path, causing resource loading to fail. After correction, the text was restored. The root cause of this type of problem is that embedded systems usually lack a mature filesystem abstraction layer: relative paths on the PC side depend on the operating system's current working directory (CWD) mechanism, whereas the filesystem mount points in embedded Linux or bare-metal environments are often fixed (such as
/mnt/or/data/), requiring absolute paths or resource base addresses injected via compile-time macro definitions. A more thorough solution is to convert font resources into C arrays using tools likexxdorbin2cand compile them directly into the firmware, fundamentally eliminating the filesystem dependency—LVGL officially calls this inline resource a "Built-in Font." Its essence is storing the glyph bitmap data as aconstarray in the Flash read-only segment, both avoiding filesystem dependency and enabling the compiler to optimize it into efficient read-only access. The working principle ofbin2c-type tools is to read the binary file byte by byte, write it into a C array in the hexadecimal literal0xXXformat, and use compiler directives like__attribute__((section(".rodata")))to position the array in Flash's read-only data segment, with address mapping completed by the linker script at program startup. This is one of the most typical "environment difference pitfalls" in embedded porting. -
Steps requiring manual intervention: The author chose to manually perform the step of copying the UI Builder directory under Lubanite before compiling. This reminds us that AI-assisted development does not equal full automation—when it comes to critical operations such as environment configuration and directory migration, human control remains necessary.
It's worth noting that Claude Code differs fundamentally from traditional code completion tools (such as GitHub Copilot) in handling such problems. Traditional completion tools make local predictions based on "cursor context," essentially performing greedy sampling in the conditional probability space of a statistical language model—they're helpless in the face of cross-file, cross-toolchain path errors. Claude Code in Agent mode, however, has the ability to retrieve code, analyze error logs, locate root causes, and fix them automatically—capable of handling the complexity of real-world engineering.
From an architectural perspective, the core of Agent mode is the "Tool Use Loop": the model not only outputs text but can also call predefined tools (file read/write, shell execution, code search, network requests, etc.) and dynamically adjust its next action based on the tool's returned results—a closed-loop architecture of "Perceive-Reason-Act," conceptually akin to control loops in robotics. This architecture was first systematically described in the 2023 ReAct (Reasoning + Acting) paper, and subsequently widely adopted in API designs such as OpenAI's Function Calling and Anthropic's Tool Use. ReAct's core innovation lies in interweaving "Chain of Thought" reasoning with external tool calls in the same generation stream—the model first reasons in natural language about what to do next (Reason), then actually executes it through structured tool calls (Act), and the real results returned by the tools become input for the next round of reasoning, forming a three-part loop of "thought–action–observation." The result of each tool call is appended to the context, becoming input for the model's next reasoning step, thereby achieving layered decomposition and solution of multi-step problems. The key breakthrough of this mechanism is that the model's reasoning process is no longer confined to static knowledge in the training data, but can obtain runtime dynamic information (such as actual compilation error output) through tool calls, elevating debugging ability from "pattern matching" to "evidence-based reasoning." This mechanism enables the AI to independently handle multi-step problems like a junior engineer, rather than remaining at the level of "offering suggestions." Cross-platform path differences and resource loading issues like these are often the most easily-stepped-in pitfalls in embedded development, and given clear error feedback and code localization, the AI demonstrated decent debugging capability.
Practical Takeaways: The Right Way to Approach AI Programming
Synthesizing the entire project, we can distill several experiences of great reference value for developers:
- Communication quality determines output quality. Spending time on thorough requirements clarification is more important than rushing to have the AI write code. Investment in the requirements phase yields the highest return of the entire project—Boehm's law tells us that eliminating one requirements defect at this stage is equivalent to eliminating dozens of code defects at the testing stage.
- Ground the plan into a file. A structured plan document is a stable anchor for multiple iterations, and the recovery foundation when the AI's context window is saturated or the session is interrupted. Documents are specs, specs are constraints, and constraints are quality assurance.
- Constrain AI behavior with Workflow rules. Clearly define rules like "must compile and verify after changes," externalizing software engineering best practices into reusable constraint files, letting the AI form an automatic closed loop that greatly reduces human intervention. Workflow rule files should be brought under version control, reviewed and iterated just like code.
- Layered development reduces complexity. Verify logic in the PC environment first, then migrate to target hardware—this effectively isolates problems and fully leverages the AI's high-frequency iteration advantage. HAL design and the Host-Target separation strategy are the technical guarantees of this workflow.
- Preserve the boundaries of human judgment. Critical junctures like directory migration and environment compilation still require human control—AI-assisted development does not equal full automation. The core value of human engineers lies in judgments about system boundaries, environment dependencies, and business constraints. This tacit knowledge is still difficult to fully encode into the AI's behavioral rules for now.
This Tetris project, completed in under three hours, is small in scale but fully demonstrates the AI's involvement across the entire process—from requirements, design, and coding to compilation and cross-platform deployment debugging. It proves that as long as the workflow is well designed, AI is already capable of taking on real, hardware-facing embedded development tasks. For embedded developers, perhaps the most important takeaway from this case is: AI is not just a tool for writing business logic. Combined with appropriate abstraction layers (such as LVGL's HAL design) and engineering constraints (Workflow rules), it can already participate in complete engineering projects with hardware deliverables.
Key Takeaways
Key Takeaways
Related articles

The Truth Behind Codex 'Build a Website in 5 Minutes': AI Isn't Creating Sites—It's Helping You Copy Them
Exposing the truth behind viral Codex 5-minute website videos: creators aren't building original sites with AI—they're copying shared prompts or scraping others' work. Learn AI coding tools' real limits.

Getting Started with AI Agent Development: A Complete Guide from Concept to Practice
A comprehensive guide to AI Agent architecture and development, covering automated marketing, intelligent customer service, and investment analysis scenarios with single and multi-agent collaboration.

The Truth Behind Codex 'Build a Website in 5 Minutes': AI Isn't Creating Sites — It's Helping You Copy Them
Exposing the truth behind viral Codex 5-minute website videos: creators aren't building original sites with AI — they're copying shared prompts or scraping others' work.