From Eye-Catching Menus to Playable Combat: A Complete Refactor Guide for AI-Generated 3D Fighting Games

    AI code-generation tools can quickly produce a 3D fighting game with a polished main menu and character select, then fall apart the moment a real match starts. That gap comes from a mismatch in requirements: presentation scenes tolerate sloppy numbers, while combat is a frame-exact real-time system. This article catalogs the typical symptoms, then walks through a systematic engineering rebuild covering the fixed-timestep loop, fighter state machines and frame data, hit detection and combo rules, AI and local versus play, 3D scene rendering and performance budgets, and a data-driven, automatically verified workflow. Each section includes illustrative TypeScript, JSON, and configuration snippets you can adapt to your own project.

    1. Where It Goes Wrong: Why a Great Menu Doesn’t Mean a Great Fight

    When you ask an AI coding tool to build a 3D fighting game, you usually end up in this situation:

    • The main menu and character select look polished, and the character showcase and stage atmosphere are genuinely good;
    • Two original fighters and a rainy rooftop stage look impressive in the showcase scenes;
    • The moment a match starts, one experience problem after another surfaces.

    This gap is not an accident. The two kinds of scenes place completely different demands on the code:

    1. Showcase scenes tolerate mistakes. The menu and character showcase are essentially animation playback and camera work driven by a preset timeline. Occasional wrong numbers or logic glitches rarely show.
    2. Combat scenes allow no deviation. A fighting game is built on a frame-exact, deterministic state machine. A single misplaced hitbox, a wrong priority, or an inconsistent timestep immediately damages game feel and fairness.

    Typical symptoms include:

    • The animation has finished but the character is still moving (or stopped long ago): the move and its hit detection are out of sync;
    • One side lands an endless string of hits and the opponent can never escape, the classic “infinite combo”;
    • Directional command inputs frequently fail or trigger the wrong move;
    • Game feel differs noticeably between high-refresh-rate displays and low-frame-rate devices;
    • The AI either stands still or only walks forward;
    • The screen stutters and the camera jumps after a super move cutscene.

    Most of these are not “it looks bad” problems. They are “it isn’t fun” problems. To move a project from “impressive opening” to “actually playable,” combat has to be rebuilt as a strict real-time system. The approach below follows five principles:

    • separate logic from presentation;
    • make time and state deterministic;
    • move rules into data;
    • keep game feel tunable;
    • make quality verifiable.

    2. Overall Architecture: Fully Separating Logic from Presentation

    A fighting game is a real-time interactive system. Establish one non-negotiable rule first: combat logic and rendering must be completely separated. The logic layer only cares about position, state, frame counters, and hit detection. The rendering layer only draws the state of a given logical frame. The payoff is threefold:

    • game speed no longer drifts with frame rate;
    • any match can be reproduced exactly through input replays;
    • automated matches can verify balance and stability.
    1. src/
    2. ├── core/ # Pure logic, independent of rendering
    3. │ ├── loop.ts # Fixed-timestep main loop
    4. │ ├── input.ts # Input sampling and buffering
    5. │ ├── fighter.ts # Fighter state machine and attributes
    6. │ ├── moves.ts # Move frame data and hitboxes
    7. │ ├── combat.ts # Hit resolution, guard, juggle, combo and cancel rules
    8. │ ├── ai.ts # Three-tier AI controller
    9. │ ├── camera.ts # Combat camera (logical coordinates)
    10. │ └── rules.ts # Round flow and match rules
    11. ├── data/ # Data-driven layer
    12. │ ├── characters.json # Character parameters and move lists
    13. │ ├── moves/*.json # Frame data for each move
    14. │ └── schema.json # Configuration validation rules
    15. ├── render/ # Presentation: scene, character animation, effects, rainy-night mood, post-processing
    16. ├── ui/ # Character select, HUD, pause, results screens
    17. └── assets/ # Models, textures, animations, audio

    In terms of call flow, the main loop advances logic at a fixed rate and the render layer only reads logical state:

    1. Input sampling → Input buffer → Fighter state machine → Moves and hitboxes → Hit resolution → Round rules → Render snapshot
    2. ↑ │
    3. └──────────────────── AI controller (shares the player input interface) ←───────────────┘

    3. The Foundation: A Fixed-Timestep Loop

    3.1 Why the Timestep Must Be Fixed

    If the main loop advances game logic “by real elapsed time each frame,” two problems appear:

    • Speed depends on frame rate. On a 144Hz display, the whole game runs relatively faster (the exact amount depends on the implementation). The “faster by a few frames” relationships between moves also shift, which distorts combo links and guaranteed-punish judgments.
    • Results are not reproducible. Floating-point elapsed time introduces tiny differences that make debugging and regression testing difficult.

    The correct approach is to advance logic at a fixed frequency (60 steps per second is common for fighting games) while rendering runs independently at the display refresh rate:

    1. // core/loop.ts: fixed-timestep main loop (illustrative)
    2. const STEP_MS = 1000 / 60; // one logical step = 1 game frame
    3. let acc = 0;
    4. let last = performance.now();
    5. function frame(now: number) {
    6. // Cap the maximum catch-up steps per frame, so restoring a background tab
    7. // doesn't simulate hundreds of steps at once
    8. const elapsed = Math.min(now - last, 100);
    9. last = now;
    10. acc += elapsed;
    11. while (acc >= STEP_MS) {
    12. if (!game.isPaused) game.step(); // don't advance logic while paused; no catch-up needed
    13. acc -= STEP_MS;
    14. }
    15. // alpha is the interpolation factor used to smooth motion between two logical updates
    16. renderer.draw(game.snapshot(), acc / STEP_MS);
    17. requestAnimationFrame(frame);
    18. }

    3.2 Express All Timing in Frames

    After this change, every timing value in the game is expressed in game frames. “Startup of 4 frames” means hit detection appears on the 4th frame after the input. The benefit is that move timing is identical on a 60Hz and a 120Hz display.

    3.3 Handling Pause

    When the game is paused, stop accumulating time and reset the time base on resume:

    1. function pause() { game.isPaused = true; last = performance.now(); acc = 0; }
    2. function resume() { last = performance.now(); game.isPaused = false; }

    Without this, all the real time spent paused gets simulated in one burst the instant you resume, and the character visibly “teleports” through part of an animation.

    4. The Input Layer: Command Recognition and Buffering

    4.1 Sampling and Normalization

    Fighting games are extremely sensitive to input, so the input layer should:

    • sample on the key-down edge, reading which buttons were pressed this step rather than the held state;
    • map buttons from keyboards, gamepads, and other devices onto abstract actions: up, down, left, right, light attack, heavy attack, guard, and so on;
    • have the AI controller emit exactly the same input structure as player devices, so both follow identical rules.
    1. // core/input.ts: key-down edge sampling (illustrative)
    2. interface FrameInput {
    3. dir: Dir; // eight-way direction composed from up/down/left/right, e.g. 'F', 'DF'
    4. attack: string | null; // attack button pressed on this step
    5. }
    6. function sample(keys: Set<string>): FrameInput {
    7. const dir = mapToEightWay(keys); // device mapping happens once at initialization
    8. const pressed = [...keys].filter(k => !prevKeys.has(k));
    9. const attack = pressed.find(k => ATTACK_KEYS.includes(k)) ?? null;
    10. prevKeys = new Set(keys);
    11. return { dir, attack };
    12. }

    4.2 Command Recognition: Direction Sequence Plus Attack Button

    A move command can be modeled as “a direction sequence plus an attack button.” For example, “down, down-forward, forward + light attack” (commonly written 236) triggers a projectile-type move, while “forward, down, down-forward + attack” (commonly written 623) triggers a rising uppercut-type move.

    Implementation notes:

    • keep a ring buffer of input history per player, recording the direction and attack button for each step;
    • on every step, walk backwards from the end of the history looking for a matching direction sequence, and check whether the corresponding attack button was pressed;
    • allow tolerance on directions. When a player slides from “forward” through “down-forward” to “down,” for instance, you may see intermediate samples where the stick hasn’t reached a cardinal point;
    • limit the command to a time window (such as 14 frames) so old history isn’t misread;
    • move priority: when several commands match at once, pick a single result by a preset priority. 623 should outrank 236, and only one move may trigger per step.
    1. // core/input.ts: command recognition (illustrative)
    2. interface HistoryItem { dir: Dir; attack: string | null; age: number }
    3. const COMMANDS = [
    4. { id: 'DP_P', pattern: ['F', 'D', 'DF'], attack: 'P', window: 14, priority: 2 },
    5. { id: 'QCF_P', pattern: ['D', 'DF', 'F'], attack: 'P', window: 14, priority: 1 },
    6. ];
    7. function matchCommand(history: HistoryItem[], input: FrameInput): string | null {
    8. const tail = [...history, { dir: input.dir, attack: input.attack, age: 0 }].slice(-16);
    9. let best: { id: string; priority: number } | null = null;
    10. for (const cmd of COMMANDS) {
    11. const n = cmd.pattern.length;
    12. for (let i = tail.length - n; i >= 0; i--) {
    13. const seg = tail.slice(i, i + n);
    14. if (seg.some(item => item.age > cmd.window)) continue;
    15. if (seg[seg.length - 1].attack !== cmd.attack) continue;
    16. // Allow neutral direction, e.g. an instant in the middle of the motion where the stick returned to center
    17. const ok = cmd.pattern.every((d, k) => seg[k].dir === d || seg[k].dir === 'N');
    18. if (ok && (!best || cmd.priority > best.priority)) best = { id: cmd.id, priority: cmd.priority };
    19. break;
    20. }
    21. }
    22. return best?.id ?? null;
    23. }

    4.3 Input Buffering: Improving Responsiveness

    When a player presses a button while the character is still in hitstun or recovery, discarding the input outright makes the game feel unresponsive. The common fix is a short buffer window, typically 4–6 frames:

    1. let buffer: { action: string; ttl: number } | null = null;
    2. function updateBuffer(input: FrameInput) {
    3. const cmd = matchCommand(history, input);
    4. if (cmd) buffer = { action: cmd, ttl: 6 };
    5. else if (buffer && --buffer.ttl <= 0) buffer = null;
    6. }
    7. // Each step, the fighter attempts a state transition and consumes the buffer along the way
    8. function tryBuffer(f: Fighter) { if (buffer) { const a = buffer.action; buffer = null; return a; } return null; }

    Don’t make the window too long, or you get the bizarre result of a move firing after the character has already hit the ground.

    5. Fighter State Machine and Frame Data

    5.1 State List

    Model character states explicitly as a finite state machine, covering at least:

    • Basic states: idle, forward/back walk, crouch, jump (including rise and fall), guard (standing and crouching), hitstun (including knockdown and wakeup);
    • Attack states: one per move, composed of startup, active, and recovery frames;
    • Special states: airborne, thrown, guard-broken stun.
    1. // core/fighter.ts: fighter state machine (illustrative)
    2. type State = 'IDLE' | 'WALK_F' | 'WALK_B' | 'CROUCH' | 'AIR' | 'GUARD' | 'HIT' | 'KNOCKDOWN' | 'ATTACK';
    3. class Fighter {
    4. state: State = 'IDLE';
    5. stateFrame = 0; // frames elapsed in the current state
    6. facing = 1; // 1 faces right, -1 faces left
    7. hitstop = 0; // hitstop frames remaining
    8. cancelOk = false; // has this move been confirmed as hit or blocked this step
    9. tick() {
    10. if (this.hitstop > 0) { this.hitstop--; return; } // motion freezes during hitstop
    11. this.stateFrame++;
    12. // State transitions, move progression, gravity and displacement are all updated per frame here
    13. }
    14. }

    5.2 Frame Data and the Transition Table

    Every move needs a complete data definition. The key fields are:

    Field Meaning Design notes
    startup Startup frames Frames before hit detection appears; smaller means faster
    active Active frames Frames during which hit detection persists
    recovery Recovery frames Frames of continued inaction after hit detection ends
    damage Damage Base damage value
    hitstun / blockstun Hitstun / blockstun How long the opponent cannot act after being hit or blocking
    level Hit level Mid, low, or overhead; determines whether it can be crouch- or stand-guarded
    pushback Displacement and knockback Determines whether combos connect and how corner behavior works
    hitstop Hitstop Frames both characters freeze on contact; directly shapes impact feel
    cancels Cancel targets Which moves this move can be chained into after connecting

    Legal transitions between states should be constrained by a single transition table rather than scattered if-else checks that inevitably miss cases:

    1. const TRANSITIONS: Record<State, State[]> = {
    2. IDLE: ['WALK_F', 'WALK_B', 'CROUCH', 'AIR', 'GUARD'],
    3. CROUCH: ['IDLE', 'AIR', 'GUARD'],
    4. AIR: ['IDLE', 'CROUCH', 'WALK_F'],
    5. GUARD: ['IDLE', 'CROUCH'],
    6. HIT: ['IDLE', 'KNOCKDOWN'],
    7. KNOCKDOWN: ['IDLE'],
    8. ATTACK: [],
    9. };
    10. function canSwitch(from: State, to: State) { return TRANSITIONS[from].includes(to); }

    6. Hit Detection and Offense/Defense Resolution

    6.1 Boxes and the Plane Constraint

    A 3D fighting game has to commit to one spatial model:

    • Full 3D space: characters move freely in three dimensions. You must handle displacement, collision, and camera follow on the depth axis, and both implementation and tuning complexity rise sharply.
    • Planar combat (2.5D): characters are locked to a single combat plane (z=0), left/right and forward/back map to screen left/right, and the 3D shows up in the models, stage, and camera. Most classic arcade fighters use this model, and it is the recommended default.

    For hit detection, give each character a capsule or box hurtbox, and generate attack boxes during active frames from frame data. When two boxes intersect on the combat plane, the hit lands; the 3D model itself never participates in collision math.

    1. // core/combat.ts: box overlap and hit resolution flow (illustrative)
    2. function overlaps(a: Box, b: Box) {
    3. return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
    4. }
    5. function resolveHits(a: Fighter, b: Fighter) {
    6. if (a.state !== 'ATTACK' || a.hitstop > 0) return;
    7. const m = a.currentMove();
    8. if (a.stateFrame < m.startup || a.stateFrame >= m.startup + m.active) return;
    9. if (a.hitConfirmed) return; // a given move resolves only once per activation
    10. const box = { x: a.x + a.facing * m.box.offsetX - (a.facing < 0 ? m.box.w : 0), y: m.box.offsetY, w: m.box.w, h: m.box.h };
    11. if (!overlaps(box, b.hurtbox())) return;
    12. a.hitConfirmed = true;
    13. applyHit(a, b, m);
    14. }

    6.2 Offense and Defense Priority

    • Priority and startup. When both attack boxes connect on the same frame, use move priority and startup to decide who resolves first. At equal priority, the move with fewer startup frames wins: fast beats slow.
    • Hit levels. Low attacks can only be crouch-guarded, overheads only stand-guarded, and mids can be guarded either way.
    • Guard direction. Characters always face the opponent, so guard detection only needs to check “is back held, and does the hit level match.”
    • Pushbox collision. Characters cannot overlap. When one walks forward, the other gets pushed; when the defender is cornered, the advancing character stops instead.
    • Throws. Throws typically have armor or invincibility but cannot be guarded. After being thrown, the victim enters throw stun and must be flagged so they can’t be thrown again immediately.

    7. Combos, Juggling, and Cancel Rules

    Whether one attack chains into another depends on three things: whether it connected, whether the opponent is still in stun afterward, and whether the current move allows cancels. The core rules:

    1. Hit confirmation. Only a confirmed hit or block enables cancels. At the end of each step, check whether the attack box touched the opponent and set the cancelOk flag accordingly.
    2. Cancel table. Once a move connects, it can chain into the moves listed in a configuration table, for example normal → special → super.
    3. Time window. Cancels are only legal within a limited number of frames after hit confirmation, which keeps combo timing tight.
    4. Juggle routing. A launch puts the opponent into an airborne state. When hitting an airborne target, cap the number of follow-ups (the “juggle limit”) and accelerate the fall with gravity so the combo has a natural end point.
    5. Damage scaling. Each subsequent hit in a combo deals reduced damage (for example ×0.9 per hit with a floor), so a single combo can’t end the match.
    6. Links with cancels. Link frames between moves should line up with the cancel window so advanced “link first, then cancel” combos can be executed reliably.
    1. // core/fighter.ts: cancel validation (illustrative)
    2. const CANCEL_TABLE: Record<string, string[]> = {
    3. lightP: ['special_qcf'],
    4. heavyK: ['special_qcf', 'super'],
    5. special_qcf: ['super'],
    6. };
    7. function canCancel(a: Fighter, b: Fighter): boolean {
    8. if (!a.cancelOk || a.hitstop > 0 || b.hitstun <= 0 && b.state !== 'AIRBORNE') return false;
    9. const window = a.currentMove().cancelWindow ?? 0;
    10. const sinceHit = a.stateFrame - (a.lastHitFrame ?? -999);
    11. const allowed = CANCEL_TABLE[a.currentMove().id] ?? [];
    12. return sinceHit <= window && allowed.some(id => fsm.canSwitch(a.state, 'ATTACK'));
    13. }

    7.2 About “Infinites”

    A combo counts as an infinite when it meets three conditions: high success rate, low execution barrier, and high payoff. So every new cancel node should be validated with automated matches: can the AI land the combo consistently, and does the opponent have an escape option?

    8. Specials and Supers: Presentation and Pacing

    8.1 Meter and Super Activation

    • Meter gain. Landing hits, taking hits, and guarding all build meter; a full meter allows a super.
    • Cost and priority. Supers usually consume the entire meter and take priority over regular specials.
    • Activation conditions. Both a full meter and a legal state (cancel window or neutral) must be satisfied.
    • When hit. Meter is retained when the character is hit, so one mistake doesn’t wipe out all accumulated resource.

    8.2 Cinematic Phases and Skip Handling

    Super cutscenes easily break the pace. Solve it like this:

    • define the super cinematic as its own phase (for example SUPER_FREEZE); combat logic freezes entirely and only the camera and effects animate;
    • set a maximum duration; when the cinematic ends, the character immediately enters the super move state;
    • support skipping: roughly 0.5 seconds after the cinematic starts, any button skips it;
    • during the cinematic, use camera push-in, shallow depth of field, and slow motion, paired with dedicated sound effects to sell the impact.
    1. // core/rules.ts: super cinematic phase (illustrative)
    2. if (game.phase === 'SUPER_FREEZE') {
    3. const c = game.cinematic;
    4. c.elapsed++;
    5. camera.cinematic(c.attacker, c.target, Math.min(1, c.elapsed / c.duration));
    6. if (c.elapsed >= c.skipAfter && anyPressed()) c.elapsed = c.duration;
    7. if (c.elapsed >= c.duration) { game.phase = 'FIGHT'; c.attacker.startMove(c.moveId, { super: true }); }
    8. return; // no character logic advances during the freeze
    9. }

    9. The AI Opponent: Engineering Three Difficulty Levels

    The two most common AI failures are mindless forward pressure and hard difficulty that cheats with faster reactions. The sound approach is to let the AI share the player’s input interface, then control its behavior in layers.

    9.1 Layered Design

    1. Perception. Read visible information only: distance between fighters, the opponent’s current state, remaining stun frames.
    2. Decision. Choose an intent using “finite state machine plus strategy weights”: approach, retreat, guard, counterattack, attack.
    3. Execution. Convert intent into an input sequence with a “reaction delay” and a “decision interval.”

    The three difficulties are separated by these parameters:

    Parameter Easy Normal Hard
    Decision interval ~12 frames ~6 frames ~3 frames
    Guard probability ~10% ~45% ~75%
    Combo ability No combos Basic link combos Cancel combos plus link mix-ups
    Meter management Random usage Timely usage Holds or spends based on the situation
    Punishing gaps Mostly ignored Occasional counters High-probability guaranteed punishes
    1. // core/ai.ts: three-tier AI decision making (illustrative)
    2. const LEVELS = {
    3. easy: { think: 12, guard: 0.10, combo: 0, punish: 0.05 },
    4. normal: { think: 6, guard: 0.45, combo: 1, punish: 0.40 },
    5. hard: { think: 3, guard: 0.75, combo: 3, punish: 0.85 },
    6. };
    7. class AIController {
    8. private cooldown = 0;
    9. constructor(private level: keyof typeof LEVELS) {}
    10. next(self: Fighter, foe: Fighter): FrameInput {
    11. if (this.cooldown > 0) { this.cooldown--; return { dir: 'N', attack: null }; }
    12. const cfg = LEVELS[this.level];
    13. const dist = Math.abs(foe.x - self.x);
    14. const toward: Dir = foe.x > self.x ? 'F' : 'B';
    15. if (dist < 2.5 && foe.state === 'ATTACK' && Math.random() < cfg.guard) {
    16. this.cooldown = 10; return { dir: foe.currentMove()?.level === 'LOW' ? 'DB' : 'B', attack: null };
    17. }
    18. if (dist < 1.6 && self.stunFrames > 20 && Math.random() < cfg.punish) {
    19. this.cooldown = 4; return { dir: toward, attack: 'H' };
    20. }
    21. if (dist > 2.0) { this.cooldown = cfg.think; return { dir: toward, attack: null }; }
    22. this.cooldown = cfg.think;
    23. return { dir: 'N', attack: 'L' };
    24. }
    25. }

    9.2 Fairness Constraints

    • The AI never reads player input that hasn’t happened yet;
    • AI combo execution follows the same input buffering and command recognition rules as the player;
    • Give the AI a “reaction delay,” the interval between perceiving the opponent’s action and actually guarding;
    • Hard difficulty does not boost AI damage or reduce its hitstun. It only improves decision quality.

    10. Local Two-Player, Round Rules, and the Flow State Machine

    10.1 Local Versus

    • Use the input abstraction layer to hide differences between keyboard and gamepad, so the two players can use different devices;
    • Document key conflicts and key-rollover limits per device. Some keyboards fail to register several simultaneous presses, so a hint to use a gamepad is worth showing in the UI;
    • Both players’ inputs are sampled in the same logical step, so there is no first-move advantage.

    10.2 Round Rules

    Model the round flow as an explicit flow state machine:

    1. // core/rules.ts: round flow (illustrative)
    2. type Phase = 'ROUND_INTRO' | 'FIGHT' | 'ROUND_END' | 'MATCH_END';
    3. class MatchRules {
    4. phase: Phase = 'ROUND_INTRO';
    5. timer = 99; rounds = 0; wins = [0, 0]; intro = 120; // 2-second round intro countdown
    6. tick(p1: Fighter, p2: Fighter) {
    7. if (this.phase === 'ROUND_INTRO' && --this.intro <= 0) this.phase = 'FIGHT';
    8. if (this.phase !== 'FIGHT') return;
    9. if (--this.timer > 0 && p1.hp > 0 && p2.hp > 0) return;
    10. this.wins[p1.hp === p2.hp ? 2 : p1.hp > 0 ? 0 : 1]++; // no score on a draw; replay the round
    11. this.rounds++;
    12. this.phase = this.wins.some(w => w >= 2) ? 'MATCH_END' : 'ROUND_END'; // best of three
    13. }
    14. }

    Supporting rules include:

    • Time over. The fighter with the higher remaining health percentage wins;
    • Draw. If both fighters hit zero at the same time or health is exactly equal, the round is replayed;
    • Character select. A separate screen supporting keyboard and gamepad, with selections locked before the round begins;
    • Pause. Pausing stops logic immediately and corrects the timer; the UI can offer restart or quit.

    11. 3D Scene and Rendering: Atmosphere and Performance on a Rainy Rooftop

    11.1 Character and Stage Presentation

    • Character models need a full skeleton rig and animation set: idle, movement, crouch guard, hitstun, airborne, knockdown, and every move animation;
    • The mapping from animations to logical states should live in a data table; hardcoding is not allowed;
    • A rainy rooftop stage can use volumetric fog, combined directional and point lights, wet-floor reflections, rain-streak particles, distant neon bloom, and brief lightning fill light for atmosphere, finished with tone mapping and bloom in post-processing.

    11.2 Combat Camera

    • Keep the camera focus at the midpoint between the two fighters, with distance varying dynamically based on their separation and clamped to the stage bounds;
    • On hit, a short camera shake whose intensity scales with damage works well;
    • On supers, cut to a close-up angle and smoothly return to the combat camera afterward.

    11.3 Performance Budget

    Set an explicit performance budget for browser and mobile targets, then tier it by device capability:

    1. // render/quality.ts: device-tiered rendering presets (illustrative)
    2. const PRESETS = {
    3. high: { rain: 1200, reflections: true, shadow: 2048, post: true },
    4. medium: { rain: 600, reflections: false, shadow: 1024, post: true },
    5. low: { rain: 250, reflections: false, shadow: 512, post: false },
    6. };

    Beyond rain count, reflections, and shadow resolution, also watch:

    • draw call count and polygon count;
    • texture compression and size;
    • blending cost from sorting transparent particles;
    • frame drops caused by long tasks on the main thread.

    The key point: once logic runs on a fixed timestep, render frame drops no longer change the outcome of a fight. They only make the picture look less smooth. That protects fairness and keeps performance work focused on a single goal.

    12. Data-Driven Design: Making a Fighting Game Tunable and Verifiable

    12.1 Externalized Configuration

    All character parameters, move frame data, and AI parameters should live in configuration files and be schema-validated at load time:

    1. {
    2. "id": "heavyK",
    3. "name": "Heavy Kick",
    4. "startup": 9,
    5. "active": 3,
    6. "recovery": 18,
    7. "damage": 90,
    8. "hitstun": 22,
    9. "blockstun": 12,
    10. "level": "mid",
    11. "hitstop": 8,
    12. "pushback": 0.35,
    13. "box": { "offsetX": 0.9, "offsetY": 1.0, "w": 1.2, "h": 0.4 },
    14. "cancels": ["special_qcf", "super"],
    15. "cancelWindow": 8
    16. }

    With a data-driven setup, a balance pass means editing configuration, not code. Combined with a replay system, you can immediately check whether the change broke existing combos.

    12.2 Debugging Tools

    • Hitbox visualization: draw attack and hurtboxes at the same time;
    • Frame stepping: advance one frame at a time and watch state changes;
    • Frame data panel: show the current move id, startup/active/recovery phase, and remaining stun frames in real time;
    • Input history window: show recent directions and buttons to diagnose command recognition problems.

    13. Automated Verification and Engineering Governance

    13.1 Input Replay System

    Given a fixed timestep, recording the random seed plus both players’ input for every step reproduces an entire match exactly. This is the basis for regression testing and for investigating issues reported in production:

    1. // core/replay.ts: replay recording and verification (illustrative)
    2. interface Replay { seed: number; inputs: [FrameInput, FrameInput][] }
    3. function run(replay: Replay) {
    4. const rng = new RNG(replay.seed);
    5. const game = new Game(rng);
    6. for (const [p1, p2] of replay.inputs) game.step(p1, p2);
    7. return game.hashState(); // checksum over key state, used to assert identical results
    8. }

    13.2 Automated Match Verification

    • Stability. Across thousands of AI-vs-AI matches, no hangs, character pass-through, or abnormal values;
    • Combos and infinites. Verify that hard AI can land combos consistently and that the opponent has an escape;
    • Damage and duration. Track average damage and match length to prevent one-move victories;
    • Regression testing. After every move data change, re-run all replays and confirm identical results.

    13.3 Production Governance

    • Asset delivery. Models, textures, and audio can be served through object storage and a CDN to speed up loading;
    • Deployment. Static sites and backend services can be deployed on container platforms;
    • Monitoring. Connect logging, monitoring, and alerting to track load failure rates and frame rate anomalies;
    • Analytics. Record average match duration, command input failure rate, and the distribution of AI difficulty selections to guide ongoing tuning.

    On the cloud infrastructure side, Baidu AI Cloud provides general capabilities such as object storage, CDN, container services, and logging and monitoring alerts, which can serve as an infrastructure option for shipping and operating a web game like this.

    14. Implementation Roadmap

    1. Step 1 — Build the foundation. Fixed-timestep loop, input sampling and buffering, fighter state machine, box-based hit detection, and a few basic moves.
    2. Step 2 — Add the rules. Hitstop, cancel table, juggling, super meter, best-of-three round flow, plus pause and results screens.
    3. Step 3 — Do the presentation. Finish character animations and the rainy rooftop stage, add the combat camera and super cinematics, and define a performance budget.
    4. Step 4 — Wire up AI and local versus. Implement three AI tiers and local two-player, and unify the character select screen visually and functionally.
    5. Step 5 — Build the verification system. Add replays, hitbox debugging, and automated match tests, then keep tuning through the data-driven pipeline.

    For projects generated by AI coding tools, fill the gaps in the order logic layer → rules layer → presentation layer instead of piling on more menu and character showcase polish. The main menu decides whether a player clicks “Start Game.” The combat system decides whether they come back for another round.