Reverse Engineering and Rewriting a Classic Game with LLMs: A Technical Practice Report

    This article documents a roughly two-week experiment in using AI coding tools to reverse engineer a last-century real-time strategy game from its executable and rewrite it in a modern systems language. It explains why missing specifications, proprietary formats, and non-enumerable behavior make this a strong stress test for long-horizon automated coding, then walks through acceptance criteria, format reverse engineering, license compliance, CI gating, replay-based logic verification, and performance considerations. Readers will find practical engineering practices for turning autonomous coding output into something runnable, testable, and deliverable.

    1. Why Rewriting an Old Game Without Source Code Is a Good Testbed

    The source material records an experiment of roughly two weeks: using an AI coding tool to reverse engineer a real-time strategy game released decades ago from the executable, then rewrite it in a modern systems language. The goal was not to replicate the visuals, but to reproduce an engineering skeleton that is runnable, playable against opponents, and extensible.

    The value of this choice is that it compresses three of the hardest problems in software engineering into a single container: missing specifications, proprietary formats, and non-enumerable behavior.

    First, missing specifications. The original source code was lost long ago, and the only authoritative implementation is the binary itself. Any rewrite is effectively reverse engineering with the black box as the sole source of truth, so the specification must be inferred from behavior.

    Second, proprietary formats. Games of this era typically use custom resource containers, proprietary animation and video encodings, binary scripts, and map layouts. The community has almost no general-purpose parsing implementations available.

    Third, non-enumerable behavior. Unit pathfinding, damage calculation, armor-type counters, and chrono-shift mechanics are tightly coupled, making them hard to cover with a finite set of test cases.

    This makes the project a strong stress test for long-horizon automated coding: the output is runnable, comparable, and regression-testable.

    2. Defining the Rewrite as an Acceptance-Driven Engineering Problem

    Before starting, the goal should be reframed from “does it look the same” to “can it be verified.” It helps to split acceptance into four layers and converge layer by layer:

    1. Resource readability: parse all key containers and encodings into a unified intermediate representation.
    2. Logic equivalence: core combat and construction logic produce the same results as the original implementation for given inputs.
    3. Interaction usability: the UI, hotkeys, build queues, and path display are sufficient to complete a standard match.
    4. Multiplayer readiness: state synchronization, reconnection after disconnects, and save compatibility reach a demonstrable level.

    Mapped to milestones, the original experiment was divided into pre-Alpha (engineering and resource pipeline), Alpha (UI and interaction loop), Beta (combat and AI), and finally the multiplayer stage. This follows the principle of “get the narrowest path working first, then expand horizontally”: first make one unit creatable, movable, and able to fire, then expand factions and the tech tree.

    3. Format Reverse Engineering: From Magic Constants to a Maintainable Parsing Layer

    Old game resource formats usually have no public documentation. The first step is to build a three-level model of container, chunk, and field, using a hex viewer and diff comparison to locate offsets. The most common pitfall in practice is hard-coding observed values as constants, which breaks as soon as the version changes. A more robust approach has three layers:

    • Probe layer: read the file header magic number, version, and chunk length, with bounds checking.
    • Intermediate layer: map different formats uniformly to textures, palettes, frame sequences, audio blocks, and script instructions.
    • Render layer: depend only on the intermediate layer, hiding differences in specific encodings.

    Illustrative code (pseudo-Rust style):

    1. enum Chunk { Palette(Vec<u8>), Frame(FrameDesc), Audio(AudioBlock), Script(Vec<Op>) }
    2. fn parse_container(bytes: &[u8]) -> Result<Vec<Chunk>, Error> {
    3. let mut cur = 0usize;
    4. let mut out = Vec::new();
    5. while cur + 8 <= bytes.len() {
    6. let tag = &bytes[cur..cur + 4];
    7. let len = u32::from_le_bytes(bytes[cur + 4..cur + 8].try_into()?) as usize;
    8. let body = bytes.get(cur + 8..cur + 8 + len).ok_or(Error::Truncated)?;
    9. out.push(match tag {
    10. b"PAL " => Chunk::Palette(body.to_vec()),
    11. b"FRM " => Chunk::Frame(FrameDesc::parse(body)?),
    12. _ => return Err(Error::UnknownTag(*tag)),
    13. });
    14. cur += 8 + len;
    15. }
    16. Ok(out)
    17. }

    On license compliance, the most valuable takeaway from the source material is this: when only a few open-source implementations exist for a proprietary encoding, the model tends to “check the license first and then decide whether it can be referenced,” and turns to an independent implementation when the licenses are incompatible. The correct engineering posture is to make license review an upstream pipeline gate rather than an ad-hoc negotiation during the coding phase:

    • Establish a dependency allowlist that states the permitted license types and linking methods.
    • For implementations that may be referenced but not copied, extract only the format specification and algorithmic ideas, implement independently, and leave a design note.
    • Every third-party code introduction must have a provenance record and change notes for auditing.

    It is worth stressing that “memorizing constants and writing them out from memory” is not acceptable engineering practice: it is unmaintainable and creates compliance risk. The maintainable approach is to centralize constants in an annotated specification table with unit tests, for example:

    1. #[test]
    2. fn palette_index_wraps() { assert_eq!(wrap(255, 1), 0); }

    4. Long-Horizon Automation: Managing Context, Licensing, and “Clever” Behavior

    The original experiment noted that the model refuses when asked to “copy,” but tends to reference an existing implementation when the context is “someone has implemented this algorithm.” It also observed an extremely high output rate of hundreds of commits per day. Together, these suggest that the core of long-horizon automation is not making the model more obedient, but caging uncertainty.

    1. Break tasks down finely enough to be independently verifiable. Each commit should correspond to a small, runnable, testable goal, such as “parse the palette and pass a snapshot test.”
    2. Manage the context budget explicitly. Write specifications, interface contracts, and license policy into in-repo specification files so the tool loads only the necessary fragments each time, reducing token waste and drift.
    3. Make behavior constraints executable. Use CI as a hard gate: format parsing must pass fuzzing, logic changes must pass regression replay diffs, and a failed license scan fails the build directly.
    4. Make output observable. Commit frequency is not progress; track outcome metrics such as “number of passing test cases,” “playable match duration,” and “crash rate.”

    A simplified gate configuration:

    1. stages:
    2. - fmt_and_lint
    3. - unit_and_snapshot
    4. - fuzz_parse: { seconds: 120 }
    5. - replay_diff: { tolerance: 0 }
    6. - license_scan: { allow: [MIT, Apache-2.0] }

    5. Logic Equivalence: Replay Diffing Instead of Eyeballing

    Combat logic is the hardest to verify because it consists of large amounts of floating-point math, randomness, and state machines. A workable approach is “record, replay, diff”: fix the random seed and the input command sequence, drive both the original and the rewritten implementations, and compare key state per frame (position, health, ammo, construction progress). When a divergence appears, binary-search to the first inconsistent command to pinpoint the logic difference.

    1. Input: command sequence + seed
    2. Output: per-frame state hash
    3. Decision: first differing frame -> locate the specific command

    For floating-point differences, agree on a unified fixed-point or rounding strategy to avoid cases that “look the same but are actually inconsistent.”

    6. Performance and Resources: Benefits and Pitfalls of Modern Systems Languages

    Rewriting in a modern systems language naturally provides memory safety and concurrency, but it is easy to over-engineer rendering and pathfinding. Recommendations:

    • Decouple logic from rendering, and keep the logic layer deterministic for replay.
    • Use hierarchical graphs or flow fields for pathfinding instead of a full-map search per unit.
    • Make resource loading asynchronous and use object pools to reduce jitter.
    • Collect crash, frame-time, and memory curves through monitoring, alerting, and logging services for continuous observability.

    If multiplayer and save distribution are needed, a combination of general-purpose cloud capabilities works: object storage for resources and replay files, a container platform to host match services, a message queue for room and state broadcasts, and logging and monitoring for observability. These are all general categories and do not involve any vendor-proprietary interfaces.

    7. Common Pitfalls and Checklist

    • Put the license gate upstream; no “write first, review later.”
    • Proprietary formats must have bounds checking and fuzzing.
    • Centralize constants with tests; eliminate scattered magic values.
    • Every commit must be independently revertible; accept milestones with demonstrable scenarios.
    • Replace subjective judgment with replay diffing, and commit counts with outcome metrics.

    8. Conclusion

    The real lesson from this experiment is not whether a model can write a large project, but that when specifications are missing, formats are proprietary, and behavior is coupled, engineering discipline is the variable that determines success. Making licensing, verification, and observability hard pipeline constraints is what moves long-horizon automation from a spectacle to something deliverable.