Feature: add character creation logic and tests

- Implement character creation functions to handle adventurer setup.
- Add validation for adventurer name and selection of starting items.
- Introduce new items in sample content pack: Flint and Steel, Pouch, Wax Sealing Kit, and Backpack.
- Create tests for character creation functionality to ensure valid options and error handling.

Feature: implement dice rolling mechanics and tests

- Add functions for rolling various dice types (d3, d6, 2d6, d66) with validation.
- Implement modifier application with clamping for roll results.
- Create tests to verify correct behavior of dice rolling functions.

Feature: add table lookup functionality and tests

- Implement table lookup and resolution logic for defined tables.
- Support for modified ranges and fallback to nearest entries.
- Create tests to ensure correct table entry resolution based on roll results.
This commit is contained in:
Keith Solomon
2026-03-15 11:59:50 -05:00
parent e303373441
commit 6bf48df74c
9 changed files with 996 additions and 3 deletions

View File

@@ -0,0 +1,50 @@
import { describe, expect, it } from "vitest";
import { sampleContentPack } from "@/data/sampleContentPack";
import { createStartingAdventurer, getCharacterCreationOptions } from "./character";
describe("character creation", () => {
it("exposes legal starting options from the content pack", () => {
const options = getCharacterCreationOptions(sampleContentPack);
expect(options.weapons).toHaveLength(1);
expect(options.armour).toHaveLength(1);
expect(options.scrolls).toHaveLength(1);
});
it("builds a valid starting adventurer from legal choices", () => {
const adventurer = createStartingAdventurer(sampleContentPack, {
name: "Mira",
weaponId: "weapon.short-sword",
armourId: "armour.leather-vest",
scrollId: "scroll.lesser-heal",
});
expect(adventurer.name).toBe("Mira");
expect(adventurer.level).toBe(1);
expect(adventurer.stats.shift).toBe(2);
expect(adventurer.manoeuvreIds).toEqual([
"manoeuvre.exact-strike",
"manoeuvre.guard-break",
]);
expect(adventurer.inventory.rationCount).toBe(3);
expect(adventurer.inventory.carried).toEqual(
expect.arrayContaining([
expect.objectContaining({ definitionId: "potion.healing", quantity: 1 }),
expect.objectContaining({ definitionId: "scroll.lesser-heal", quantity: 1 }),
]),
);
});
it("rejects an empty adventurer name", () => {
expect(() =>
createStartingAdventurer(sampleContentPack, {
name: " ",
weaponId: "weapon.short-sword",
armourId: "armour.leather-vest",
scrollId: "scroll.lesser-heal",
}),
).toThrow("Adventurer name is required.");
});
});

128
src/rules/character.ts Normal file
View File

@@ -0,0 +1,128 @@
import type { ContentPack } from "@/types/content";
import type { AdventurerState, InventoryEntry } from "@/types/state";
export type CharacterCreationChoiceSet = {
name: string;
weaponId: string;
armourId: string;
scrollId: string;
};
const DEFAULT_STARTING_ITEM_IDS = [
"item.flint-and-steel",
"item.lantern",
"item.ration",
"item.pouch",
"item.wax-sealing-kit",
"item.backpack",
];
function requireDefinition<T extends { id: string }>(
entries: T[],
id: string,
label: string,
) {
const entry = entries.find((candidate) => candidate.id === id);
if (!entry) {
throw new Error(`Unknown ${label} id: ${id}`);
}
return entry;
}
function makeInventoryEntry(definitionId: string, quantity = 1): InventoryEntry {
return {
definitionId,
quantity,
};
}
export function getCharacterCreationOptions(content: ContentPack) {
return {
weapons: content.weapons.filter((weapon) => weapon.startingOption),
armour: content.armour.filter((armour) => armour.startingOption),
scrolls: content.scrolls.filter((scroll) => scroll.startingOption),
};
}
export function createStartingAdventurer(
content: ContentPack,
choices: CharacterCreationChoiceSet,
): AdventurerState {
const trimmedName = choices.name.trim();
if (trimmedName.length === 0) {
throw new Error("Adventurer name is required.");
}
const selectedWeapon = requireDefinition(content.weapons, choices.weaponId, "weapon");
const selectedArmour = requireDefinition(content.armour, choices.armourId, "armour");
const selectedScroll = requireDefinition(content.scrolls, choices.scrollId, "scroll");
if (!selectedWeapon.startingOption) {
throw new Error(`Weapon ${selectedWeapon.id} is not a legal starting option.`);
}
if (!selectedArmour.startingOption) {
throw new Error(`Armour ${selectedArmour.id} is not a legal starting option.`);
}
if (!selectedScroll.startingOption) {
throw new Error(`Scroll ${selectedScroll.id} is not a legal starting option.`);
}
const allowedManoeuvreIds = selectedWeapon.allowedManoeuvreIds;
if (allowedManoeuvreIds.length === 0) {
throw new Error(`Weapon ${selectedWeapon.id} does not define starting manoeuvres.`);
}
DEFAULT_STARTING_ITEM_IDS.forEach((itemId) => requireDefinition(content.items, itemId, "item"));
requireDefinition(content.potions, "potion.healing", "potion");
return {
id: "adventurer.new",
name: trimmedName,
level: 1,
xp: 0,
hp: {
current: 10,
max: 10,
base: 10,
},
stats: {
shift: 2,
discipline: 1,
precision: 0,
},
weaponId: selectedWeapon.id,
manoeuvreIds: allowedManoeuvreIds,
armourId: selectedArmour.id,
favour: {},
statuses: [],
inventory: {
carried: [
makeInventoryEntry("item.flint-and-steel"),
makeInventoryEntry("item.lantern"),
makeInventoryEntry("item.ration", 3),
makeInventoryEntry("item.pouch"),
makeInventoryEntry("item.wax-sealing-kit"),
makeInventoryEntry("item.backpack"),
makeInventoryEntry(selectedScroll.id),
makeInventoryEntry("potion.healing"),
],
equipped: [
makeInventoryEntry(selectedWeapon.id),
makeInventoryEntry(selectedArmour.id),
],
stored: [],
currency: {
gold: 0,
},
rationCount: 3,
lightSources: [makeInventoryEntry("item.lantern")],
},
progressionFlags: [],
};
}

