Back to Find the Invisible Cow
SOURCE / PINNED RELEASE

Made of little things.

Find the Invisible Cow

Release
e48b3dced31c…
Author-recorded commit
cf79302f143d…
License
LICENSE
Author’s source reference
nostr://npub1p8rxwea4e0l4jml0q53n5mvh3n7pywq523jk3lm336v04r8ny9jqtq7ttf/wss%3A%2F%2Fgit.napplet.soy%2F/n-3b179f1d7df

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

src/main.ts
import './napplet-settings.js';
import {
  IDENTITY_DOMAIN,
  STORAGE_DOMAIN,
  identity,
  media,
  storage,
  type Subscription,
} from '@napplet/sdk';
import { runtimeHasDomain } from './domain-availability.js';
import { CoordinatedAudio, type AudioMediaClient } from './coordinated-audio.js';
import { MooSynth } from './moo.js';
import { createGamepadInput } from './gamepad.js';
import { getSettings, initSettings, onSettingsChange } from './napplet-settings.js';
import {
  catchRadiusFor,
  formatTime,
  intervalFor,
  proximityFor,
  spotDescription,
  volumeFor,
} from './rules.js';
import './styles.css';

/* ---------- Elements ---------- */

const field = requireElement<HTMLDivElement>('#field');
const probe = requireElement<HTMLDivElement>('#probe');
const hintMeterWrap = requireElement<HTMLDivElement>('#hintMeterWrap');
const hintMeter = requireElement<HTMLDivElement>('#hintMeter');
const hintArrow = requireElement<SVGSVGElement>('#hintArrow');
const cowReveal = requireElement<HTMLDivElement>('#cowReveal');
const timerLabel = requireElement<HTMLElement>('#timer');
const mooLabel = requireElement<HTMLElement>('#mooCount');
const soundToggle = requireElement<HTMLButtonElement>('#soundToggle');
const coach = requireElement<HTMLParagraphElement>('#coach');
const notice = requireElement<HTMLParagraphElement>('#notice');
const startOverlay = requireElement<HTMLDivElement>('#startOverlay');
const startButton = requireElement<HTMLButtonElement>('#startButton');
const winOverlay = requireElement<HTMLDivElement>('#winOverlay');
const againButton = requireElement<HTMLButtonElement>('#againButton');
const resultTime = requireElement<HTMLElement>('#resultTime');
const resultMoos = requireElement<HTMLElement>('#resultMoos');
const resultBest = requireElement<HTMLElement>('#resultBest');
const resultSpot = requireElement<HTMLElement>('#resultSpot');

function requireElement<T extends Element>(selector: string): T {
  const element = document.querySelector<T>(selector);
  if (!element) {
    throw new Error(`Missing required element: ${selector}`);
  }
  return element;
}

/* ---------- Audio (NAP-MEDIA, one napplet-owned session) ---------- */

const audio = new CoordinatedAudio(
  media as unknown as AudioMediaClient | undefined,
  'Invisible Cow moo',
  { onChange: () => syncSoundButton() },
);
let mooSynth: MooSynth | null = null;
let audioBlocked = false;

function ensureSynth(): MooSynth | null {
  if (!audio.context || !audio.output) return null;
  if (!mooSynth) mooSynth = new MooSynth(audio.context, audio.output);
  return mooSynth;
}

/** Call from a user gesture only. */
function tryActivateAudio(): void {
  audio.activate();
  // The session handshake is asynchronous; settle before deciding the host
  // cannot play sound at all, so the game can fall back to visual hints.
  window.setTimeout(() => {
    if (
      !audio.audible &&
      (audio.unavailable || !audio.hasMedia) &&
      !audioBlocked
    ) {
      audioBlocked = true;
      showNotice('Audio is unavailable here — visual hints are on so you can still hunt.', 8000);
    }
  }, 2000);
}

function syncSoundButton(): void {
  const pressed = !audio.muted;
  soundToggle.setAttribute('aria-pressed', String(pressed));
  soundToggle.setAttribute(
    'aria-label',
    pressed ? 'Sound is on. Turn sound off.' : 'Sound is off. Turn sound on.',
  );
}

soundToggle.addEventListener('click', () => {
  if (audio.muted) {
    audio.setMuted(false);
    if (audio.unavailable) {
      audio.reset();
      tryActivateAudio();
    } else {
      audio.activate();
    }
  } else {
    audio.setMuted(true);
  }
  syncSoundButton();
});

