52 lines
1.2 KiB
TypeScript
52 lines
1.2 KiB
TypeScript
import {
|
|
type Creature,
|
|
type CreatureId,
|
|
calculateInitiative,
|
|
type DomainError,
|
|
type DomainEvent,
|
|
isDomainError,
|
|
rollInitiative,
|
|
setInitiative,
|
|
} from "@initiative/domain";
|
|
import type { EncounterStore } from "./ports.js";
|
|
|
|
export function rollAllInitiativeUseCase(
|
|
store: EncounterStore,
|
|
rollDice: () => number,
|
|
getCreature: (id: CreatureId) => Creature | undefined,
|
|
): DomainEvent[] | DomainError {
|
|
let encounter = store.get();
|
|
const allEvents: DomainEvent[] = [];
|
|
|
|
for (const combatant of encounter.combatants) {
|
|
if (!combatant.creatureId) continue;
|
|
if (combatant.initiative !== undefined) continue;
|
|
|
|
const creature = getCreature(combatant.creatureId);
|
|
if (!creature) continue;
|
|
|
|
const { modifier } = calculateInitiative({
|
|
dexScore: creature.abilities.dex,
|
|
cr: creature.cr,
|
|
initiativeProficiency: creature.initiativeProficiency,
|
|
});
|
|
const value = rollInitiative(rollDice(), modifier);
|
|
|
|
if (isDomainError(value)) {
|
|
return value;
|
|
}
|
|
|
|
const result = setInitiative(encounter, combatant.id, value);
|
|
|
|
if (isDomainError(result)) {
|
|
return result;
|
|
}
|
|
|
|
encounter = result.encounter;
|
|
allEvents.push(...result.events);
|
|
}
|
|
|
|
store.save(encounter);
|
|
return allEvents;
|
|
}
|