Back to Arañas Pistoleras
SOURCE / PINNED RELEASE

Made of little things.

Arañas Pistoleras

Release
2578a037ceaf…
Author-recorded commit
e35cc0733a7b…
License
LICENSE
Author’s source reference
nostr://npub1eg5pfnws6tg6rtp33tugpppqtv5u05crmf983qp438cdycwzngys0gxzcs/wss%3A%2F%2Fgit.napplet.soy%2F/n-7bf0a402584

Archive hash verified: 52cdda8c063eaf88…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/game.ts
// The rules of Arañas Pistoleras. Nothing here touches the DOM, so the same
// code drives the headless balance test. Positions are in world units: the
// view always has an area of one million units, whatever its shape.

export interface View {
  w: number;
  h: number;
}

export type Kind = 'widow' | 'hat' | 'mini' | 'boss';
export type Mode = 'drop' | 'peek' | 'crawl';
export type Phase = 'intro' | 'waves' | 'bossIntro' | 'boss' | 'outro' | 'won' | 'lost';
export type SpiderState = 'enter' | 'lurk' | 'aim' | 'fire' | 'stun' | 'move' | 'leave';

/** A place a spider can appear, given by the scene. */
export interface Spot {
  mode: Mode;
  /** Where the spider sits while it aims. For a peek upwards, y follows from the edge. */
  x: number;
  y: number;
  /** Peek: which way the spider comes out from behind the edge. */
  dir?: 'up' | 'left' | 'right';
  /** Peek: the line the spider hides behind (y for up, x for left and right). */
  edge?: number;
  /** Crawl: the side it walks in from. */
  from?: -1 | 1;
}

export interface Spider {
  id: number;
  kind: Kind;
  mode: Mode;
  /** Index into the scene's spots, −1 for the queen. */
  spot: number;
  state: SpiderState;
  /** Seconds in this state, and how long the state lasts. */
  t: number;
  dur: number;
  hp: number;
  maxHp: number;
  hat: boolean;
  /** Shots it still wants to take before it runs away. */
  shots: number;
  x: number;
  y: number;
  scale: number;
  age: number;
  /** A fixed random number per spider, for sway and blinking. */
  seed: number;
  /** Seconds of white flash left after a hit. */
  flinch: number;
  /** Seconds since its last shot, for the muzzle flash. */
  sinceShot: number;
  /** Hits taken during the current aim (the queen gets dizzy after three). */
  aimHits: number;
  fromX: number;
  fromY: number;
  toX: number;
  toY: number;
  /** Peek spiders: 0 hidden to 1 fully out, for clipping and hit tests. */
  out: number;
}

export interface Pickup {
  id: number;
  x: number;
  y: number;
  t: number;
  life: number;
  seed: number;
}

export type GameEvent =
  | { type: 'spawn'; s: Spider }
  | { type: 'aim'; s: Spider }
  | { type: 'fire'; s: Spider; hurt: boolean }
  | { type: 'hit'; s: Spider; x: number; y: number }
  | { type: 'hatOff'; s: Spider }
  | { type: 'die'; s: Spider; combo: number }
  | { type: 'leave'; s: Spider }
  | { type: 'miss'; x: number; y: number }
  | { type: 'heart'; p: Pickup }
  | { type: 'heal'; p: Pickup }
  | { type: 'bossIntro' }
  | { type: 'bossStun'; s: Spider }
  | { type: 'bossSummon'; s: Spider }
  | { type: 'bossDie'; s: Spider }
  | { type: 'win'; stars: number }
  | { type: 'lose' };

export interface LevelDef {
  id: 'colegio' | 'cocina' | 'dormitorio' | 'bodega' | 'bosque';
  name: string;
  /** Spiders to beat before the queen comes. */
  quota: number;
  /** Spiders at once, at the start and at the end of the level. */
  alive: [number, number];
  /** Seconds between two spiders appearing. */
  gap: [number, number];
  /** Seconds a spider aims before it shoots. */
  aim: [number, number];
  /** Share of spiders with a hat (two hits) and of little fast ones. */
  hats: number;
  minis: number;
  /** Shots a spider takes before it runs away. */
  shots: number;
  bossHp: number;
  bossAim: number;
}