/* ---------- Game state ---------- */

type GameState = 'idle' | 'hunting' | 'found';

let state: GameState = 'idle';
let cow = { fx: 0.5, fy: 0.5 };
let pos = { x: 0, y: 0 }; // Listening position in field pixels (pointer or probe).
const keyDir = new Set<string>();
let padVec = { x: 0, y: 0 };
let inputMode: 'pointer' | 'keys' | 'pad' = 'pointer';
let mooTimer = 0;
let mooCount = 0;
let elapsedBase = 0;
let runningSince: number | null = null;
let bestTimeMs: number | null = null;
let storedBest = false;
let lastFrame = 0;

const KEY_SPEED = 430; // Probe speed for keyboard/gamepad, px per second.

function fieldSize(): { w: number; h: number } {
  const rect = field.getBoundingClientRect();
  return { w: rect.width, h: rect.height };
}

function cowPosition(): { x: number; y: number } {
  const { w, h } = fieldSize();
  return { x: cow.fx * w, y: cow.fy * h };
}

function catchRadius(): number {
  const { w, h } = fieldSize();
  return catchRadiusFor(w, h, getSettings().catchSize);
}

function proximity(): number {
  const { w, h } = fieldSize();
  const c = cowPosition();
  const ref = Math.hypot(w, h) / 2 || 1;
  return proximityFor(Math.hypot(c.x - pos.x, c.y - pos.y), ref);
}

function placeCow(): void {
  const { w, h } = fieldSize();
  const ref = Math.hypot(w, h) / 2 || 1;
  for (let attempt = 0; attempt < 12; attempt += 1) {
    const fx = 0.06 + Math.random() * 0.88;
    const fy = 0.1 + Math.random() * 0.8;
    const dx = (fx - pos.x / w) * w;
    const dy = (fy - pos.y / h) * h;
    if (Math.hypot(dx, dy) > ref * 0.45 || attempt === 11) {
      cow = { fx, fy };
      return;
    }
  }
}

function intervalForWithJitter(p: number): number {
  return intervalFor(p) * (0.88 + Math.random() * 0.24);
}

function playMoo(): void {
  if (state !== 'hunting') return;
  const p = proximity();
  if (audio.audible) {
    const synth = ensureSynth();
    if (synth) {
      const { w } = fieldSize();
      const c = cowPosition();
      const pan = Math.max(-1, Math.min(1, ((pos.x - c.x) / w) * 2));
      synth.play({
        volume: volumeFor(p),
        pan,
        pitch: 150 * (0.9 + Math.random() * 0.2),
      });
      mooCount += 1;
      mooLabel.textContent = `${mooCount} moo${mooCount === 1 ? '' : 's'}`;
    }
  }
  updateHints(p);
}

function scheduleMoo(): void {
  mooTimer = window.setTimeout(() => {
    playMoo();
    scheduleMoo();
  }, intervalForWithJitter(proximity()));
}

function stopMooLoop(): void {
  window.clearTimeout(mooTimer);
  mooTimer = 0;
}

/* ---------- Timer ---------- */

function startTimer(): void {
  elapsedBase = 0;
  runningSince = performance.now();
}

function freezeTimer(): number {
  if (runningSince !== null) {
    elapsedBase += performance.now() - runningSince;
    runningSince = null;
  }
  return elapsedBase;
}

function resumeTimer(): void {
  if (state === 'hunting' && runningSince === null) {
    runningSince = performance.now();
  }
}

function elapsedMs(): number {
  return elapsedBase + (runningSince !== null ? performance.now() - runningSince : 0);
}

/* ---------- Notices ---------- */

let noticeTimer = 0;

function showNotice(message: string, timeoutMs = 5000): void {
  notice.textContent = message;
  notice.hidden = false;
  window.clearTimeout(noticeTimer);
  if (timeoutMs > 0) {
    noticeTimer = window.setTimeout(() => {
      notice.hidden = true;
    }, timeoutMs);
  }
}

/* ---------- Best time (optional NAP-STORAGE) ---------- */

async function loadBestTime(): Promise<void> {
  if (!runtimeHasDomain(STORAGE_DOMAIN)) return;
  try {
    const raw = await storage.getItem('best-time-ms');
    const parsed = raw === null ? Number.NaN : Number(raw);
    if (Number.isFinite(parsed) && parsed > 0) {
      bestTimeMs = parsed;
      storedBest = true;
    }
  } catch {
    // Optional saves are best-effort; the game works without them.
  }
}

