Preferences: motion, confirming a move, coordinates on the board, and the last table choices remembered

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jm2auWk6RP71CjaAb4FMoG
This commit is contained in:
Eric Wagoner
2026-09-23 18:54:55 -04:00
co-authored by Claude Fable 5.1
parent 5db89edbc1
commit aa4f86bc56
7 changed files with 233 additions and 8 deletions
+43 -6
View File
@@ -9,6 +9,7 @@
import TableTalk from './TableTalk.svelte';
import { beyond, cellOf, cornersOf, isEdge, movesFrom, rulesetOf, sideOf, throneOf, type Move, type Side } from '$lib/game';
import type { Room } from '$lib/net/room.svelte';
import { prefs, reducedMotion } from '$lib/prefs.svelte';
let { room }: { room: Room } = $props();
@@ -59,7 +60,9 @@
let shown = $state(0);
let shownSet = $state('');
let animating = $state(false);
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
const calm = $derived(prefs.motion === 'reduced' || reducedMotion());
const showCoords = $derived(prefs.coordinates !== false);
const wait = (ms: number) => new Promise((r) => setTimeout(r, calm ? 0 : ms));
function resetTokens() {
let id = 0;
@@ -149,15 +152,28 @@
liveText = text;
}
/** A move awaiting the player's word, when they asked to confirm. */
let pending = $state<{ from: number; to: number } | null>(null);
async function send(from: number, to: number) {
pending = null;
selected = null;
await room.submit({ from, to });
}
async function tap(i: number) {
if (!yourMove || room.sending || animating) return;
reviewing = null;
if (selected !== null && targets.includes(i)) {
const from = selected;
selected = null;
await room.submit({ from, to: i });
if (prefs.confirmMoves === true) {
pending = { from: selected, to: i };
announce(`Move ${label(selected)} to ${label(i)}? Confirm or cancel below.`);
return;
}
await send(selected, i);
return;
}
pending = null;
if (sideOf(g.cells[i]) === mySide) {
selected = selected === i ? null : i;
if (selected !== null) {
@@ -188,6 +204,7 @@
} else if (e.key === 'Escape') {
selected = null;
reviewing = null;
pending = null;
announce('Selection cleared.');
}
}
@@ -215,9 +232,14 @@
{#if shownStory && (shownCaptured.length || reviewing !== null)}
<p class="story" class:capture={shownCaptured.length > 0}>{shownStory}{#if reviewing !== null}&nbsp;<button type="button" class="link" onclick={() => (reviewing = null)}>back to now</button>{/if}</p>
{/if}
{#if pending}
<p class="confirm">Move {label(pending.from)} to {label(pending.to)}?
<button type="button" class="commit small" onclick={() => pending && send(pending.from, pending.to)}>Confirm</button>
<button type="button" class="quiet" onclick={() => (pending = null)}>Cancel</button></p>
{/if}
{#if room.error}<p class="warning">{room.error}</p>{/if}
<div class="frame">
<div class="frame" class:calm>
<svg viewBox="0 0 {width} {height}" role="grid" aria-label="The board">
<defs>
<filter id="grain" x="0" y="0" width="100%" height="100%">
@@ -232,7 +254,7 @@
</filter>
</defs>
<rect class="wood" x="0" y="0" {width} {height} rx="6" filter="url(#grain)" />
{#each Array.from({ length: size }, (_, n) => n) as n (n)}
{#each showCoords ? Array.from({ length: size }, (_, n) => n) : [] as n (n)}
<text class="coord" x={PAD_L + n * CELL + CELL / 2} y={height - 4} text-anchor="middle">{String.fromCharCode(97 + n)}</text>
<text class="coord" x={PAD_L - 4} y={PAD_T + n * CELL + CELL / 2 + 3} text-anchor="end">{size - n}</text>
{/each}
@@ -419,6 +441,21 @@
margin: 0 auto 0.5rem;
}
.confirm {
max-width: 620px;
margin: 0 auto 0.5rem;
display: flex;
align-items: center;
gap: 0.6rem;
flex-wrap: wrap;
}
.calm .piece,
.calm .square,
.calm .wood {
transition: none;
}
.frame {
max-width: 620px;
margin: 0 auto;
+21 -2
View File
@@ -4,6 +4,8 @@
// about panel with the rules, the guide and a way to reach the keeper.
import { goto } from '$app/navigation';
import { otherGames, type FamilyGame } from '$lib/family';
import Preferences from './Preferences.svelte';
import { prefs, setPref } from '$lib/prefs.svelte';
import { allSeats, doubtSeat, forgetSeat, rememberSeat, ServerError, trustSeat, type Report, type Tally } from '$lib/net/client';
import { api, NAME_MAX, playerName, rememberName, Room } from '$lib/net/room.svelte';
import { unreadTalk } from '$lib/net/talk';
@@ -14,7 +16,14 @@
let name = $state(playerName());
let code = $state('');
/** The host's choices for the next table, from the game's declared options. */
let options = $state<Record<string, string>>(Object.fromEntries((game.options ?? []).map((o) => [o.key, o.default])));
// The host's last choices come back as the defaults; a regular does not re-pick them each visit.
let options = $state<Record<string, string>>(
Object.fromEntries((game.options ?? []).map((o) => [o.key, o.choices.some((c) => c.value === prefs[`table.${o.key}`]) ? String(prefs[`table.${o.key}`]) : o.default]))
);
$effect(() => {
for (const o of game.options ?? []) if (prefs[`table.${o.key}`] !== options[o.key]) setPref(`table.${o.key}`, options[o.key]);
});
let prefsOpen = $state(false);
/** The hall's still of the opening position, on whichever board the selector names. */
const still = $derived(
@@ -167,7 +176,8 @@
<h1>Hnefatafl</h1>
<p class="pitch">The Viking board game. One king, one throne, four corners, and a ring of attackers closing in.</p>
<p class="tag">Hnefatafl was played across the Norse world for a thousand years before chess. Every piece moves like a rook and is taken by being sandwiched; the attackers must capture the king, the king must reach safety. Play a housecarl, or open a table for a friend and play by turns. Copenhagen rules on the big board, or Tablut, the older game Linnaeus wrote down in 1732.</p>
<p class="links"><a href="/guide">how to play</a> · <a href="/rules">the rules</a> · <a class="about-link" href="#about" onclick={() => (aboutOpen = true)}>about this game a labor of love</a></p>
<p class="links"><a href="/guide">how to play</a> · <a href="/rules">the rules</a> · <a class="about-link" href="#about" onclick={() => (aboutOpen = true)}>about this game a labor of love</a> · <button type="button" class="link-like" onclick={() => (prefsOpen = true)}>preferences</button></p>
<Preferences bind:open={prefsOpen} />
</div>
<div class="lid-play">
@@ -655,4 +665,13 @@
.tally dd {
margin: 0;
}
.link-like {
background: none;
border: 0;
padding: 0;
font: inherit;
color: inherit;
text-decoration: underline;
cursor: pointer;
}
</style>
+97
View File
@@ -0,0 +1,97 @@
<script lang="ts">
// The preferences panel: every declared setting, kit and game, as a
// control. Opened from the masthead; closes with its button or Escape.
import { PREFERENCES, prefs, setPref } from '$lib/prefs.svelte';
let { open = $bindable(false) }: { open?: boolean } = $props();
function onKey(e: KeyboardEvent) {
if (e.key === 'Escape') open = false;
}
</script>
<svelte:window onkeydown={onKey} />
{#if open}
<div class="scrim" role="presentation" onclick={() => (open = false)}></div>
<div class="panel" role="dialog" aria-modal="true" aria-labelledby="prefs-title">
<h2 id="prefs-title">Preferences</h2>
<p class="muted small">Kept in this browser, and nowhere else.</p>
{#each PREFERENCES as p (p.key)}
<div class="pref">
{#if p.kind === 'toggle'}
<label class="row">
<input type="checkbox" checked={prefs[p.key] === true} onchange={(e) => setPref(p.key, e.currentTarget.checked)} />
<span>{p.label}</span>
</label>
{:else}
<label class="row">
<span>{p.label}</span>
<select value={prefs[p.key]} onchange={(e) => setPref(p.key, e.currentTarget.value)}>
{#each p.choices ?? [] as c (c.value)}<option value={c.value}>{c.label}</option>{/each}
</select>
</label>
{/if}
{#if p.note}<p class="muted small note">{p.note}</p>{/if}
</div>
{/each}
<button type="button" class="quiet" onclick={() => (open = false)}>Done</button>
</div>
{/if}
<style>
.scrim {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.45);
z-index: 20;
}
.panel {
position: fixed;
z-index: 21;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: min(92vw, 26rem);
max-height: 90vh;
overflow: auto;
background: var(--slate);
border: 1px solid var(--rule-strong);
border-radius: 8px;
padding: 1.2rem 1.4rem 1.4rem;
}
h2 {
font-size: 1.3rem;
margin: 0 0 0.2rem;
}
.pref {
padding: 0.55rem 0;
border-top: 1px solid var(--rule);
}
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.8rem;
}
.row input[type='checkbox'] {
order: 2;
}
.note {
margin-top: 0.3rem;
}
.small {
font-size: 0.85rem;
}
.quiet {
margin-top: 0.8rem;
}
</style>
+1
View File
@@ -397,6 +397,7 @@ export const game: GameSpec<State, Input> = {
},
{ key: 'side', label: 'You play', choices: SIDES, default: 'defenders' }
],
preferences: [{ key: 'coordinates', label: 'Coordinates on the board', kind: 'toggle', default: true }],
create: createGame,
resolve: resolveRound,
needsInput: (state, seat) => !state.over && state.players[seat]?.side === state.toMove,
+2
View File
@@ -39,6 +39,8 @@ export interface GameSpec<State, Input> {
seatIds: SeatId[];
/** What the host may choose when opening a table; empty for a game with one way to play. */
options?: TableOption[];
/** The game's own settings for the preferences panel, kept in the player's browser (see $lib/prefs.svelte). */
preferences?: { key: string; label: string; kind: 'toggle' | 'choice'; choices?: { value: string; label: string }[]; default: boolean | string; note?: string }[];
minSeats: number;
/** Names the server draws for bots, in preference order. */
botNames: string[];
+65
View File
@@ -0,0 +1,65 @@
// Preferences: what this browser remembers about how its player likes to
// play. The kit's own settings are motion and whether a move is confirmed
// before it is sent; a game declares more in GameSpec.preferences, and the
// panel renders every declaration. Nothing here leaves the browser.
import { game } from '$lib/game';
export interface Preference {
key: string;
label: string;
/** A toggle holds a boolean; a choice holds one of its choices' values. */
kind: 'toggle' | 'choice';
choices?: { value: string; label: string }[];
default: boolean | string;
note?: string;
}
/** The settings every game in the kit shares. */
export const KIT_PREFERENCES: Preference[] = [
{ key: 'motion', label: 'Motion', kind: 'choice', choices: [{ value: 'full', label: 'pieces move and fade' }, { value: 'reduced', label: 'changes appear at once' }], default: 'full' },
{ key: 'confirmMoves', label: 'Confirm a move before it is sent', kind: 'toggle', default: false }
];
export const PREFERENCES: Preference[] = [...KIT_PREFERENCES, ...(game.preferences ?? [])];
const KEY = 'hnefatafl:prefs';
function defaults(): Record<string, boolean | string> {
return Object.fromEntries(PREFERENCES.map((p) => [p.key, p.default]));
}
function load(): Record<string, boolean | string> {
const base = defaults();
try {
const saved = JSON.parse(localStorage.getItem(KEY) ?? '{}') as Record<string, unknown>;
for (const p of PREFERENCES) {
const v = saved[p.key];
if (p.kind === 'toggle' && typeof v === 'boolean') base[p.key] = v;
if (p.kind === 'choice' && typeof v === 'string' && p.choices?.some((c) => c.value === v)) base[p.key] = v;
}
// The hall's last table options ride along under table.<key>, undeclared.
for (const [k, v] of Object.entries(saved)) if (k.startsWith('table.') && typeof v === 'string') base[k] = v;
} catch {
// Without storage the defaults apply for this visit.
}
return base;
}
/** The live preferences; read them where they matter, set them through setPref. */
export const prefs = $state<Record<string, boolean | string>>(typeof localStorage === 'undefined' ? defaults() : load());
export function setPref(key: string, value: boolean | string): void {
prefs[key] = value;
try {
localStorage.setItem(KEY, JSON.stringify(prefs));
} catch {
// The change still applies for this visit.
}
}
/** The reduced-motion preference, or the system's, whichever asks for calm. */
export function reducedMotion(): boolean {
if (prefs.motion === 'reduced') return true;
return typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches;
}
+4
View File
@@ -4,6 +4,7 @@
import Board from '$lib/components/Board.svelte';
import Lobby from '$lib/components/Lobby.svelte';
import ReportSlip from '$lib/components/ReportSlip.svelte';
import Preferences from '$lib/components/Preferences.svelte';
import { seatFor } from '$lib/net/client';
import { NAME_MAX, playerName, rememberName, Room } from '$lib/net/room.svelte';
@@ -16,6 +17,7 @@
let error = $state('');
let copied = $state(false);
let reporting = $state(false);
let prefsOpen = $state(false);
/** A phrase minted to carry this seat to another device, while it lasts. */
let phrase = $state<{ phrase: string; expiresAt: number } | null>(null);
let rematching = $state(false);
@@ -120,6 +122,7 @@
<button type="button" class="quiet" title="A phrase that brings this seat to another device" onclick={transfer}>Transfer seat</button>
{/if}
{/if}
<button type="button" class="quiet" onclick={() => (prefsOpen = true)}>Preferences</button>
<a class="quiet" href="/guide">How to play</a>
<a class="quiet" href={room ? `/rules?room=${roomId}` : '/rules'}>Rules</a>
{#if room}
@@ -129,6 +132,7 @@
</nav>
</header>
<Preferences bind:open={prefsOpen} />
{#if room}
<ReportSlip {room} bind:open={reporting} />
{/if}