Skip to content
Make the player visible with a procedural 3D humanoid132be7c
JavaScript246 lines8.8 KB
// Pure, deterministic fight simulation. No DOM, no randomness, no side effects.// Coordinates: x along the arena, y = height above the floor (positive = up), vy positive = up.// Usage: let state = createMatch(level); state = step(state, [inputsP1, inputsP2], DT); import { getLevel, LEVELS } from './levels.mjs'; export const DT = 1 / 60; export const CONFIG = Object.freeze({  moveSpeed: 260,  jumpVelocity: 620,  gravity: 1700,  fighterWidth: 56,  fighterHeight: 150,  maxHealth: 100,  maxStamina: 100,  staminaRegen: 18,  blockStaminaDrain: 10,  attacks: Object.freeze({    punch: Object.freeze({ startup: 0.08, active: 0.08, recovery: 0.16, damage: 7, reach: 70, knockback: 90, stamina: 8, hitstun: 0.22 }),    kick: Object.freeze({ startup: 0.15, active: 0.1, recovery: 0.26, damage: 13, reach: 95, knockback: 190, stamina: 15, hitstun: 0.32 })  }),  blockDamageFactor: 0.15,  blockKnockbackFactor: 0.4,  roundEndDelay: 1.5}); export const EMPTY_INPUT = Object.freeze({ left: false, right: false, jump: false, punch: false, kick: false, block: false }); export function createFighter(id, x, facing) {  return {    id, x, y: 0, vx: 0, vy: 0,    facing, // 1 = right, -1 = left    health: CONFIG.maxHealth,    stamina: CONFIG.maxStamina,    stance: 'idle', // idle | walk | jump | punch | kick | block | hit | ko    attack: null, // { type, t, hasHit }    hitstun: 0,    onGround: true,    roundsWon: 0  };} function spawnXs(level) {  const { width, padding } = level.arena;  return [padding + width * 0.25, width - padding - width * 0.25];} export function createMatch(levelRef = 0) {  const level = (typeof levelRef === 'object' && levelRef) ? levelRef : (getLevel(levelRef) ?? LEVELS[0]);  const xs = spawnXs(level);  return {    level, tick: 0, round: 1, roundTime: level.roundTime,    phase: 'fight', // fight | roundover | matchover    phaseTimer: 0, roundWinner: null, winner: null, events: [],    fighters: [createFighter(0, xs[0], 1), createFighter(1, xs[1], -1)]  };} function resetRound(state) {  const xs = spawnXs(state.level);  state.fighters = state.fighters.map((f, i) => ({ ...createFighter(f.id, xs[i], i === 0 ? 1 : -1), roundsWon: f.roundsWon }));  state.roundTime = state.level.roundTime;  state.phase = 'fight';  state.phaseTimer = 0;  state.roundWinner = null;} export function getHurtbox(f) {  return { x: f.x - CONFIG.fighterWidth / 2, y: f.y, w: CONFIG.fighterWidth, h: CONFIG.fighterHeight };} export function getHitbox(f) {  if (!f.attack) return null;  const spec = CONFIG.attacks[f.attack.type];  const t = f.attack.t;  if (t < spec.startup || t >= spec.startup + spec.active) return null;  const w = spec.reach;  const x = f.facing === 1 ? f.x + CONFIG.fighterWidth / 2 : f.x - CONFIG.fighterWidth / 2 - w;  const y = f.y + (f.attack.type === 'punch' ? CONFIG.fighterHeight * 0.55 : CONFIG.fighterHeight * 0.25);  return { x, y, w, h: CONFIG.fighterHeight * 0.35 };} export function rectsOverlap(a, b) {  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;} export function distance(state) {  return Math.abs(state.fighters[0].x - state.fighters[1].x);} function cloneState(state) {  return { ...state, events: [], fighters: state.fighters.map((f) => ({ ...f, attack: f.attack ? { ...f.attack } : null })) };} function stepFighter(f, input, opponent, state, dt) {  const level = state.level;  const g = CONFIG.gravity * level.gravity;  const canAct = f.hitstun <= 0 && f.health > 0;   if (f.attack) {    const spec = CONFIG.attacks[f.attack.type];    f.attack.t += dt;    if (f.attack.t >= spec.startup + spec.active + spec.recovery) f.attack = null;  }  if (f.hitstun > 0) f.hitstun = Math.max(0, f.hitstun - dt);   const busy = !!f.attack;  let stance = f.onGround ? 'idle' : 'jump';   if (canAct && !busy) {    if (input.block && f.onGround) {      stance = 'block';      f.vx = 0;      f.stamina = Math.max(0, f.stamina - CONFIG.blockStaminaDrain * dt);    } else {      const wanted = input.punch ? 'punch' : input.kick ? 'kick' : null;      if (wanted && f.stamina >= CONFIG.attacks[wanted].stamina) {        f.attack = { type: wanted, t: 0, hasHit: false };        f.stamina -= CONFIG.attacks[wanted].stamina;        if (f.onGround) f.vx = 0;        stance = wanted;      } else {        const dir = (input.right ? 1 : 0) - (input.left ? 1 : 0);        if (f.onGround || dir !== 0) f.vx = dir * CONFIG.moveSpeed;        if (dir !== 0) f.facing = dir;        else if (f.onGround) f.facing = opponent.x >= f.x ? 1 : -1;        if (f.onGround && dir !== 0) stance = 'walk';        if (input.jump && f.onGround) {          f.vy = CONFIG.jumpVelocity / Math.sqrt(level.gravity);          f.onGround = false;          stance = 'jump';        }      }    }  } else if (busy) {    stance = f.attack.type;    if (f.onGround) f.vx = 0;  }  if (f.hitstun > 0) stance = 'hit';  if (f.health <= 0) stance = 'ko';   // Integrate  f.x += f.vx * dt;  if (!f.onGround) {    f.vy -= g * dt;    f.y += f.vy * dt;    if (f.y <= 0) { f.y = 0; f.vy = 0; f.onGround = true; if (f.hitstun <= 0) f.vx = 0; }  } else if (f.hitstun > 0 || f.health <= 0) {    f.vx *= 0.85; // slide to a stop while stunned / KO'd    if (Math.abs(f.vx) < 5) f.vx = 0;  }   const { width, padding } = level.arena;  const half = CONFIG.fighterWidth / 2;  f.x = Math.min(width - padding - half, Math.max(padding + half, f.x));   if (stance !== 'block') f.stamina = Math.min(CONFIG.maxStamina, f.stamina + CONFIG.staminaRegen * dt);  f.stance = stance;} function resolveHits(state) {  const [a, b] = state.fighters;  for (const [attacker, defender] of [[a, b], [b, a]]) {    if (!attacker.attack || attacker.attack.hasHit) continue;    const hb = getHitbox(attacker);    if (!hb || !rectsOverlap(hb, getHurtbox(defender))) continue;    attacker.attack.hasHit = true;    const spec = CONFIG.attacks[attacker.attack.type];    const blocked = defender.stance === 'block' && defender.facing !== attacker.facing && defender.health > 0;    const dmg = blocked ? Math.round(spec.damage * CONFIG.blockDamageFactor) : spec.damage;    const kb = blocked ? spec.knockback * CONFIG.blockKnockbackFactor : spec.knockback;    defender.health = Math.max(0, defender.health - dmg);    defender.vx = attacker.facing * kb;    if (!blocked) { defender.hitstun = spec.hitstun; defender.stance = 'hit'; }    if (defender.health <= 0) defender.stance = 'ko';    state.events.push({ type: blocked ? 'block' : 'hit', attacker: attacker.id, defender: defender.id, attack: attacker.attack.type, damage: dmg, x: hb.x + hb.w / 2, y: hb.y + hb.h / 2 });  }  // Keep fighters from overlapping  const minGap = CONFIG.fighterWidth * 0.9;  const d = b.x - a.x;  if (Math.abs(d) < minGap) {    const push = (minGap - Math.abs(d)) / 2;    const sign = d >= 0 ? 1 : -1;    a.x -= push * sign;    b.x += push * sign;  }} function checkRoundEnd(state) {  const [a, b] = state.fighters;  let winner = null;  if (a.health <= 0 && b.health <= 0) winner = -1; // draw  else if (b.health <= 0) winner = 0;  else if (a.health <= 0) winner = 1;  else if (state.roundTime <= 0) winner = a.health === b.health ? -1 : a.health > b.health ? 0 : 1;  if (winner === null) return;  state.phase = 'roundover';  state.phaseTimer = CONFIG.roundEndDelay;  state.roundWinner = winner;  if (winner >= 0) state.fighters[winner].roundsWon += 1;  state.events.push({ type: 'roundover', winner, round: state.round });  const champion = state.fighters.findIndex((f) => f.roundsWon >= state.level.roundsToWin);  if (champion >= 0) {    state.phase = 'matchover';    state.winner = champion;    state.events.push({ type: 'matchover', winner: champion });  }} /** * Advance the simulation by dt seconds. Returns a new state; the given state is not mutated. * @param {object} state match state from createMatch * @param {Array<object>} inputs [inputsP1, inputsP2]; missing flags default to false * @param {number} dt fixed timestep in seconds */export function step(state, inputs = [], dt = DT) {  const s = cloneState(state);  const ins = [{ ...EMPTY_INPUT, ...(inputs[0] || {}) }, { ...EMPTY_INPUT, ...(inputs[1] || {}) }];  s.tick += 1;  if (s.phase === 'matchover') return s;  if (s.phase === 'roundover') {    s.phaseTimer -= dt;    if (s.phaseTimer <= 0) {      s.round += 1;      resetRound(s);      s.events.push({ type: 'roundstart', round: s.round });    }    return s;  }  s.roundTime = Math.max(0, s.roundTime - dt);  const [a, b] = s.fighters;  stepFighter(a, ins[0], b, s, dt);  stepFighter(b, ins[1], a, s, dt);  resolveHits(s);  checkRoundEnd(s);  return s;} /** Run n fixed steps with constant inputs (handy for bots and tests). */export function simulate(state, inputs, steps, dt = DT) {  let s = state;  for (let i = 0; i < steps; i++) s = step(s, inputs, dt);  return s;}