async function saveBestTime(ms: number): Promise<void> {
  if (!runtimeHasDomain(STORAGE_DOMAIN)) {
    if (!storedBest) showNotice('Best time not saved — this host has no storage.', 4000);
    return;
  }
  try {
    await storage.setItem('best-time-ms', String(ms));
    storedBest = true;
  } catch {
    showNotice('Best time not saved — storage refused the write.', 4000);
  }
}

/* ---------- Catching and rounds ---------- */

function attemptCatch(): void {
  if (state !== 'hunting') return;
  const c = cowPosition();
  if (Math.hypot(c.x - pos.x, c.y - pos.y) <= catchRadius()) {
    win();
  }
}

function win(): void {
  state = 'found';
  stopMooLoop();
  const ms = freezeTimer();
  if (mooSynth && audio.audible) mooSynth.fanfare();

  const c = cowPosition();
  cowReveal.style.left = `${c.x}px`;
  cowReveal.style.top = `${c.y}px`;
  cowReveal.hidden = false;

  const isBest = bestTimeMs === null || ms < bestTimeMs;
  if (isBest) bestTimeMs = ms;
  resultTime.textContent = formatTime(ms);
  resultMoos.textContent = String(mooCount);
  resultBest.textContent = bestTimeMs === null ? '—' : formatTime(bestTimeMs);
  resultSpot.textContent = spotDescription(cow.fx, cow.fy) + (isBest ? ' A new best!' : '');
  void saveBestTime(ms);

  coach.textContent = 'Got her! Listen for the next hiding spot.';
  window.setTimeout(() => {
    winOverlay.hidden = false;
    againButton.focus();
  }, 850);
}

function startRound(): void {
  startOverlay.hidden = true;
  winOverlay.hidden = true;
  cowReveal.hidden = true;
  mooCount = 0;
  mooLabel.textContent = '0 moos';
  placeCow();
  state = 'hunting';
  coach.textContent = 'Listen — the moo gets louder and quicker as you close in.';
  startTimer();
  resumeTimer();
  stopMooLoop();
  scheduleMoo();
  field.focus({ preventScroll: true });
}

startButton.addEventListener('click', () => {
  tryActivateAudio();
  startRound();
});

againButton.addEventListener('click', () => {
  startRound();
});

/* ---------- Pointer input ---------- */

function fieldPoint(event: PointerEvent): { x: number; y: number } {
  const rect = field.getBoundingClientRect();
  return { x: event.clientX - rect.left, y: event.clientY - rect.top };
}

field.addEventListener('pointermove', (event) => {
  const point = fieldPoint(event);
  pos = point;
  inputMode = 'pointer';
  probe.classList.remove('active');
});

field.addEventListener('pointerdown', (event) => {
  const point = fieldPoint(event);
  pos = point;
  inputMode = 'pointer';
  probe.classList.remove('active');
  attemptCatch();
});

/* ---------- Keyboard input ---------- */

const MOVE_KEYS = new Set([
  'ArrowUp',
  'ArrowDown',
  'ArrowLeft',
  'ArrowRight',
  'w',
  'a',
  's',
  'd',
  'W',
  'A',
  'S',
  'D',
]);

window.addEventListener('keydown', (event) => {
  const target = event.target as HTMLElement | null;
  if (target?.closest('button, input, textarea, select')) return;
  if (MOVE_KEYS.has(event.key)) {
    event.preventDefault();
    keyDir.add(event.key.toLowerCase());
    inputMode = 'keys';
    probe.classList.add('active');
    return;
  }
  if ((event.key === 'Enter' || event.key === ' ') && state === 'hunting') {
    event.preventDefault();
    attemptCatch();
  }
});

window.addEventListener('keyup', (event) => {
  if (MOVE_KEYS.has(event.key)) keyDir.delete(event.key.toLowerCase());
});

window.addEventListener('blur', () => keyDir.clear());

/* ---------- Gamepad input (optional NAP-GAMEPAD shim) ---------- */

const gamepad = createGamepadInput();

function pollGamepad(): void {
  const frame = gamepad.poll();
  const player = frame.players[0];
  if (!player) return;
  const x = player.actions.moveX?.value ?? 0;
  const y = player.actions.moveY?.value ?? 0;
  if (x !== 0 || y !== 0) {
    padVec = { x, y };
    inputMode = 'pad';
    probe.classList.add('active');
  } else if (inputMode === 'pad') {
    padVec = { x: 0, y: 0 };
  }
  if (player.actions.catch?.pressed) attemptCatch();
}

