Files
bworld/tests/time_test.ts
T
2026-09-26 11:03:07 -03:00

58 lines
2.7 KiB
TypeScript

import { assert, assertEquals } from "@std/assert";
import { clock, CYCLE_TICKS, DAY_TICKS, daylight, format_clock, is_day, NIGHT_TICKS } from "$/common/time.ts";
import { test_game } from "./helpers.ts";
Deno.test("a day is 30 minutes and a night 10, tick 0 is 06:00 of day 1", () => {
assertEquals(DAY_TICKS, 30 * 60 * 20);
assertEquals(NIGHT_TICKS, 10 * 60 * 20);
assertEquals(format_clock(0), "Day 1, 06:00");
assertEquals(format_clock(DAY_TICKS / 2), "Day 1, 12:00");
assertEquals(format_clock(DAY_TICKS), "Day 1, 18:00");
// midnight is halfway through the night, and the day number goes up there
assertEquals(format_clock(DAY_TICKS + NIGHT_TICKS / 2 - 1), "Day 1, 23:59");
assertEquals(format_clock(DAY_TICKS + NIGHT_TICKS / 2), "Day 2, 00:00");
assertEquals(format_clock(CYCLE_TICKS), "Day 2, 06:00");
assertEquals(clock(3 * CYCLE_TICKS + DAY_TICKS / 4), { day: 4, hour: 9, minute: 0 });
assert(is_day(DAY_TICKS - 1) && !is_day(DAY_TICKS) && is_day(CYCLE_TICKS));
});
Deno.test("it's bright all day, dark in the middle of the night, and fades in between", () => {
assertEquals(daylight(0), 1);
assertEquals(daylight(DAY_TICKS - 1), 1);
assertEquals(daylight(DAY_TICKS + NIGHT_TICKS / 2), 0);
const dusk = daylight(DAY_TICKS + 600);
const dawn = daylight(CYCLE_TICKS - 600);
assert(dusk > 0 && dusk < 1 && Math.abs(dusk - dawn) < 1e-9, `dusk ${dusk}, dawn ${dawn}`);
// smooth between ticks too
assert(daylight(DAY_TICKS + 600.5) < dusk);
});
Deno.test("the server keeps the time, tells players, saves it, and /time changes it", async () => {
const { game, join, take, send } = await test_game("mods");
assertEquals(join(1, "alice").time, 0);
for (let i = 0; i < 40; i++) game.tick();
assertEquals(take(1).filter((m) => m.type === "time").map((m) => m.time), [20, 40]);
send(1, { type: "chat", text: "/time" });
assertEquals(take(1).find((m) => m.type === "chat").text, "Day 1, 06:00 (tick 40)");
send(1, { type: "chat", text: "/time set midnight" });
let messages = take(1);
assertEquals(messages.find((m) => m.type === "time").time, DAY_TICKS + NIGHT_TICKS / 2);
assert(messages.some((m) => m.text === "alice set the time to Day 2, 00:00"));
// named times are the next one, so time never goes backwards
send(1, { type: "chat", text: "/time set day" });
assertEquals(game.world.time, CYCLE_TICKS);
send(1, { type: "chat", text: "/time add 100" });
assertEquals(game.world.time, CYCLE_TICKS + 100);
send(1, { type: "chat", text: "/time set nope" });
messages = take(1);
assert(messages.at(-1).text.startsWith("Usage: /time"));
const loaded = await test_game("mods", game.save());
assertEquals(loaded.game.world.time, CYCLE_TICKS + 100);
assertEquals(loaded.join(1, "alice").time, CYCLE_TICKS + 100);
});