-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add turn, a dungeon-turn tracker #2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| import { | ||
| advance, | ||
| clearState, | ||
| formatElapsed, | ||
| loadState, | ||
| parseTurns, | ||
| saveState, | ||
| statePath, | ||
| } from "../turn.ts"; | ||
| import type { TurnState } from "../turn.ts"; | ||
|
|
||
| const USAGE = `usage: dw turn [n] advance n turns (default 1) | ||
| dw turn track <name> <duration> track a light or spell (6, 30m, 1h) | ||
| dw turn status current turn and tracked durations | ||
| dw turn check-every <n> wandering-check cadence (default 2) | ||
| dw turn end end the session, clear state`; | ||
|
|
||
| function load(): TurnState { | ||
| const { state, note } = loadState(); | ||
| if (note) console.error(`dw: ${note}`); | ||
| return state; | ||
| } | ||
|
|
||
| function header(state: TurnState): string { | ||
| return `Turn ${state.turn} (${formatElapsed(state.turn)} elapsed)`; | ||
| } | ||
|
|
||
| function cmdStatus(): void { | ||
| const state = load(); | ||
| console.log(header(state)); | ||
| const next = state.turn + state.checkEvery - (state.turn % state.checkEvery); | ||
| console.log(`Wandering check every ${state.checkEvery} turns; next due turn ${next}`); | ||
| if (state.tracked.length === 0) { | ||
| console.log("Nothing tracked."); | ||
| return; | ||
| } | ||
| const width = Math.max(...state.tracked.map((t) => t.name.length)); | ||
| for (const t of state.tracked) { | ||
| const s = t.remaining === 1 ? "" : "s"; | ||
| console.log( | ||
| ` ${t.name.padEnd(width)} ${t.remaining} turn${s} left (expires turn ${state.turn + t.remaining})`, | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| function cmdTrack(rest: string[]): void { | ||
| const [name, duration] = rest; | ||
| if (!name || !duration) { | ||
| console.error("usage: dw turn track <name> <duration> (e.g. dw turn track torch 1h)"); | ||
| process.exit(1); | ||
| } | ||
| const turns = parseTurns(duration); | ||
| const state = load(); | ||
| state.tracked = state.tracked.filter((t) => t.name !== name); | ||
| state.tracked.push({ name, remaining: turns }); | ||
| saveState(state); | ||
| const s = turns === 1 ? "" : "s"; | ||
| console.log( | ||
| `Tracking ${name}: ${turns} turn${s} (${formatElapsed(turns)}), expires turn ${state.turn + turns}`, | ||
| ); | ||
| } | ||
|
|
||
| // Digits only: turn state persists, so "1h" or "3x" must not slip through as 1 or 3. | ||
| function parseCount(arg: string | undefined): number { | ||
| return /^\d+$/.test(arg ?? "") ? parseInt(arg!, 10) : NaN; | ||
| } | ||
|
|
||
| function cmdCheckEvery(rest: string[]): void { | ||
| const n = parseCount(rest[0]); | ||
| if (Number.isNaN(n) || n < 1) { | ||
| console.error("usage: dw turn check-every <n> (n >= 1)"); | ||
| process.exit(1); | ||
| } | ||
| const state = load(); | ||
| state.checkEvery = n; | ||
| saveState(state); | ||
| console.log(`Wandering check every ${n} turn${n === 1 ? "" : "s"}`); | ||
| } | ||
|
|
||
| function cmdEnd(): void { | ||
| const { state } = loadState(); | ||
| if (state.turn === 0 && state.tracked.length === 0) { | ||
| console.log("No session in progress."); | ||
| } else { | ||
| console.log(`Session ended: ${state.turn} turns (${formatElapsed(state.turn)})`); | ||
| } | ||
| clearState(); | ||
| } | ||
|
|
||
| function cmdAdvance(arg: string | undefined): void { | ||
| const n = arg === undefined ? 1 : parseCount(arg); | ||
| if (Number.isNaN(n) || n < 1) { | ||
| console.error(USAGE); | ||
| process.exit(1); | ||
| } | ||
| const state = load(); | ||
| const result = advance(state, n); | ||
| saveState(state); | ||
| console.log(header(state)); | ||
| for (const e of result.expired) { | ||
| const when = e.turn === state.turn ? "now" : `turn ${e.turn}`; | ||
| console.log(` ✗ ${e.name} expired ${when}`); | ||
| } | ||
| for (const name of result.expiringNext) { | ||
| console.log(` ! ${name} expires next turn`); | ||
| } | ||
| if (result.checksDue.length === 1) { | ||
| console.log(` Wandering check due (every ${state.checkEvery} turns; dw wander)`); | ||
| } else if (result.checksDue.length > 1) { | ||
| console.log( | ||
| ` ${result.checksDue.length} wandering checks due: turns ${result.checksDue.join(", ")} (dw wander)`, | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| export function cmdTurn(args: string[]): void { | ||
| const [sub, ...rest] = args; | ||
| switch (sub) { | ||
| case "status": | ||
| return cmdStatus(); | ||
| case "track": | ||
| return cmdTrack(rest); | ||
| case "check-every": | ||
| return cmdCheckEvery(rest); | ||
| case "end": | ||
| return cmdEnd(); | ||
| case "help": | ||
| case "--help": | ||
| case "-h": | ||
| console.log(USAGE); | ||
| console.log(`\nState survives between invocations in ${statePath()}`); | ||
| return; | ||
| default: | ||
| return cmdAdvance(sub); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; | ||
| import { dirname, join } from "node:path"; | ||
|
|
||
| // Anchored to the repo root (like pdf/config.ts) so the session follows the | ||
| // install, not the invocation directory. Gitignored as dw-session.json. | ||
| const REPO_ROOT = join(import.meta.dir, ".."); | ||
|
|
||
| export const TURN_MINUTES = 10; | ||
| export const DEFAULT_CHECK_EVERY = 2; | ||
|
|
||
| export interface Tracked { | ||
| name: string; | ||
| remaining: number; | ||
| } | ||
|
|
||
| export interface TurnState { | ||
| turn: number; | ||
| checkEvery: number; | ||
| tracked: Tracked[]; | ||
| } | ||
|
|
||
| export function statePath(): string { | ||
| const env = process.env.DW_SESSION?.trim(); | ||
| return env || join(REPO_ROOT, "dw-session.json"); | ||
| } | ||
|
|
||
| export function freshState(): TurnState { | ||
| return { turn: 0, checkEvery: DEFAULT_CHECK_EVERY, tracked: [] }; | ||
| } | ||
|
|
||
| export function loadState(): { state: TurnState; note?: string } { | ||
| const path = statePath(); | ||
| if (!existsSync(path)) return { state: freshState() }; | ||
| try { | ||
| const raw = JSON.parse(readFileSync(path, "utf8")); | ||
| if ( | ||
| !Number.isInteger(raw.turn) || | ||
| raw.turn < 0 || | ||
| !Number.isInteger(raw.checkEvery) || | ||
| raw.checkEvery < 1 || | ||
| !Array.isArray(raw.tracked) || | ||
| raw.tracked.some( | ||
| (t: Tracked) => | ||
| typeof t?.name !== "string" || !Number.isInteger(t?.remaining) || t.remaining < 1, | ||
| ) | ||
| ) { | ||
| throw new Error("bad shape"); | ||
| } | ||
| return { state: { turn: raw.turn, checkEvery: raw.checkEvery, tracked: raw.tracked } }; | ||
| } catch { | ||
| return { state: freshState(), note: `Turn state at ${path} was unreadable; starting fresh.` }; | ||
| } | ||
| } | ||
|
|
||
| export function saveState(state: TurnState): void { | ||
| const path = statePath(); | ||
| mkdirSync(dirname(path), { recursive: true }); | ||
| writeFileSync(path, JSON.stringify(state, null, 2) + "\n"); | ||
| } | ||
|
|
||
| export function clearState(): void { | ||
| rmSync(statePath(), { force: true }); | ||
| } | ||
|
|
||
| /** Parse a duration into turns: "6" or "6t" turns, "30m" minutes, "1h" hours. */ | ||
| export function parseTurns(spec: string): number { | ||
| const m = /^(\d+)\s*(t|m|min|h|hr)?$/i.exec(spec.trim()); | ||
| if (!m) throw new Error(`Can't parse duration "${spec}" (turns like 6, or 30m, 1h)`); | ||
| const n = parseInt(m[1], 10); | ||
| const unit = (m[2] ?? "t").toLowerCase(); | ||
| const turns = | ||
| unit === "h" || unit === "hr" | ||
| ? n * (60 / TURN_MINUTES) | ||
| : unit === "m" || unit === "min" | ||
| ? Math.ceil(n / TURN_MINUTES) | ||
| : n; | ||
| if (turns < 1) | ||
| throw new Error(`Duration "${spec}" is shorter than a turn (${TURN_MINUTES} minutes)`); | ||
| return turns; | ||
| } | ||
|
|
||
| export function formatElapsed(turns: number): string { | ||
| const minutes = turns * TURN_MINUTES; | ||
| const h = Math.floor(minutes / 60); | ||
| const m = minutes % 60; | ||
| if (h === 0) return `${m}m`; | ||
| return m === 0 ? `${h}h` : `${h}h${m}m`; | ||
| } | ||
|
|
||
| export interface AdvanceResult { | ||
| expired: { name: string; turn: number }[]; | ||
| expiringNext: string[]; | ||
| checksDue: number[]; | ||
| } | ||
|
|
||
| /** Advance n turns in place, ticking durations and noting due wandering checks. */ | ||
| export function advance(state: TurnState, n: number): AdvanceResult { | ||
| const expired: { name: string; turn: number }[] = []; | ||
| const checksDue: number[] = []; | ||
| for (let i = 0; i < n; i++) { | ||
| state.turn += 1; | ||
| for (const t of state.tracked) { | ||
| t.remaining -= 1; | ||
| if (t.remaining === 0) expired.push({ name: t.name, turn: state.turn }); | ||
| } | ||
| state.tracked = state.tracked.filter((t) => t.remaining > 0); | ||
| if (state.turn % state.checkEvery === 0) checksDue.push(state.turn); | ||
| } | ||
| const expiringNext = state.tracked.filter((t) => t.remaining === 1).map((t) => t.name); | ||
| return { expired, expiringNext, checksDue }; | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.