From Wish to Playable Racing Game: Engineering Practices for Long-Horizon Agent Tasks

    This article explores how to transform natural language prompts into executable specifications for long-horizon AI agent tasks. Using a browser-based racing game as a case study, it covers task-level evaluation metrics, modular architecture design, the agent execution loop, and strategies for optimizing the performance-cost tradeoff.

    Using “natural language to application” as an entry point for development is undeniably attractive: users simply describe the goal, and the agent handles requirement understanding, code generation, execution, debugging, and local fixes. While this approach can quickly validate ideas during the demo phase, real-world projects quickly shift the focus from “can it generate code” to “can it deliver stably.” This article uses a playable mini racing game as an experimental subject to discuss how to transform a single wish into executable specifications, how to use agents for multi-round iterations, and how to evaluate long-horizon tasks from the perspective of unit cost per successful task.

    I. The Value and Boundaries of Wishful Programming

    The core value of “wishful programming” lies in lowering the barrier to entry. Faced with a new idea, developers do not need to write complete requirement documents or define all technical details upfront. Instead, they describe the goal in natural language and let the agent provide the first runnable skeleton. This approach is ideal for exploratory tasks, such as building a racing prototype: with a track, drivable mechanics, a timer, and support for both driver and rear camera views.

    However, a “single wish” is inherently ambiguous. Taking the racing game as an example, it seemingly only involves driving, a track, and timing, but actually implies a large number of specifications:

    • How the vehicle accelerates, steers, and brakes, and whether reversing is allowed;
    • Whether track boundary collisions result in deceleration, bouncing, or a reset;
    • When timing starts and whether best lap times are recorded;
    • How the two camera views switch and whether the camera follows smoothly;
    • Whether pause, restart, and mobile input are supported;
    • Whether graphical assets can use external dependencies or must run offline;
    • Whether physics updates remain deterministic when the frame rate is unstable.

    If these constraints are not clearly defined, the agent will typically choose the implementation path with the lowest cost. The result is often “all features are present, but the experience is mediocre”: crude graphics, insufficient feedback, and missing edge cases. The problem is not that the model cannot write code, but that the input is merely a wish rather than an acceptable engineering contract.

    Therefore, a more reasonable positioning is: wishful programming is responsible for rapid exploration, while specification and verification are responsible for engineering convergence. The former opens up ideas, while the latter ensures deliverability.

    II. Beyond Benchmarks: Establishing Task-Level Evaluation Metrics

    Model iterations geared towards agents often emphasize capabilities in terminal operations, tool execution, automated workflows, and programming problem-solving. These metrics are meaningful because they reflect the agent’s potential in “multi-step execution.” However, benchmarks are only slices of capability and cannot directly represent product completion. A model might perform well on programming questions but still suffer from context drift, repetitive modifications, and missed acceptance criteria during long-horizon tasks.

    Evaluation closer to engineering should revolve around the task loop:

    1. Task Success Rate: Under given specifications and environments, whether all acceptance test cases can be passed after one or multiple attempts.
    2. First-Pass Rate: The proportion of cases that run without manual fixes after initial generation.
    3. Average Iteration Rounds: How many rounds of generation, execution, and fixing are needed from the initial version to passing acceptance.
    4. Invalid Output Ratio: The proportion of outputs with duplicate code, irrelevant explanations, unexecuted modifications, or broken existing functionality.
    5. Tool Call Reliability: Whether running, testing, log reading, and result parsing are stable.
    6. End-to-End Latency: The total time from issuing a task to obtaining a verifiable result.
    7. Manual Intervention Count: The number of times manual problem localization or prompt rewriting is required.
    8. Unit Cost of Successful Task: Total resource consumption divided by the number of accepted tasks.

    A “performance-cost Pareto improvement” can be understood as reducing invalid consumption without lowering quality, or improving the task success rate without increasing costs. For long-horizon agents, costs do not just come from a single model call. A single task may involve multiple rounds of planning, code generation, tool execution, error fixing, and result verification. If intermediate feedback is unclear, the agent will repeatedly trial and error, amplifying the real cost in a loop.

    Therefore, optimization focus should not only be on the price of a single call, but on:

    • Whether errors can be detected earlier;
    • Whether irrelevant context can be reduced;
    • Whether only necessary files are modified;
    • Whether clear failure reasons are provided when acceptance fails;
    • Whether invalid retries can be limited and checkpoints retained.

    A rough calculation can be done using the following formula:

    1. Unit Cost of Successful Task =
    2. (Model Call Cost + Tool Execution Cost + Manual Review Cost)
    3. / Number of Accepted Tasks

    This metric is closer to real development costs than simply counting tokens, and it encourages teams to optimize the agent execution process rather than just optimizing the surface length of prompts.

    III. From a Wish to Verifiable Specifications

    Inspired by the concept of “natural language to application,” the goal of this experiment can be stated as: implement a mini racing game running in a browser, supporting vehicle driving, track boundaries, timing, and switching between driver and rear camera views. This wish is enough to start the agent, but not enough for acceptance.

    A better approach is to complete the specifications first. Below is a universal prompt structure:

    1. Goal:
    2. Implement a single-page racing game prototype that runs offline.
    3. Environment and Constraints:
    4. - Use native browser capabilities without external network resources;
    5. - All graphics drawn programmatically or using embedded resources;
    6. - Clear code structure for easy rendering layer replacement;
    7. - No undocumented third-party dependencies allowed.
    8. Core Features:
    9. - Vehicle supports acceleration, braking, left and right steering;
    10. - Track has boundaries with clear feedback on collision;
    11. - Timer starts after the vehicle crosses the start line;
    12. - Supports switching between driver and rear camera views;
    13. - Supports pause, resume, and restart.
    14. State Model:
    15. - Vehicle position, speed, and heading;
    16. - Current lap, current time, best time;
    17. - Current view, paused state;
    18. - Track boundaries and checkpoints.
    19. Acceptance Test Cases:
    20. 1. Track and vehicle displayed after page load;
    21. 2. Vehicle accelerates and steers on key press;
    22. 3. Observable state change after boundary collision;
    23. 4. Timer starts after crossing the start line;
    24. 5. Camera switch does not break driving logic;
    25. 6. Timer and vehicle updates stop when paused;
    26. 7. State resets to initial values on restart.
    27. Output Requirements:
    28. - Provide complete runnable code;
    29. - Explain module division;
    30. - List executable acceptance checks.

    This specification does not aim to be exhaustive at once, but explicitly defines the most critical uncertainties. After the first round of generation, details can be added based on execution results, such as camera smoothing, speed feedback, track textures, collision damping, and best lap time display.

    IV. Prototype Architecture: Splitting the Game into Verifiable Modules

    Although the racing game is small, it already contains key elements typical of real-time applications. To prevent the agent from stuffing all logic into a single function, it can be required to split responsibilities:

    • Input Module: Collects keyboard or touch input with simple buffering;
    • Simulation Module: Updates vehicle state at a fixed time step;
    • Collision Module: Detects the relationship between the vehicle and track boundaries/checkpoints;
    • Camera Module: Calculates the observation position based on the current view;
    • Rendering Module: Draws the track, vehicle, timer, and prompt information;
    • Timer Module: Manages start, pause, lap time, and best scores;
    • Test Module: Verifies state transitions and key invariants.

    A fixed time step update loop is conducive to stable reproduction:

    1. state = init(seed)
    2. while running:
    3. input = collectInput()
    4. dt = clamp(frameDelta, 0, maxStep)
    5. while accumulator >= fixedStep:
    6. state = update(state, input, fixedStep)
    7. accumulator -= fixedStep
    8. render(state, camera(state))
    9. verifyInvariants(state)

    Vehicle updates can adopt a simplified physics model. It does not need to pursue realistic vehicle dynamics, but must ensure consistent feedback. For example:

    1. function updateVehicle(vehicle, input, dt):
    2. acceleration = input.throttle * enginePower
    3. friction = drag * vehicle.speed
    4. vehicle.speed += (acceleration - friction) * dt
    5. vehicle.speed = clamp(vehicle.speed, minSpeed, maxSpeed)
    6. steering = input.steer * steeringRate * speedFactor(vehicle.speed)
    7. vehicle.heading += steering * dt
    8. vehicle.position += direction(vehicle.heading) * vehicle.speed * dt
    9. if outsideTrack(vehicle.position):
    10. vehicle.speed *= collisionDamping
    11. vehicle.position = pushBackToTrack(vehicle.position)

    Timing and lap counting also need a clear state machine to avoid issues like “timing starts as soon as the vehicle moves” or “repeated lap counting due to crossing the line multiple times.” A checkpoint sequence can be used: the vehicle must pass the start line, mid-way checkpoints, and the finish line in order. Only when the sequence is correct is a lap completed. This both validates the logic and prevents timing anomalies caused by simple clipping.

    The corresponding tests can be written in pseudocode:

    1. test("Timer starts after crossing the start line"):
    2. state = init()
    3. crossStartLine(state)
    4. assert state.timer.running == true
    5. test("Vehicle and timer stop when paused"):
    6. state = init()
    7. start(state)
    8. pause(state)
    9. before = copy(state)
    10. update(state, input, fixedStep)
    11. assert state.timer.elapsed == before.timer.elapsed
    12. test("Camera switch does not change vehicle state"):
    13. state = init()
    14. before = copyVehicle(state.vehicle)
    15. toggleCamera(state)
    16. assert state.vehicle == before

    When these checks exist, the agent’s modifications in each round are more easily constrained to “fixing failed test cases” rather than arbitrary rewrites.

    V. The Agent Execution Loop: Plan, Execute, Observe, Fix

    Long-horizon agents fear two things: no feedback, and too much feedback. Without feedback, the model can only guess modifications; with too much feedback, the context is flooded with logs, diluting the real error. Therefore, the execution framework should provide structured observation results:

    1. Execution Results: Whether it started successfully, whether there were syntax errors or runtime exceptions;
    2. Test Results: Which acceptance cases passed, which failed, and what the failure assertions were;
    3. UI Results: Key screenshots or state snapshots to discover visual and interaction issues;
    4. Performance Results: Frame intervals, long task durations, and whether there is noticeable lag;
    5. Diff Results: Which files were modified this round and whether existing functionality was broken.

    The following loop is recommended:

    1. Plan: List minimal fix points based on failed test cases
    2. Execute: Modify only related modules, preserve existing acceptance items
    3. Observe: Run tests and collect errors, screenshots, logs
    4. Verify: Re-run all acceptance test cases, check for regressions
    5. Fix: Retry based on minimal failure information if failed
    6. Stop: Pass acceptance or reach retry limit

    Security and stability also require engineering constraints. For example, run generated code in an isolated environment, disable external network access, limit execution time and resource usage, use dependency whitelists, and save diffs and checkpoints for each round. For tasks involving file writes, writable directories should be restricted, and a rollback snapshot should be generated after each round.

    VI. Second Iteration: From “Playable” to “Fun”

    The first round of generation often completes basic gameplay, but the visuals and details fall far short of expectations. At this point, it is not recommended to simply say “make it look better,” because this phrase is not verifiable. More effective feedback should be divided into three categories:

    • Gameplay Issues: Unnatural acceleration curves, overly sensitive steering, too weak collision feedback;
    • Presentation Issues: Lack of track boundary indicators, low vehicle recognizability, inconspicuous timing information;
    • Engineering Issues: Unstable frame rate, camera shaking after switching views, timer not freezing when paused.

    The second round of prompts can be organized as follows:

    1. While keeping all existing acceptance cases passing, modify by priority:
    2. 1. Add a sense of speed to the vehicle, such as dynamic FOV, speed lines, and brake feedback;
    3. 2. Add damping to camera follow, smoothing to position within 0.3 seconds after switching views;
    4. 3. Add high-contrast indicators to track boundaries, brief slowdown and offset upon collision;
    5. 4. Display current and best lap times in the timing area, keep unchanged when paused;
    6. 5. Add new tests: switching views does not change vehicle state; pausing does not advance timer.
    7. Prohibited:
    8. - No external resources introduced;
    9. - No rewriting of track data structures;
    10. - No deletion of existing tests.

    Handling only one set of related issues per round makes it easier to locate regressions. If physics, rendering, UI, and sound effects are all requested for a redo at once, the agent will likely modify the code extensively, making it difficult to determine which module caused the failure.

    VII. Key Levers for Performance-Cost Optimization

    To truly reduce the cost of long-horizon agents, the core is not to make prompts as short as possible, but to reduce invalid loops. The following strategies can be adopted:

    1. Stable Specification Caching: Place goals, constraints, and acceptance criteria that rarely change in a fixed context to avoid repeated generation each round.
    2. Structured Feedback: Only pass back failed test cases, error summaries, and necessary log fragments to prevent entire logs from polluting the context.
    3. Minimal Diff Modification: Require the agent to modify only related files and output change descriptions and impact scopes.
    4. Fail Fast: Execute syntax checks, basic runs, and key unit tests as early as possible. Do not wait until full rendering to expose low-level errors.
    5. Checkpoints and Rollbacks: Save a runnable version each round. Revert to the most recent passing version on failure to reduce cascading breakage.
    6. Retry Limits: Set a maximum number of attempts for the same type of error. If exceeded, switch to manual diagnosis.
    7. Task Splitting: Divide “generate prototype,” “add acceptance tests,” “optimize visuals,” and “organize docs” into independent tasks to reduce single-pass context complexity.
    8. Cost Evaluation via Successful Tasks: Do not just look at how much code is generated, but at how many rounds and manual reviews a successful delivery consumes.

    These strategies have a direct effect on the “performance-cost Pareto improvement”: reducing repeated generation and invalid tool calls without compromising quality; increasing the first-pass rate without increasing costs. For long-horizon tasks, even reducing a small amount of invalid output per round will amplify cumulative benefits across multiple loops.

    VIII. Transferable Practical Conclusions

    This practice of moving from a natural language wish to a racing prototype yields several transferable experiences.

    First, wishes are for starting, specifications are for delivery. Natural language can quickly express intent, but it must be supplemented with runtime environments, state models, interaction details, and acceptance test cases. A “successful generation” without acceptance criteria has no engineering significance.

    Second, benchmarks are directions, not conclusions. Evaluations in terminal operations, automated tasks, and programming problem-solving can indicate the direction of agent capability changes, but they cannot replace stability, observability, and cost accounting in real projects.

    Third, cost management for long-horizon tasks is a first-class engineering problem. Every task for an agent is a multi-round loop. The real costs come from failed retries, log bloat, context drift, and repetitive modifications. Establishing isolated execution, structured feedback, regression testing, and checkpoint mechanisms is more important than simply pursuing longer context.

    Fourth, a gap exists between demo quality and product quality, bridged by a verification system. Generating a playable racing game in the first round is not uncommon; the difficulty lies in making it reproducible, testable, maintainable, and resilient against broken existing functionality across multiple iterations.

    For developers, wishful programming does not replace engineering methods; it shifts the engineering focus forward to “specification expression” and “verification design.” Whoever can translate vague wishes into clear acceptance criteria will more stably leverage agents to complete long-horizon tasks. For teams, the more valuable capability to build is not a specific prompt template, but an observable, rollback-capable, and measurable agent execution process. Only in this way can the appeal of a single demo translate into continuous, usable productivity.