46
src/rules/dice.test.ts Normal file
View File

@@ -0,0 +1,46 @@
import { describe, expect, it } from "vitest";
import { applyRollModifier, roll2D6, rollD3, rollD66, rollDice } from "./dice";
function createSequenceRoller(values: number[]) {
let index = 0;
return () => {
const next = values[index];
index += 1;
return next;
};
}
describe("dice rules", () => {
it("maps d3 rolls from a d6 source", () => {
const result = rollD3(createSequenceRoller([5]));
expect(result.rolls).toEqual([5]);
expect(result.total).toBe(3);
expect(result.modifiedTotal).toBe(3);
});
it("preserves primary and secondary dice for d66", () => {
const result = rollD66(createSequenceRoller([4, 2]));
expect(result.primary).toBe(4);
expect(result.secondary).toBe(2);
expect(result.total).toBe(42);
});
it("applies modifiers with clamping when limits are provided", () => {
const roll = roll2D6(createSequenceRoller([6, 6]));
const modified = applyRollModifier(roll, 3, { min: 2, max: 12 });
expect(modified.modifiedTotal).toBe(12);
expect(modified.clamped).toBe(true);
});
it("routes dice kinds through the shared roller", () => {
const result = rollDice("d6", createSequenceRoller([2]));
expect(result.total).toBe(2);
expect(result.diceKind).toBe("d6");
});
});

113
src/rules/dice.ts Normal file
View File

@@ -0,0 +1,113 @@
import type { DiceKind, RollResult } from "@/types/rules";
export type DiceRoller = (sides: number) => number;
const defaultDiceRoller: DiceRoller = (sides) =>
Math.floor(Math.random() * sides) + 1;
function assertRollInRange(value: number, sides: number) {
if (!Number.isInteger(value) || value < 1 || value > sides) {
throw new Error(`Dice roller returned invalid value ${value} for d${sides}.`);
}
}
function clampTotal(total: number, min: number, max: number) {
return Math.max(min, Math.min(max, total));
}
export function rollD3(roller: DiceRoller = defaultDiceRoller): RollResult {
const value = roller(6);
assertRollInRange(value, 6);
const total = Math.ceil(value / 2);
return {
diceKind: "d3",
rolls: [value],
total,
modifiedTotal: total,
};
}
export function rollD6(roller: DiceRoller = defaultDiceRoller): RollResult {
const value = roller(6);
assertRollInRange(value, 6);
return {
diceKind: "d6",
rolls: [value],
total: value,
modifiedTotal: value,
};
}
export function roll2D6(roller: DiceRoller = defaultDiceRoller): RollResult {
const first = roller(6);
const second = roller(6);
assertRollInRange(first, 6);
assertRollInRange(second, 6);
const total = first + second;
return {
diceKind: "2d6",
rolls: [first, second],
primary: first,
secondary: second,
total,
modifiedTotal: total,
};
}
export function rollD66(roller: DiceRoller = defaultDiceRoller): RollResult {
const primary = roller(6);
const secondary = roller(6);
assertRollInRange(primary, 6);
assertRollInRange(secondary, 6);
const total = primary * 10 + secondary;
return {
diceKind: "d66",
rolls: [primary, secondary],
primary,
secondary,
total,
modifiedTotal: total,
};
}
export function applyRollModifier(
roll: RollResult,
modifier = 0,
limits?: { min: number; max: number },
): RollResult {
if (roll.total === undefined) {
throw new Error("Cannot apply a modifier to a roll without a total.");
}
const nextTotal = roll.total + modifier;
const boundedTotal = limits
? clampTotal(nextTotal, limits.min, limits.max)
: nextTotal;
return {
...roll,
modifier,
modifiedTotal: boundedTotal,
clamped: limits ? boundedTotal !== nextTotal : false,
};
}
export function rollDice(
diceKind: DiceKind,
roller: DiceRoller = defaultDiceRoller,
): RollResult {
switch (diceKind) {
case "d3":
return rollD3(roller);
case "d6":
return rollD6(roller);
case "2d6":
return roll2D6(roller);
case "d66":
return rollD66(roller);
}
}

