Files
weirsoe-party-protocol/frontend/src/spa/gameplay-phase-machine.ts

59 lines
1.3 KiB
TypeScript

import type { SessionDetailResponse } from '../api/types';
export type GameplayPhase = 'lie' | 'guess' | 'reveal' | 'scoreboard';
export type GameplayPhaseEvent =
| 'LIES_LOCKED'
| 'GUESSES_LOCKED'
| 'SCOREBOARD_READY'
| 'NEXT_ROUND';
export interface GameplayTransitionResult {
phase: GameplayPhase;
changed: boolean;
}
const TRANSITIONS: Record<GameplayPhase, Partial<Record<GameplayPhaseEvent, GameplayPhase>>> = {
lie: {
LIES_LOCKED: 'guess'
},
guess: {
GUESSES_LOCKED: 'reveal'
},
reveal: {
SCOREBOARD_READY: 'scoreboard'
},
scoreboard: {
NEXT_ROUND: 'lie'
}
};
export function transitionGameplayPhase(phase: GameplayPhase, event: GameplayPhaseEvent): GameplayTransitionResult {
const next = TRANSITIONS[phase][event] ?? phase;
return {
phase: next,
changed: next !== phase
};
}
export function allowedGameplayEvents(phase: GameplayPhase): GameplayPhaseEvent[] {
return Object.keys(TRANSITIONS[phase]) as GameplayPhaseEvent[];
}
export function deriveGameplayPhase(session: SessionDetailResponse | null): GameplayPhase | null {
const status = session?.session.status;
if (!status) {
return null;
}
if (status === 'lie' || status === 'guess' || status === 'reveal') {
return status;
}
if (status === 'finished') {
return 'scoreboard';
}
return null;
}