AI Coding Capability in Practice: Delivering a Tower Defense Game as an Engineering Task

    This article uses a single-file tower defense game as a test case for judging AI coding capability beyond code volume or visual polish. It shows how to convert a natural-language prompt into a verifiable specification with a requirements matrix, why the minimum playable loop (tower placement through wave resolution) must be accepted first, and how to trace input, state, and rendering failures layer by layer. It also covers responsibility separation inside a single HTML file, fixed routes versus path search, consistent combat resolution across targeting and damage stages, separating animation time from game time, measurement-driven performance work such as object pooling, and layered acceptance criteria that gate delivery on a closed core gameplay loop. The conclusion is a staged workflow in which AI coding accelerates specification work, structure, implementation, and debugging while quality is still judged by observable, reproducible results.

    1. Code Length Is Not a Measure of AI Coding Capability

    Discussions of AI coding capability tend to focus on generation speed, output volume, or interface appearance. From a developer’s perspective, the more important questions are whether the generated program runs, whether the core functionality forms a closed loop, whether complex rules are executed correctly, and whether the code remains easy to modify.

    A single-file tower defense game is a representative evaluation scenario. It contains data models for the map, enemies, and towers, and it also involves mouse or touch interaction, real-time animation, combat resolution, resource management, and interface feedback. The requirement is not merely to “draw a game” but to make several subsystems work together under one set of state and timing rules.

    The key observation in the original case is that some generated results displayed a game interface yet could not complete the basic operation of placing a tower, while others reached an actually playable flow. This shows a clear gap between visual completeness and engineering usability.

    However, a single generation result only reflects the completion of that one task; it cannot be used to infer the overall quality of a class of models across all programming tasks. A more useful approach is to turn the case into a general engineering question: how should tasks be designed, implementations organized, and acceptance performed so that we can tell whether code is genuinely deliverable.

    2. Turn Natural-Language Requirements into Verifiable Specifications

    Complex prompts usually mix gameplay, numeric values, interface, performance, and additional features. Asking for all of it in one pass easily leads to omissions, misunderstandings, or conflicting rules.

    The first step of engineering this process is to build a requirements matrix.

    Category Core Content Verification
    Map and path 15×10 grid, fixed serpentine route Check start and end points, connectivity, and path cell markers
    Build interaction Three tower types, buildable only on non-path cells Check legal placement, illegal placement, and gold deduction
    Combat rules Different ranges, damage, slow, and area attacks Use controlled enemies to verify actual resolution
    Wave system 20 waves total, increasing count and strength Check the spawn plan and wave-end conditions
    Progression Three upgrade levels and sell refund Check prices, attributes, and resource accounting
    Runtime quality Animation loop, object reuse, mobile adaptation Check frame time, input mapping, and long-running stability

    Numeric rules must also be explicit. Take “each level improves attributes by 40%” as an example: there are at least two interpretations, multiplying the current attribute by 1.4 each time, or adding 40% of the base attribute per level. The two approaches produce different top-level values and cannot be left to be decided during implementation.

    A more robust specification should state which attributes participate in upgrades, whether the increase is multiplicative or additive against the base value, whether an attack-speed increase means a higher attack frequency or a shorter attack interval, and whether the slow ratio stays constant.

    Likewise, “sell refunds 60% of gold” needs a defined calculation basis. If it is based on total build and upgrade investment, total investment must be recorded; if only the initial build cost is refunded, the interface should state this clearly.

    These details may look trivial, but they determine whether the game rules are self-consistent.

    3. Build the Minimum Playable Loop First

    A complete game can include particles, sound effects, an opening animation, and a high-score record, but none of these should come before basic gameplay.

    The recommended loop to complete first is:

    Select a tower → click a legal cell → deduct gold → spawn the tower instance → start the wave → enemies move → towers attack → enemies die or reach the end → update gold and lives → determine wave end.

    If this chain does not work end to end, no amount of polish elsewhere proves the game is complete.

    The build function in particular should be among the first acceptance targets. A click with no response may not mean “building was not implemented” but rather an error in input coordinates, state management, or cell detection. Troubleshooting should follow the event propagation chain step by step:

    1. Does the page receive the input event?
    2. Is the input position correctly converted to canvas-internal coordinates?
    3. Do the coordinates map to the correct grid row and column?
    4. Is a buildable tower currently selected?
    5. Is the target cell a path cell or already occupied?
    6. Is there enough gold?
    7. Is the new tower added to the game state?
    8. Does the rendering logic read the updated state?

    This layered localization is more efficient than guessing causes after looking at the interface, and it is better suited to guiding an AI coding system in fixing problems.

    4. A Single-File Deliverable Is Not a Single Block of Code

    Putting the page, styles, and script in one HTML file makes it easy to save and run directly, but it does not mean all logic should pile up in one function.

    Even in a single-file project, responsibilities should stay separated:

    • Configuration layer: map dimensions, tower attributes, enemy attributes, and wave rules;
    • State layer: gold, lives, entity collections, the selected object, and the current phase;
    • Input layer: clicks, touches, buttons, and shortcut actions;
    • Update layer: movement, attacks, projectiles, status effects, and waves;
    • Render layer: map, entities, health bars, range, and effects;
    • Interface layer: button states, numeric text, and messages.

    The most important principle here is that the interface displays the game state, not the other way around.

    For example, gold should be stored in a single state object. Buying, upgrading, and selling all modify that value, and the status bar only displays it. If the balance is determined by reading text on the interface, it becomes vulnerable to formatting, delayed refresh, and other interactions.

    Enemy movement in tower defense games is often loosely called pathfinding, but it actually covers two different tasks.

    The first is a route that is already defined. The map presets a route from start to end, and enemies only need to pass through the path nodes in order. Here an array of waypoints is usually more direct and easier to verify.

    The second is a route that must be computed from the map. If obstacles change, players can block the way, or there are multiple candidate exits, a search algorithm is needed to obtain a feasible route.

    For a scenario that only allows building on non-path cells and has a fixed route, continuous re-searching is usually unnecessary. If the specification really requires A* or a similar algorithm, the route can be computed and validated from the passable cells during initialization, and enemies then move along the result.

    Note also that handing only the start and end points to a shortest-path algorithm does not guarantee the specified serpentine route. The passable area of the map must constrain the route, or a preset path must be used as the authoritative data.

    Movement should use continuous coordinates rather than jumping to the next cell every frame. Once an enemy approaches a target waypoint, it switches to the following node. To support target priority, you can also record the path distance an enemy has traveled instead of comparing only the straight-line distance to the end.

    6. Rule Consistency Is the Core of the Combat System

    Three tower types combined with three enemy types form a resolution ruleset more complex than the interface.

    For example, a rapid-fire tower handles sustained close-range output, an area-attack tower must handle blast radius and damage reduction for special enemies, and an electromagnetic tower involves both damage and a timed slow. Whether flying enemies can be attacked must become a unified target-filtering rule.

    It is advisable to split an attack into four stages:

    Filter targets, select a target, spawn the projectile, resolve the hit.

    The filtering stage checks whether an enemy is alive, within range, and of an attackable type; the selection stage sorts by a strategy such as nearest or lowest health; the projectile stage handles flight; the hit stage uniformly computes damage, reduction, and status effects.

    This avoids inconsistencies such as “the restriction is correct at lock-on, but the explosion wrongly damages targets that must not be attacked.”

    For area damage, it should also be specified whether resolution uses the position at projectile launch or the landing position. For homing projectiles, the behavior after the target dies early must be defined, for example continuing to the last position or being recycled immediately.

    The slow effect is best recorded with an expiration time. An enemy’s actual speed should be derived from base speed and currently effective states rather than modifying base speed and later trying to restore it. Rules for repeated hits should be decided in advance, for example refreshing the duration without stacking the slow ratio.

    7. Separate Animation Time from Game Time

    A real-time game cannot assume every frame update has the same interval. Device performance, page load, and background tab switches all affect the time between frames.

    The animation loop can use requestAnimationFrame, but this does not automatically deliver a stable 60 frames. Movement, cooldowns, wave intervals, and status durations should all advance based on elapsed time.

    For a game supporting 1×, 2×, and 3× speed, time can be split into two kinds:

    • Real time for measuring frame rate, responding to input, and handling some interface animation;
    • Game time for advancing enemy movement, attack cooldowns, projectiles, and slow effects.

    Otherwise, after a speed change enemies may move faster while tower attacks do not, causing unintended shifts in game balance.

    A more robust implementation can use a fixed-timestep update, splitting accumulated time into multiple logical steps while capping the maximum catch-up steps per frame. When the page returns from the background, an abnormally large time interval also needs to be clamped so enemies do not suddenly cross the whole route.

    8. Performance Optimization Must Be Driven by Measurement

    Object pools suit large numbers of short-lived projectiles and particles. The idea is to reuse existing objects and reduce the memory churn caused by frequent creation and collection.

    Whether an object pool is effective depends on implementation quality. A reused object must have its position, velocity, target, damage, lifetime, and active state reset; otherwise stale data can pollute the new entity. The pool also needs a capacity limit so it does not grow without bound under heavy load.

    Beyond object pools, these optimizations are also possible:

    • Pre-render the static map to reduce repeated work;
    • Use squared distance for range checks and avoid unnecessary square roots;
    • Limit particle counts, glow layers, and alpha overdraw;
    • Refresh interface numbers on demand instead of every frame;
    • Separate logical coordinates from display size and handle scaling in one place;
    • Consider spatial partitioning structures only after entity counts grow.

    Performance acceptance cannot rely on a frame-rate counter alone. Entity counts in later waves, frame-time variation, memory trends, and input responsiveness should all be recorded. Running stably for a short period is a different level of requirement from staying smooth after playing through all 20 waves.

    9. Replace One-Off Subjective Scoring with Layered Acceptance

    The scoring dimensions of the original task can be kept, but explicit check steps and baseline gates should be added.

    Start with startup acceptance: does the file open, are there script errors, does it depend on external network resources.

    Then interaction acceptance: can you select, build, upgrade, and sell towers and start a wave; do illegal operations give reasonable feedback.

    Then rule acceptance: can different towers only attack allowed enemies, does damage reduction take effect, does the slow end on time, does the boss appear as planned.

    Only then come performance, visual, and additional-feature acceptance, including smoothness under heavy load, sound triggers, local records, the end screen, and touch adaptation.

    A gate such as “if the core gameplay loop is not closed, the result is not judged deliverable” prevents a polished interface from offsetting serious functional defects. The specific weights should still be adjusted to the task goal: a prototype for demonstration and a project meant for ongoing maintenance should not use exactly the same evaluation emphasis.

    For reproducibility, use a fixed wave configuration or a repeatable random sequence, and record the browser environment, window size, run steps, and error messages. A screenshot proves the appearance at one moment; it cannot replace interaction testing and rule verification.

    10. Bring AI Coding into a Controlled Development Workflow

    Rather than asking for all the code in one shot, a more reliable process delivers in stages:

    Stage one organizes the specification and settles numeric interpretations and rule conflicts; stage two implements the minimum playable loop; stage three completes enemies, upgrades, and the wave system; stage four adds projectile trajectories, status effects, and particles; stage five completes sound, records, and mobile interaction; finally, regression testing and performance checks are performed.

    Every fix should preserve the tests that already pass. For example, after correcting touch coordinates, desktop clicks must be re-verified; after changing the time system, attack intervals, slow durations, and wave spawning must be re-verified.

    The practical value of AI coding is not to let developers skip the engineering process but to help them complete specification work, structure setup, implementation, and problem localization faster. The final quality judgment still rests on observable, reproducible results.

    For a comprehensive task like a tower defense game, the real highlight is not how many lines of code were produced but whether interaction, rules, time, performance, and maintainability are organized into a reliable system. Only by moving from “generated output” to “verified delivery” can AI coding capability turn into stable development efficiency.