The bots talk at the table, each name in one of four tempers: a word on taking a chair, one from one of them as the duel begins, a line on a hard blow, a wizard brought down, its own death or the win, now and then a remark on a quiet turn, and an answer when named or when the talk speaks of bots; their lines go on the ledger as talk and are not counted as people talking in the tally or the visitors report. A duel in which every wizard has fallen while bots still stand is played out by the bots on the spot, where it used to wait forever for a turn no one could give

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0141G6xqLeNRYEtviLWSB5Up
This commit is contained in:
Eric WagonerandClaude Fable 5.1 committed 2026-11-12 09:57:16 -05:00
1 parent 07ebc41623
commit 89bc4083fc
6 files changed
+318 -10

No files matched your search

+116
View File
@@ -177,3 +177,119 @@ describe('a seat a browser lost', () => {
expect(rooms.findSeats('Bo', 'home').seated.map((s) => s.roomId)).toEqual([other.room.id]);
});
});
describe('the bots at the table', () => {
/** Ann opens a table of three and seats a bot. */
function withBot() {
const rooms = new Rooms(new Store(dir));
const host = rooms.create('Ann', 3);
const bot = rooms.addBot(host.room, host.token);
return { rooms, room: host.room, ann: host.token, bot };
}
it('says a word on taking a chair, which the ledger keeps', () => {
const { rooms, room, bot } = withBot();
expect(room.chat.at(-1)).toMatchObject({ id: bot.id });
expect(room.chat.at(-1)!.text.length).toBeGreaterThan(0);
expect(new Rooms(new Store(dir)).get(room.id).chat).toEqual(room.chat);
});
it('one of them says a word as the duel begins', () => {
const { rooms, room, ann, bot } = withBot();
const before = room.chat.length;
rooms.begin(room, ann);
expect(room.chat.length).toBe(before + 1);
expect(room.chat.at(-1)!.id).toBe(bot.id);
});
it('answers when named by a wizard, by the gallery or by the keeper, and only when named whole', () => {
const { rooms, room, ann, bot } = withBot();
rooms.setGalleryTalk(room, ann, true);
const before = room.chat.length;
rooms.say(room, ann, `${bot.name.toLowerCase()}, are you there?`);
expect(room.chat.length).toBe(before + 2);
expect(room.chat.at(-1)!.id).toBe(bot.id);
rooms.say(room, ann, `${bot.name}ish weather today`);
expect(room.chat.length).toBe(before + 3);
rooms.sayFromGallery(room, 'Cy', `Go ${bot.name}!`);
expect(room.chat.at(-1)!.id).toBe(bot.id);
rooms.keeperSays(room, 'Eric', `${bot.name}?`);
expect(room.chat.at(-1)!.id).toBe(bot.id);
});
it('play the duel out among themselves, at once, when the last wizard falls', () => {
const rooms = new Rooms(new Store(dir));
const host = rooms.create('Ann', 3);
rooms.addBot(host.room, host.token);
rooms.addBot(host.room, host.token);
rooms.begin(host.room, host.token);
const room = host.room;
for (let turns = 0; room.state!.wizards.A.alive && turns < 80; turns++) rooms.submit(room, host.token, { left: '-', right: '-', casts: [] }, room.resolved);
expect(room.state!.wizards.A.alive).toBe(false);
expect(room.state!.over).not.toBeNull();
expect(room.state!.over!.winner).not.toBe('A');
expect(room.chat.some((c) => c.id === room.state!.over!.winner)).toBe(true);
expect(new Rooms(new Store(dir)).get(room.id).state!.over).toEqual(room.state!.over);
});
it('speaks of its own death and the win, and a bot standing in for a wizard keeps quiet', () => {
const rooms = new Rooms(new Store(dir));
const host = rooms.create('Ann', 2);
const guest = rooms.join(host.room, 'Bo');
rooms.begin(host.room, host.token);
const room = host.room;
rooms.standIn(room, host.token, 'B');
let turns = 0;
while (!room.state!.over && turns++ < 60) rooms.submit(room, host.token, { left: 'P', right: 'P', casts: [] }, room.resolved);
expect(room.state!.over).not.toBeNull();
expect(room.chat.filter((c) => c.id === 'B')).toEqual([]);
void guest;
});
});
describe('the voices themselves', () => {
it('gives every name a temper, fills the names in, and never leaves a blank', async () => {
const { botLine, temperOf, turnTalk, botsNamed } = await import('./voices');
expect(temperOf('Aldric')).toBe('gruff');
expect(temperOf('The Construct')).toBe(temperOf('The Construct'));
for (const name of ['Aldric', 'Thessaly', 'Morwenna', 'Lucan', 'The Construct']) {
for (const moment of ['sit', 'begin', 'hurt', 'struck', 'slew', 'dead', 'won', 'drew', 'idle', 'named', 'hailed'] as const) {
for (let i = 0; i < 20; i++) {
const line = botLine(name, moment, { who: 'Ann', victim: 'Bo', foe: 'Cy' });
expect(line).not.toMatch(/\{|\}/);
expect(line).not.toMatch(/ — |: /);
}
}
}
expect(botsNamed('aldric and Lucan', [{ id: 'A', name: 'Aldric' }, { id: 'B', name: 'Lucan' }, { id: 'C', name: 'Wynne' }]).map((b) => b.id + b.moment)).toEqual(['Anamed', 'Bnamed']);
expect(botsNamed('Aldrics', [{ id: 'A', name: 'Aldric' }])).toEqual([]);
expect(botsNamed('can the bots talk?', [{ id: 'A', name: 'Aldric' }, { id: 'B', name: 'Lucan' }], () => 0.9)).toEqual([{ id: 'B', name: 'Lucan', moment: 'hailed' }]);
expect(botsNamed('robots!', [{ id: 'A', name: 'Aldric' }])).toEqual([]);
void turnTalk;
});
it('speaks on a death, a kill and a win from the states before and after a turn, and not for the dead', async () => {
const { turnTalk } = await import('./voices');
const { createGame } = await import('../../src/lib/game/state');
const before = createGame({ A: 'Ann', B: 'Aldric', C: 'Lucan' }, 1, 1);
const after = structuredClone(before);
after.wizards.A.alive = false;
after.wizards.A.lastHurtBy = 'B';
after.wizards.C.alive = false;
after.wizards.C.lastHurtBy = 'A';
const bots = [{ id: 'B', name: 'Aldric' }, { id: 'C', name: 'Lucan' }];
const said = turnTalk(bots, before, after, () => 0);
expect(said.map((s) => s.id)).toEqual(['B', 'C']);
expect(said[0].text).toBe('Down.');
expect(said[1].text).toBe('Nooo.');
after.over = { winner: 'B', reason: 'last standing' };
expect(turnTalk(bots, before, after, () => 0)[0].text).toBe('Done.');
// A quiet turn draws at most one remark, from a bot still standing, and only now and then.
const quiet = structuredClone(before);
expect(turnTalk(bots, before, quiet, () => 0.5)).toEqual([]);
expect(turnTalk(bots, before, quiet, () => 0).map((s) => s.id)).toEqual(['B']);
// A bot already dead before the turn has nothing more to say.
before.wizards.C.alive = false;
expect(turnTalk(bots, before, after, () => 0).map((s) => s.id)).toEqual(['B']);
});
});
+35 -8
View File
@@ -10,6 +10,7 @@ import { GESTURES, type Gesture } from '../../src/lib/game/spells';
import { CURRENT_RULES, createGame, inDuel, SPECTATOR, type GameState, type TurnInput, type WizardId } from '../../src/lib/game/state';
import { viewFor, type ChatLine, type RoomView } from '../../src/lib/game/view';
import type { LedgerLine, Store } from './store';
import { botLine, botsNamed, turnTalk } from './voices';
/** A dozen seats at most: a turn resolves only when every seat has moved, and the slowest sets the pace. */
const SEAT_IDS: WizardId[] = 'ABCDEFGHJKLM'.split('');
@@ -19,6 +20,8 @@ export { SPECTATOR };
const CHAT_MAX_LENGTH = 300;
/** Lines of talk kept and sent; the ledger keeps them all. */
const CHAT_KEEP = 200;
/** Turns the bots play on among themselves in one go; a duel still running past this many waits where it stands. */
const BOTS_ALONE_LIMIT = 300;
export interface Seat {
id: WizardId;
@@ -207,12 +210,16 @@ export class Rooms {
if (!room.galleryTalk) throw new RoomError('The gallery listens at this table; the host has not let it talk.', 403);
const name = cleanName(rawName);
if (room.seats.some((s) => s.name.toLowerCase() === name.toLowerCase())) throw new RoomError('A wizard at the table has that name.', 409);
this.commit(room, { t: 'chat', at: Date.now(), id: SPECTATOR, name, text: cleanTalk(raw) });
const text = cleanTalk(raw);
this.commit(room, { t: 'chat', at: Date.now(), id: SPECTATOR, name, text });
this.answer(room, name, text);
}
/** The keeper of the site says a word at a table from the keeper's door, whether or not the gallery may talk: the answer to a call they could not take up. */
keeperSays(room: Room, keeper: string, raw: unknown): void {
this.commit(room, { t: 'chat', at: Date.now(), id: SPECTATOR, name: keeper, text: cleanTalk(raw), keeper: true });
const text = cleanTalk(raw);
this.commit(room, { t: 'chat', at: Date.now(), id: SPECTATOR, name: keeper, text, keeper: true });
this.answer(room, keeper, text);
}
/**
@@ -382,6 +389,9 @@ export class Rooms {
if (room.state) throw new RoomError('The duel has already begun.', 409);
if (room.seats.length < 2) throw new RoomError('A duel needs at least two wizards.', 409);
this.commit(room, { t: 'start', seed: newSeed(), rules: CURRENT_RULES });
const bots = this.voiced(room);
const bot = bots[Math.floor(Math.random() * bots.length)];
if (bot) this.commit(room, { t: 'chat', at: Date.now(), id: bot.id, text: botLine(bot.name, 'begin') });
}
/** The host seats a bot in an empty chair. */
@@ -392,7 +402,9 @@ export class Rooms {
const taken = new Set(room.seats.map((s) => s.name.toLowerCase()));
const pool = BOT_NAMES.filter((n) => !taken.has(n.toLowerCase()));
const name = pool[Math.floor(Math.random() * pool.length)] ?? 'The Construct';
return this.sit(room, name, true).seat;
const seat = this.sit(room, name, true).seat;
this.commit(room, { t: 'chat', at: Date.now(), id: seat.id, text: botLine(name, 'sit') });
return seat;
}
/** Take the next free seat. The token is returned once and never stored; the ledger keeps its hash. */
@@ -492,18 +504,33 @@ export class Rooms {
if (seat.bot && needsInput(state, seat.id) && !(seat.id in inputs)) inputs[seat.id] = chooseBotTurn(state, seat.id);
}
this.commit(room, { t: 'turn', at: Date.now(), inputs });
// A time stop owed to a bot resolves at once; a human's waits for them.
while (room.state && !room.state.over && room.state.timeStops[0] && room.seats.find((s) => s.id === room.state!.timeStops[0])?.bot) {
const actor = room.state.timeStops[0];
this.commit(room, { t: 'turn', at: Date.now(), inputs: { [actor]: chooseBotTurn(room.state, actor) } });
// A turn nobody at the table is awaited for is the bots' alone, whether a time stop owed to
// one of them or the rest of a duel every wizard has left; it resolves at once, to the end.
for (let played = 0; room.state && !room.state.over && waitingOn(room).length === 0 && played < BOTS_ALONE_LIMIT; played++) {
const theirs: Record<WizardId, TurnInput> = {};
for (const seat of room.seats) if (seat.bot && needsInput(room.state, seat.id)) theirs[seat.id] = chooseBotTurn(room.state, seat.id);
this.commit(room, { t: 'turn', at: Date.now(), inputs: theirs });
}
if (room.state?.over) this.commit(room, { t: 'over', at: Date.now(), winner: room.state.over.winner, reason: room.state.over.reason });
for (const line of turnTalk(this.voiced(room), state, room.state!)) this.commit(room, { t: 'chat', at: Date.now(), id: line.id, text: line.text });
}
/** Table talk, from a seat to everyone at the table and in the gallery. */
say(room: Room, token: string | undefined, raw: unknown): void {
const seat = this.seatOf(room, token);
this.commit(room, { t: 'chat', at: Date.now(), id: seat.id, text: cleanTalk(raw) });
const text = cleanTalk(raw);
this.commit(room, { t: 'chat', at: Date.now(), id: seat.id, text });
this.answer(room, seat.name, text);
}
/** The bots at the table, speaking for themselves; one standing in for a wizard keeps that wizard's silence. */
private voiced(room: Room): { id: WizardId; name: string }[] {
return room.seats.filter((s) => s.bot && !s.standIn).map((s) => ({ id: s.id, name: s.name }));
}
/** A bot named in a line of talk answers it. */
private answer(room: Room, speaker: string, text: string): void {
for (const bot of botsNamed(text, this.voiced(room))) this.commit(room, { t: 'chat', at: Date.now(), id: bot.id, text: botLine(bot.name, bot.moment, { who: speaker }) });
}
/** The view for a seat, or for the gallery when the seat is SPECTATOR. */
+4 -1
View File
@@ -84,7 +84,10 @@ export class Tallies {
state = null;
}
}
} else if (line.t === 'chat') t.talkLines += 1;
} else if (line.t === 'chat') {
// A bot's lines are the table's colour, not people talking.
if (!seats.find((s) => s.id === line.id)?.bot) t.talkLines += 1;
}
else if (line.t === 'over') over = line;
}
t.turnsPlayed += turns;
+160
View File
@@ -0,0 +1,160 @@
// What the bots say at the table. Each bot name has a temper, and each temper
// a few lines for each moment worth a word: taking a chair, the duel beginning,
// a hit taken, a wizard slain, its own death, the end, a lull, and being named
// in the talk. A line is chosen at random when the moment comes and written to
// the ledger as the bot's own talk, so a restart replays what was said and not
// a fresh draw.
import type { GameState, WizardId } from '../../src/lib/game/state';
export type Temper = 'gruff' | 'courtly' | 'dry' | 'eager';
export type Moment = 'sit' | 'begin' | 'hurt' | 'struck' | 'slew' | 'dead' | 'won' | 'drew' | 'idle' | 'named' | 'hailed';
const TEMPER: Record<string, Temper> = {
aldric: 'gruff',
ormund: 'gruff',
gandric: 'gruff',
thessaly: 'courtly',
isaura: 'courtly',
bellamy: 'courtly',
morwenna: 'dry',
corwin: 'dry',
wynne: 'dry',
ysolde: 'eager',
hesper: 'eager',
lucan: 'eager'
};
/** `{me}` is the speaker, `{who}` the one spoken to, `{victim}` the wizard just slain, `{foe}` the one who did the hurting. */
const LINES: Record<Temper, Record<Moment, string[]>> = {
gruff: {
sit: ['{me}. This chair will do.', 'Sat. Get on with it.', 'I came for a duel. Who is giving me one?', 'Move your elbows. {me} is sitting down.'],
begin: ['At last.', 'Hands up, then.', 'Let us see what you know.', 'No talking. Waving.'],
hurt: ['That stung.', 'I have had worse from a cook.', 'Hm.', 'Do that again and I will remember it.'],
struck: ['Enough of that.', 'You will get that back with interest.', 'Right. Now I am annoyed.'],
slew: ['Down.', 'One fewer.', '{victim} should have kept a shield up.', 'That is how it is done.'],
dead: ['Bah.', 'Well struck.', 'So it goes.', 'Done, then. Finish the rest.'],
won: ['Done.', 'The table is mine.', 'Next.', 'Good duel. Short.'],
drew: ['Nobody wins. Typical.', 'A draw. I want my hour back.'],
idle: ['Get on with it.', 'Somebody wave something.', 'Slow table.'],
named: ['What.', 'Say it plainly, {who}.', 'I hear you, {who}.', 'Talk after. Duel now.'],
hailed: ['We hear you.', 'Bots, is it. I have a name.', 'Here. What of it?']
},
courtly: {
sit: ['{me}, at your service and shortly against it.', 'A seat near the fire. How kind.', 'I accept the invitation with pleasure.', 'Good evening, all. {me} will take this chair.'],
begin: ['Shall we? We shall.', 'A fair duel to all, and a short one to some.', 'Let the best hands win.', 'After you. No, I insist. Oh, very well.'],
hurt: ['Ow. Noted.', 'How rude.', 'I felt that, and I will answer it.', 'A touch. Only a touch.'],
struck: ['That was uncalled for.', 'You have my full attention now, {foe}.', 'I shall remember that, {foe}.'],
slew: ['My apologies, {victim}. It was you or me.', '{victim} fought well, which was not quite enough.', 'Rest easy, {victim}. The rest of us will carry on.'],
dead: ['Well. That is that.', 'Carry on without me. I insist.', 'Fairly done, {foe}. Fairly done.', 'I shall watch from the gallery with great interest.'],
won: ['Thank you all. A pleasure.', 'Last one standing, as I had hoped.', 'I would say it was close. It would be a kindness.'],
drew: ['A draw, then. Honour all round.', 'Nobody left to bow to. How odd.'],
idle: ['Does anyone else hear the fire crackle?', 'A pleasant lull.', 'Take your time. I am enjoying the company.'],
named: ['You called, {who}?', 'I am listening, {who}.', 'Go on.', 'Yes, {who}? I am all ears and both hands.'],
hailed: ['One of us is listening, {who}.', 'We can talk, and we can hear. Do go on.', 'Speaking for the bots, as you call us, good evening.']
},
dry: {
sit: ['{me}. I will be over here, losing gracefully.', 'Save me a chair near the door.', 'I suppose someone has to.', 'Is this the duel? It looks like a duel.'],
begin: ['Here we go.', 'Everyone remember their gestures? No? Good.', 'Try to look surprised when I win.', 'Let us get this over with.'],
hurt: ['Rude.', 'I needed that.', 'Someone is keeping count, I hope.', 'I felt that in my boots.'],
struck: ['Is it hot in here, or is that me on fire?', 'Well. That happened.', 'Noted, {foe}. Very much noted.'],
slew: ['Sorry, {victim}. Not very, but sorry.', '{victim} will want a word with me later.', 'Oh. That worked.'],
dead: ['Told you.', 'I had a plan. This was not it.', 'Carry on. Pretend I was never here.', 'Ah. Dead. There it is.'],
won: ['Oh. I won. Someone write that down.', 'That went better than expected.', 'I would like it noted that I did not cheat. Much.'],
drew: ['A draw. How tidy.', 'Everybody loses. I feel seen.'],
idle: ['Taking our time, are we.', 'I had a thought. It has gone.', 'Lovely weather for it.'],
named: ['Yes, {who}?', 'Present.', 'That is my name, {who}. Use it kindly.', 'Speaking.'],
hailed: ['We can hear you, you know.', 'Bots. Charming. Yes, {who}?', 'Someone said bots. I am choosing to be flattered.']
},
eager: {
sit: ['Hello! {me}. Which hand do I wave first?', 'Ooh, a duel. Yes please.', 'Is this seat free? It is now.', 'Hi everyone! Sorry. Hi.'],
begin: ['Here we go, here we go.', 'Everyone ready? I am ready.', 'Oh, this is exciting.', 'Good luck! Not too much luck.'],
hurt: ['Ow! Ow ow.', 'That one got through.', 'Right. Right. I am fine.', 'Hey!'],
struck: ['That was a big one.', 'Oof. I am still up, though. Still up.', 'Okay. Okay. Wow.'],
slew: ['Oh no, {victim}, I am sorry, did that hurt?', 'Did I do that? I did that.', 'Sorry, {victim}! Not sorry. A bit sorry.'],
dead: ['Nooo.', 'Well, that was quick.', 'Good duel! Ow.', 'I nearly had something.'],
won: ['I won! I actually won!', 'Did you see that? Did everyone see that?', 'Again! Can we go again?'],
drew: ['Nobody won? Can we go again?', 'A draw! I have never had a draw.'],
idle: ['What is everyone casting? Do not tell me.', 'I have a plan. It is a secret.', 'This is fun.', 'Is it my turn? It is everyone’s turn. Right.'],
named: ['Yes! Hello, {who}.', 'That is me! What is it?', 'Here!', 'Hi, {who}!'],
hailed: ['We can talk! I can talk!', 'Hello! Yes! Bots here!', 'Did someone say bots? That is us. Hi, {who}.']
}
};
/** A bot under a name not on the list, such as The Construct, still gets a temper, and the same one each time. */
export function temperOf(name: string): Temper {
const known = TEMPER[name.toLowerCase()];
if (known) return known;
const tempers: Temper[] = ['gruff', 'courtly', 'dry', 'eager'];
let h = 0;
for (const c of name) h = (h * 31 + c.charCodeAt(0)) >>> 0;
return tempers[h % tempers.length];
}
export interface Fill {
who?: string;
victim?: string;
foe?: string;
}
export function botLine(name: string, moment: Moment, fill: Fill = {}, rng: () => number = Math.random): string {
const pool = LINES[temperOf(name)][moment];
const line = pool[Math.floor(rng() * pool.length)];
return line.replace(/\{(me|who|victim|foe)\}/g, (_, k: string) => (k === 'me' ? name : (fill[k as keyof Fill] ?? 'you')));
}
/**
* A bot named in a line of talk answers; the name must stand as a whole word. A line
* that speaks of "the bots" without naming one gets an answer from one of them.
*/
export function botsNamed(text: string, bots: { id: WizardId; name: string }[], rng: () => number = Math.random): { id: WizardId; name: string; moment: 'named' | 'hailed' }[] {
const words = text.toLowerCase();
const whole = (word: string) => new RegExp(`(^|[^\\p{L}])${word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([^\\p{L}]|$)`, 'u').test(words);
const named = bots.filter((b) => whole(b.name.toLowerCase())).map((b) => ({ ...b, moment: 'named' as const }));
if (named.length === 0 && bots.length > 0 && (whole('bot') || whole('bots'))) return [{ ...bots[Math.floor(rng() * bots.length)], moment: 'hailed' }];
return named;
}
/** Small hits are not always worth a word, and a lull rarely is. */
const SPEAK_ON_HURT = 1 / 3;
const SPEAK_ON_LULL = 1 / 15;
const HEAVY_BLOW = 4;
/**
* What each bot has to say about the turn just played, in seat order, at most one
* line each: its death, its win, a wizard it slew, or a hit it took. On a turn that
* gave nobody anything to say, one bot may remark on the lull.
*/
export function turnTalk(bots: { id: WizardId; name: string }[], before: GameState, after: GameState, rng: () => number = Math.random): { id: WizardId; text: string }[] {
const said: { id: WizardId; text: string }[] = [];
const nameOf = (id: WizardId | undefined) => (id ? after.wizards[id]?.name : undefined);
// Two bots of one temper may draw the same line in one turn; a second draw usually parts them.
const fresh = (name: string, moment: Moment, fill: Fill): string => {
const first = botLine(name, moment, fill, rng);
return said.some((s) => s.text === first) ? botLine(name, moment, fill, rng) : first;
};
const fell = after.seats.filter((id) => before.wizards[id].alive && !after.wizards[id].alive && !after.wizards[id].surrendered);
for (const bot of bots) {
const was = before.wizards[bot.id];
const now = after.wizards[bot.id];
if (!was || !now || !was.alive) continue;
const foe = nameOf(now.lastHurtBy);
let text: string | null = null;
if (!now.alive) text = fresh(bot.name, 'dead', { foe });
else if (after.over) text = after.over.winner === bot.id ? fresh(bot.name, 'won', {}) : after.over.winner === null ? fresh(bot.name, 'drew', {}) : null;
else {
const victim = fell.find((id) => after.wizards[id].lastHurtBy === bot.id);
const lost = was.hp - now.hp;
if (victim) text = fresh(bot.name, 'slew', { victim: nameOf(victim) });
else if (lost >= HEAVY_BLOW) text = fresh(bot.name, 'struck', { foe });
else if (lost > 0 && rng() < SPEAK_ON_HURT) text = fresh(bot.name, 'hurt', { foe });
}
if (text) said.push({ id: bot.id, text });
}
if (said.length === 0 && fell.length === 0 && !after.over && rng() < SPEAK_ON_LULL) {
const standing = bots.filter((b) => after.wizards[b.id]?.alive);
const bot = standing[Math.floor(rng() * standing.length)];
if (bot) said.push({ id: bot.id, text: botLine(bot.name, 'idle', {}, rng) });
}
return said;
}