/* ---------- Main loop ---------- */

function clampPos(): void {
  const { w, h } = fieldSize();
  pos.x = Math.max(0, Math.min(w, pos.x));
  pos.y = Math.max(0, Math.min(h, pos.y));
}

function effectiveHintMode(): 'off' | 'subtle' | 'full' {
  const mode = getSettings().hintMode;
  if (mode !== 'off') return mode;
  // Graceful degradation: without working sound the hunt needs some guidance.
  return audioBlocked ? 'subtle' : 'off';
}

function updateHints(p: number): void {
  const hunting = state === 'hunting';
  const mode = effectiveHintMode();
  const meterOn = hunting && mode !== 'off' && (mode === 'full' || p >= 0.7);
  hintMeterWrap.classList.toggle('on', meterOn);
  hintMeter.style.width = `${Math.round(p * 100)}%`;
  const arrowOn = hunting && mode === 'full';
  hintArrow.classList.toggle('on', arrowOn);
  if (arrowOn) {
    const c = cowPosition();
    const angle = Math.atan2(c.y - pos.y, c.x - pos.x) + Math.PI / 2;
    hintArrow.style.transform = `rotate(${(angle * 180) / Math.PI}deg)`;
    hintArrow.style.opacity = String(0.25 + 0.75 * p);
  }
}

function tick(now: number): void {
  const dt = lastFrame ? Math.min(0.1, (now - lastFrame) / 1000) : 0;
  lastFrame = now;

  pollGamepad();

  if (inputMode === 'keys' || inputMode === 'pad') {
    let dx = 0;
    let dy = 0;
    if (inputMode === 'keys') {
      if (keyDir.has('arrowleft') || keyDir.has('a')) dx -= 1;
      if (keyDir.has('arrowright') || keyDir.has('d')) dx += 1;
      if (keyDir.has('arrowup') || keyDir.has('w')) dy -= 1;
      if (keyDir.has('arrowdown') || keyDir.has('s')) dy += 1;
    } else {
      dx = padVec.x;
      dy = padVec.y;
    }
    const length = Math.hypot(dx, dy);
    if (length > 0) {
      pos.x += (dx / Math.max(1, length)) * KEY_SPEED * dt;
      pos.y += (dy / Math.max(1, length)) * KEY_SPEED * dt;
      clampPos();
    }
  }

  if (inputMode !== 'pointer') {
    probe.style.left = `${pos.x}px`;
    probe.style.top = `${pos.y}px`;
  }

  if (state === 'hunting') {
    // A host pause silences the moo, so the clock freezes with it; ordinary
    // game input must not override the pause (CoordinatedAudio holds it).
    if (audio.hostPaused) freezeTimer();
    else resumeTimer();
    timerLabel.textContent = formatTime(elapsedMs());
    updateHints(proximity());
  }

  window.requestAnimationFrame(tick);
}

window.requestAnimationFrame(tick);

/* ---------- Resize, visibility and identity ---------- */

window.addEventListener('resize', () => {
  clampPos();
  if (state === 'hunting') updateHints(proximity());
});

document.addEventListener('visibilitychange', () => {
  if (document.hidden) {
    freezeTimer();
    keyDir.clear();
  } else {
    resumeTimer();
  }
});

let identitySubscription: Subscription | null = null;
if (runtimeHasDomain(IDENTITY_DOMAIN)) {
  try {
    // Sessions are scoped per account; suspend on identity change instead of
    // letting ordinary input fight a retired session. A sound-button press
    // (a fresh gesture) resumes playback.
    identitySubscription = identity.onChanged(() => {
      if (audio.audible && state === 'hunting') {
        audio.setMuted(true);
        showNotice('Account changed — sound paused. Press the sound button to resume.', 6000);
      }
    });
  } catch {
    identitySubscription = null;
  }
}

/* ---------- Settings ---------- */

initSettings();
onSettingsChange(() => {
  if (state === 'hunting') updateHints(proximity());
});

/* ---------- Boot and teardown ---------- */

pos = {
  x: fieldSize().w / 2,
  y: fieldSize().h / 2,
};
syncSoundButton();
void loadBestTime();

window.addEventListener('pagehide', () => {
  stopMooLoop();
  gamepad.dispose();
  identitySubscription?.close();
  audio.dispose();
});