62
src/rules/tables.test.ts Normal file
View File

@@ -0,0 +1,62 @@
import { describe, expect, it } from "vitest";
import type { TableDefinition } from "@/types/content";
import { lookupTable, resolveTableEntry } from "./tables";
function createSequenceRoller(values: number[]) {
let index = 0;
return () => {
const next = values[index];
index += 1;
return next;
};
}
const d6Table: TableDefinition = {
id: "table.sample",
code: "SAMPLE1",
name: "Sample Table",
category: "generic",
page: 1,
diceKind: "d6",
usesModifiedRangesRule: true,
entries: [
{ key: "1", exact: 1, label: "One" },
{ key: "2-5", min: 2, max: 5, label: "Two to Five" },
{ key: "6", exact: 6, label: "Six" },
],
mvp: true,
};
describe("table lookup rules", () => {
it("finds a matching exact entry", () => {
const result = lookupTable(d6Table, { roller: createSequenceRoller([6]) });
expect(result.entry.label).toBe("Six");
expect(result.roll.total).toBe(6);
});
it("clamps modified results when the table uses modified ranges", () => {
const result = lookupTable(d6Table, {
roller: createSequenceRoller([6]),
modifier: 3,
});
expect(result.entry.label).toBe("Six");
expect(result.roll.modifiedTotal).toBe(6);
expect(result.roll.clamped).toBe(true);
});
it("falls back to the nearest numeric entry for direct resolution", () => {
const result = resolveTableEntry(d6Table, {
diceKind: "d6",
rolls: [0],
total: 4,
modifiedTotal: 7,
});
expect(result.entry.label).toBe("Six");
});
});

110
src/rules/tables.ts Normal file
View File

@@ -0,0 +1,110 @@
import type { TableDefinition, TableEntry } from "@/types/content";
import type { RollResult } from "@/types/rules";
import { applyRollModifier, rollDice, type DiceRoller } from "./dice";
export type TableLookupResult = {
tableId: string;
entryKey: string;
roll: RollResult;
entry: TableEntry;
};
function getNumericEntryValue(entry: TableEntry) {
if (entry.d66 !== undefined) {
return entry.d66;
}
if (entry.exact !== undefined) {
return entry.exact;
}
return undefined;
}
function getEntryBounds(entries: TableEntry[]) {
const values = entries
.flatMap((entry) => {
if (entry.min !== undefined && entry.max !== undefined) {
return [entry.min, entry.max];
}
const exactValue = getNumericEntryValue(entry);
return exactValue !== undefined ? [exactValue] : [];
})
.sort((a, b) => a - b);
if (values.length === 0) {
throw new Error("Cannot compute table bounds for an empty numeric table.");
}
return { min: values[0], max: values[values.length - 1] };
}
function matchesEntry(entry: TableEntry, lookupValue: number) {
if (entry.min !== undefined && entry.max !== undefined) {
return lookupValue >= entry.min && lookupValue <= entry.max;
}
const exactValue = getNumericEntryValue(entry);
return exactValue === lookupValue;
}
function findNearestEntry(entries: TableEntry[], lookupValue: number) {
return entries
.map((entry) => ({ entry, value: getNumericEntryValue(entry) }))
.filter((candidate): candidate is { entry: TableEntry; value: number } => {
return candidate.value !== undefined;
})
.sort((left, right) => {
const distanceDelta =
Math.abs(left.value - lookupValue) - Math.abs(right.value - lookupValue);
return distanceDelta !== 0 ? distanceDelta : left.value - right.value;
})[0]?.entry;
}
export function resolveTableEntry(
table: TableDefinition,
roll: RollResult,
): TableLookupResult {
const lookupValue = roll.modifiedTotal ?? roll.total;
if (lookupValue === undefined) {
throw new Error(`Cannot resolve table ${table.code} without a roll total.`);
}
const matchingEntry = table.entries.find((entry) => matchesEntry(entry, lookupValue));
const fallbackEntry = matchingEntry ?? findNearestEntry(table.entries, lookupValue);
if (!fallbackEntry) {
throw new Error(`No table entry found for ${table.code} with value ${lookupValue}.`);
}
return {
tableId: table.id,
entryKey: fallbackEntry.key,
roll,
entry: fallbackEntry,
};
}
export function lookupTable(
table: TableDefinition,
options?: {
modifier?: number;
roller?: DiceRoller;
},
): TableLookupResult {
const rawRoll = rollDice(table.diceKind, options?.roller);
const roll =
options?.modifier !== undefined
? applyRollModifier(
rawRoll,
options.modifier,
table.usesModifiedRangesRule ? getEntryBounds(table.entries) : undefined,
)
: rawRoll;
return resolveTableEntry(table, roll);
}