import type { WorldState } from "../types.ts"; import { pump } from "./conversation.ts"; import { changed, petEngine } from "./engine.ts"; import { store } from "./store.ts"; import { canRunLocally } from "./hosting.ts"; // The body runs in the shared engine; this module only drives its clock. export const age = () => (store.state.pet ? Date.now() - store.state.pet.hatched : 0); export const dayNum = () => petEngine().dayNum(Date.now()); let weather = { at: 0, value: "" }; /** The local weather, read at most once a second (the LCD draws every frame). */ export function weatherNow() { const now = Date.now(); if (now - weather.at >= 1000) weather = { at: now, value: petEngine().weather(now) }; return weather.value; } export function worldState(): WorldState { const world = petEngine().world(Date.now()); if (!world) throw new Error("An egg has no world state."); return world; } // After an absence the engine catches up quietly (at most a week) and the pet // notices its owner coming back after half an hour. export function catchUp() { if (!canRunLocally()) return; const now = Date.now(); petEngine().advance(now, true); lastSecond = now; changed(); } let lastSecond = Date.now(); /** Restarts the body clock so time spent elsewhere (on a host) is not replayed. */ export function resetSimulationClock() { lastSecond = Date.now(); petEngine().resetClock(lastSecond); } export function tick() { if (!canRunLocally()) return; const now = Date.now(); if (now - lastSecond < 1000) return; lastSecond = now; changed(petEngine().advance(now)); pump(); }