export const LEVELS: LevelDef[] = [
  { id: 'colegio', name: 'El Colegio', quota: 12, alive: [1, 2], gap: [2.2, 1.7], aim: [3.4, 2.9], hats: 0, minis: 0, shots: 1, bossHp: 8, bossAim: 3.4 },
  { id: 'cocina', name: 'La Cocina', quota: 15, alive: [2, 2], gap: [2.0, 1.6], aim: [3.2, 2.8], hats: 0.28, minis: 0, shots: 1, bossHp: 10, bossAim: 3.2 },
  { id: 'dormitorio', name: 'El Dormitorio', quota: 18, alive: [2, 3], gap: [1.9, 1.5], aim: [3.1, 2.7], hats: 0.25, minis: 0.2, shots: 2, bossHp: 12, bossAim: 3.0 },
  { id: 'bodega', name: 'La Bodega', quota: 21, alive: [2, 3], gap: [1.8, 1.4], aim: [3.0, 2.6], hats: 0.28, minis: 0.24, shots: 2, bossHp: 14, bossAim: 2.9 },
  { id: 'bosque', name: 'El Bosque de Noche', quota: 25, alive: [2, 3], gap: [1.7, 1.25], aim: [2.9, 2.4], hats: 0.3, minis: 0.28, shots: 2, bossHp: 18, bossAim: 2.8 },
];

export const MAX_HEARTS = 5;
/** After a shot lands no other spider may shoot for this long. */
const SHOT_LOCK = 1.0;

export function rngFrom(seed: number): () => number {
  let s = seed >>> 0;
  return () => {
    s = (s + 0x6d2b79f5) >>> 0;
    let t = s;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

function lerp(a: number, b: number, t: number): number {
  return a + (b - a) * t;
}

function clamp(v: number, lo: number, hi: number): number {
  return Math.max(lo, Math.min(hi, v));
}

function easeOutBack(p: number): number {
  const c = 1.4;
  const q = p - 1;
  return 1 + (c + 1) * q * q * q + c * q * q;
}

function easeInOut(p: number): number {
  return p < 0.5 ? 2 * p * p : 1 - Math.pow(-2 * p + 2, 2) / 2;
}

/** How large a kind is drawn; hit circles follow from it. */
export function kindScale(kind: Kind, view: View): number {
  if (kind === 'mini') return 0.58;
  if (kind === 'hat') return 1.12;
  if (kind === 'boss') return Math.min(1.8, view.w / 460, view.h / 420);
  return 1;
}

export function hitRadius(s: Spider): number {
  return 74 * s.scale + 26;
}

export class Game {
  readonly def: LevelDef;
  phase: Phase = 'intro';
  /** Seconds in the current phase. */
  phaseT = 0;
  time = 0;
  hearts = MAX_HEARTS;
  heartsLost = 0;
  kills = 0;
  escaped = 0;
  spiders: Spider[] = [];
  pickups: Pickup[] = [];
  events: GameEvent[] = [];
  boss: Spider | null = null;
  view: View = { w: 1265, h: 790 };
  spots: Spot[] = [];
  floorY = 540;
  /** Kills in quick succession, for the rising note. */
  combo = 0;
  private comboT = 0;
  private rng: () => number;
  private nextId = 1;
  /** The first spider comes as the name of the place fades. */
  private spawnT = 0.2;
  private shotLock = 0;
  private summoned = 0;
  private lastSpot = -1;

  readonly level: number;
  /** Lost attempts in a row on this level; each one makes the spiders slower. */
  readonly mercy: number;

  constructor(level: number, mercy = 0, seed = 1) {
    this.level = level;
    this.mercy = mercy;
    this.def = LEVELS[level];
    this.rng = rngFrom(seed * 7919 + level * 104729 + 17);
  }

  setStage(view: View, spots: Spot[], floorY: number): void {
    this.view = view;
    this.spots = spots;
    this.floorY = floorY;
    for (const s of this.spiders) this.place(s);
  }

  /** 0 at the start of the level to 1 when the queen is due. */
  get progress(): number {
    return clamp(this.kills / this.def.quota, 0, 1);
  }

  get stars(): number {
    return this.heartsLost <= 1 ? 3 : this.heartsLost <= 3 ? 2 : 1;
  }

  private get slow(): number {
    return 1 + 0.25 * Math.min(this.mercy, 4);
  }

  private setPhase(p: Phase): void {
    this.phase = p;
    this.phaseT = 0;
  }

  update(dt: number): void {
    this.time += dt;
    this.phaseT += dt;
    this.shotLock = Math.max(0, this.shotLock - dt);
    this.comboT -= dt;
    if (this.comboT <= 0) this.combo = 0;

    switch (this.phase) {
      case 'intro':
        if (this.phaseT > 1.9) this.setPhase('waves');
        break;
      case 'waves':
        this.runWaves(dt);
        break;
      case 'bossIntro':
        if (!this.boss && this.phaseT > 1.0) this.spawnBoss();
        if (this.phaseT > 2.6) this.setPhase('boss');
        break;
      case 'boss':
        break;
      case 'outro':
        if (this.phaseT > 2.6) {
          this.setPhase('won');
          this.events.push({ type: 'win', stars: this.stars });
        }
        break;
      default:
        break;
    }

    for (let i = this.spiders.length - 1; i >= 0; i--) {
      const s = this.spiders[i];
      this.stepSpider(s, dt);
      if (s.state === 'leave' && s.t >= s.dur) {
        this.spiders.splice(i, 1);
        if (s.kind !== 'boss') this.escaped++;
      }
    }

    for (let i = this.pickups.length - 1; i >= 0; i--) {
      const p = this.pickups[i];
      p.t += dt;
      p.y -= 30 * dt;
      if (p.t > p.life) this.pickups.splice(i, 1);
    }
  }

  private runWaves(dt: number): void {
    const d = this.def;
    const staying = this.spiders.filter((s) => s.state !== 'leave').length;
    if (this.kills >= d.quota) {
      for (const s of this.spiders) if (s.state !== 'leave' && s.state !== 'fire') this.flee(s);
      if (this.spiders.length === 0) {
        this.setPhase('bossIntro');
        this.events.push({ type: 'bossIntro' });
      }
      return;
    }
    const q = this.progress;
    const maxAlive = Math.max(1, Math.round(lerp(d.alive[0], d.alive[1], q)) - Math.floor((Math.min(this.mercy, 4) + 1) / 2));
    this.spawnT -= dt;
    if (this.spawnT <= 0 && staying < maxAlive && this.kills + staying < d.quota) {
      if (this.spawn()) this.spawnT = lerp(d.gap[0], d.gap[1], q) * (0.8 + this.rng() * 0.4);
      else this.spawnT = 0.3;
    }
  }

  private pickKind(): Kind {
    const d = this.def;
    // The first three of the first level are plain, so the idea is clear.
    if (this.kills + this.spiders.length < 2 && this.level === 0) return 'widow';
    const r = this.rng();
    if (r < d.minis) return 'mini';
    if (r < d.minis + d.hats) return 'hat';
    return 'widow';
  }

  private freeSpot(kind: Kind): number {
    const scale = kindScale(kind, this.view);
    const free: number[] = [];
    this.spots.forEach((spot, i) => {
      if (i === this.lastSpot) return;
      if (kind === 'mini' && spot.mode === 'peek') return;
      const home = this.homeOf(spot, scale);
      for (const s of this.spiders) {
        const other = s.spot >= 0 ? this.homeOf(this.spots[s.spot], s.scale) : { x: s.toX, y: s.toY };
        if (s.spot === i) return;
        const reach = 115 * (scale + s.scale);
        if (Math.hypot(home.x - other.x, home.y - other.y) < reach) return;
      }
      free.push(i);
    });
    if (!free.length) return -1;
    return free[Math.floor(this.rng() * free.length)];
  }

  private spawn(kind: Kind = this.pickKind()): Spider | null {
    const i = this.freeSpot(kind);
    if (i < 0) return null;
    this.lastSpot = i;
    const spot = this.spots[i];
    const scale = kindScale(kind, this.view);
    const s: Spider = {
      id: this.nextId++,
      kind,
      mode: spot.mode,
      spot: i,
      state: 'enter',
      t: 0,
      dur: spot.mode === 'drop' ? 1.05 : spot.mode === 'crawl' ? (kind === 'mini' ? 0.75 : 1.1) : 0.8,
      hp: kind === 'hat' ? 2 : 1,
      maxHp: kind === 'hat' ? 2 : 1,
      hat: kind === 'hat',
      shots: this.def.shots,
      x: 0,
      y: 0,
      scale,
      age: 0,
      seed: this.rng(),
      flinch: 0,
      sinceShot: 9,
      aimHits: 0,
      fromX: 0,
      fromY: 0,
      toX: 0,
      toY: 0,
      out: 0,
    };
    this.place(s);
    this.spiders.push(s);
    this.events.push({ type: 'spawn', s });
    return s;
  }

  private spawnBoss(): void {
    const v = this.view;
    const scale = kindScale('boss', v);
    const home = this.bossAnchor(1);
    const s: Spider = {
      id: this.nextId++,
      kind: 'boss',
      mode: 'drop',
      spot: -1,
      state: 'enter',
      t: 0,
      dur: 1.5,
      hp: this.def.bossHp,
      maxHp: this.def.bossHp,
      hat: false,
      shots: 1e9,
      x: home.x,
      y: -260 * scale,
      scale,
      age: 0,
      seed: this.rng(),
      flinch: 0,
      sinceShot: 9,
      aimHits: 0,
      fromX: home.x,
      fromY: -260 * scale,
      toX: home.x,
      toY: home.y,
      out: 1,
    };
    this.boss = s;
    this.spiders.push(s);
    this.events.push({ type: 'spawn', s });
  }

  private bossAnchor(i: number): { x: number; y: number } {
    const v = this.view;
    const scale = kindScale('boss', v);
    const margin = Math.min(v.w * 0.3, 170 * scale);
    const x = lerp(margin, v.w - margin, i / 2);
    const y = clamp(v.h * (i === 1 ? 0.4 : 0.34), 150 * scale, this.floorY - 40);
    return { x, y };
  }

  /** Where a spider of this size sits at a spot once it is fully out. */
  private homeOf(spot: Spot, scale: number): { x: number; y: number } {
    if (spot.mode === 'peek') {
      const edge = spot.edge ?? spot.y;
      if (spot.dir === 'left') return { x: edge - 70 * scale, y: spot.y };
      if (spot.dir === 'right') return { x: edge + 70 * scale, y: spot.y };
      // High enough that the pistols clear the edge when they come down.
      return { x: spot.x, y: edge - 94 * scale };
    }
    return { x: spot.x, y: spot.y };
  }

  /** Sets x, y and how far out a spider is from its state. */
  private place(s: Spider): void {
    if (s.spot < 0) {
      const p = clamp(s.t / s.dur, 0, 1);
      if (s.state === 'enter') {
        s.x = s.toX;
        s.y = lerp(s.fromY, s.toY, easeOutBack(p));
      } else if (s.state === 'move') {
        const e = easeInOut(p);
        s.x = lerp(s.fromX, s.toX, e);
        // A swing: lower in the middle of the way.
        s.y = lerp(s.fromY, s.toY, e) + Math.sin(e * Math.PI) * 46 * s.scale;
      } else if (s.state === 'leave') {
        s.x = s.toX;
        s.y = lerp(s.toY, -300 * s.scale, p * p);
      } else {
        s.x = s.toX + Math.sin(s.age * 1.1) * 14;
        s.y = s.toY + Math.sin(s.age * 1.7) * 6;
      }
      s.out = 1;
      return;
    }
    const spot = this.spots[s.spot];
    if (!spot) return;
    const home = this.homeOf(spot, s.scale);
    let p = 1;
    if (s.state === 'enter') p = clamp(s.t / s.dur, 0, 1);
    else if (s.state === 'leave') p = 1 - clamp(s.t / s.dur, 0, 1);
    s.out = p;
    if (spot.mode === 'drop') {
      const e = s.state === 'enter' ? easeOutBack(p) : p * p;
      const sway = Math.sin(s.age * 1.3 + s.seed * 6) * 10 * Math.min(1, home.y / 300);
      s.x = home.x + sway;
      s.y = lerp(-190 * s.scale, home.y, e);
    } else if (spot.mode === 'crawl') {
      const side = spot.from ?? -1;
      const start = side < 0 ? -190 * s.scale : this.view.w + 190 * s.scale;
      s.x = lerp(start, home.x, easeInOut(p));
      s.y = home.y;
    } else {
      const e = s.state === 'enter' ? easeOutBack(p) : p;
      const hide = 250 * s.scale;
      if (spot.dir === 'left') {
        s.x = lerp(home.x + hide, home.x, e);
        s.y = home.y;
      } else if (spot.dir === 'right') {
        s.x = lerp(home.x - hide, home.x, e);
        s.y = home.y;
      } else {
        s.x = home.x;
        s.y = lerp(home.y + hide, home.y, e);
      }
    }
  }

  private aimTime(s: Spider): number {
    if (s.kind === 'boss') return this.def.bossAim * this.slow;
    const d = this.def;
    const base = lerp(d.aim[0], d.aim[1], this.progress);
    return base * this.slow * (s.kind === 'mini' ? 0.9 : 1);
  }

  private enter(s: Spider, state: SpiderState, dur: number): void {
    s.state = state;
    s.t = 0;
    s.dur = dur;
  }

  private flee(s: Spider): void {
    this.enter(s, 'leave', s.kind === 'boss' ? 1.2 : s.mode === 'crawl' ? 0.9 : 0.7);
    this.events.push({ type: 'leave', s });
  }

  private stepSpider(s: Spider, dt: number): void {
    s.age += dt;
    s.t += dt;
    s.flinch = Math.max(0, s.flinch - dt);
    s.sinceShot += dt;
    const over = this.phase === 'lost' || this.phase === 'won' || this.phase === 'outro';
    switch (s.state) {
      case 'enter':
        if (s.t >= s.dur) this.enter(s, 'lurk', 0.55 + this.rng() * 0.35);
        break;
      case 'lurk':
        if (s.t >= s.dur && !over) {
          this.enter(s, 'aim', this.aimTime(s));
          s.aimHits = 0;
          this.events.push({ type: 'aim', s });
        }
        break;
      case 'aim':
        if (over) {
          this.enter(s, 'lurk', 9);
        } else if (s.t >= s.dur) {
          if (this.shotLock > 0) {
            // Hold the aim: two shots never land at once.
            s.t = s.dur;
          } else {
            this.enter(s, 'fire', 0.55);
            s.sinceShot = 0;
            s.shots--;
            this.shotLock = SHOT_LOCK;
            this.hurt();
            this.events.push({ type: 'fire', s, hurt: true });
          }
        }
        break;
      case 'fire':
        if (s.t >= s.dur) {
          if (s.kind === 'boss') this.bossMove(s);
          else if (s.shots > 0 && !over) this.enter(s, 'lurk', 0.7 + this.rng() * 0.3);
          else this.flee(s);
        }
        break;
      case 'stun':
        if (s.t >= s.dur) {
          if (s.kind === 'boss') this.bossMove(s);
          else this.enter(s, 'lurk', 0.35);
        }
        break;
      case 'move':
        if (s.t >= s.dur) this.enter(s, 'lurk', 0.6);
        break;
      default:
        break;
    }
    this.place(s);
  }

  private bossMove(s: Spider): void {
    // Swing to one of the two anchors that are farther away.
    const options = [0, 1, 2]
      .map((i) => this.bossAnchor(i))
      .sort((a, b) => Math.abs(b.x - s.toX) - Math.abs(a.x - s.toX))
      .slice(0, 2);
    const to = options[Math.floor(this.rng() * options.length)];
    s.fromX = s.x;
    s.fromY = s.y;
    s.toX = to.x;
    s.toY = to.y;
    this.enter(s, 'move', 0.95);
  }

  private hurt(): void {
    if (this.phase === 'lost' || this.hearts <= 0) return;
    this.hearts--;
    this.heartsLost++;
    if (this.hearts <= 0) {
      this.setPhase('lost');
      this.events.push({ type: 'lose' });
    }
  }

  /** A click or tap at a world position. True when it hit something. */
  click(x: number, y: number): boolean {
    if (this.phase === 'won' || this.phase === 'lost') return false;
    // Hearts first: they are small and float in front.
    for (let i = this.pickups.length - 1; i >= 0; i--) {
      const p = this.pickups[i];
      if (Math.hypot(x - p.x, y - p.y) < 78) {
        this.pickups.splice(i, 1);
        if (this.hearts < MAX_HEARTS) this.hearts++;
        this.events.push({ type: 'heal', p });
        return true;
      }
    }
    let target: Spider | null = null;
    let bestScore = Infinity;
    for (const s of this.spiders) {
      if (s.state === 'leave' && s.t > s.dur * 0.6) continue;
      if (s.mode === 'peek' && s.out < 0.35) continue;
      const d = Math.hypot(x - s.x, y - s.y);
      const r = hitRadius(s);
      if (d > r) continue;
      // The nearest wins; among overlapping ones the one about to shoot.
      const urgency = s.state === 'aim' ? (s.dur - s.t) * 0.02 : 0.1;
      const score = d / r + urgency;
      if (score < bestScore) {
        bestScore = score;
        target = s;
      }
    }
    if (!target) {
      this.events.push({ type: 'miss', x, y });
      return false;
    }
    this.hit(target, x, y);
    return true;
  }

  private hit(s: Spider, x: number, y: number): void {
    s.hp--;
    s.flinch = 0.14;
    this.events.push({ type: 'hit', s, x, y });
    if (s.kind === 'boss') {
      if (s.hp <= 0) {
        this.killBoss(s);
        return;
      }
      if (s.state === 'aim') {
        s.aimHits++;
        if (s.aimHits >= 3) {
          this.enter(s, 'stun', 1.4);
          this.events.push({ type: 'bossStun', s });
        }
      }
      const third = Math.floor(((s.maxHp - s.hp) * 3) / s.maxHp);
      if (third > this.summoned && third < 3) {
        this.summoned = third;
        this.events.push({ type: 'bossSummon', s });
        const first = this.spawn('mini');
        if (first && this.level >= 2) this.spawn('mini');
        if (this.hearts < MAX_HEARTS) this.dropHeart(s.x, s.y + 60 * s.scale);
      }
      return;
    }
    if (s.hp <= 0) {
      this.kill(s);
      return;
    }
    if (s.hat) {
      s.hat = false;
      this.events.push({ type: 'hatOff', s });
      if (s.state !== 'enter' && s.state !== 'leave') this.enter(s, 'stun', 0.9);
    }
  }

  private kill(s: Spider): void {
    const i = this.spiders.indexOf(s);
    if (i >= 0) this.spiders.splice(i, 1);
    this.combo = this.comboT > 0 ? this.combo + 1 : 0;
    this.comboT = 1.6;
    if (this.phase === 'waves') this.kills++;
    this.events.push({ type: 'die', s, combo: this.combo });
    if (s.kind === 'hat' && this.hearts < MAX_HEARTS && this.pickups.length === 0 && this.rng() < 0.45) {
      this.dropHeart(s.x, s.y);
    }
  }

  private dropHeart(x: number, y: number): void {
    const p: Pickup = {
      id: this.nextId++,
      x: clamp(x, 70, this.view.w - 70),
      y: clamp(y, 200, this.view.h - 60),
      t: 0,
      life: 7,
      seed: this.rng(),
    };
    this.pickups.push(p);
    this.events.push({ type: 'heart', p });
  }

  private killBoss(s: Spider): void {
    const i = this.spiders.indexOf(s);
    if (i >= 0) this.spiders.splice(i, 1);
    this.boss = null;
    this.events.push({ type: 'bossDie', s });
    // Her little ones pop with her.
    for (const m of this.spiders.slice()) {
      this.spiders.splice(this.spiders.indexOf(m), 1);
      this.events.push({ type: 'die', s: m, combo: 0 });
    }
    this.setPhase('outro');
  }
}