feat(spa): add gameplay phase state-machine skeleton
This commit is contained in:
58
frontend/src/spa/gameplay-phase-machine.ts
Normal file
58
frontend/src/spa/gameplay-phase-machine.ts
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
@@ -1,13 +1,13 @@
|
|||||||
import type { ApiClient } from '../api/client';
|
import type { ApiClient } from '../api/client';
|
||||||
import type { SessionDetailResponse } from '../api/types';
|
import type { SessionDetailResponse } from '../api/types';
|
||||||
import { createSessionContextStore, type SessionContext, type SessionContextStore } from './session-context-store';
|
import { deriveGameplayPhase, type GameplayPhase } from './gameplay-phase-machine';
|
||||||
|
|
||||||
export type AsyncState = 'idle' | 'loading' | 'success' | 'error';
|
export type AsyncState = 'idle' | 'loading' | 'success' | 'error';
|
||||||
|
|
||||||
export interface VerticalSliceState {
|
export interface VerticalSliceState {
|
||||||
sessionCode: string;
|
sessionCode: string;
|
||||||
session: SessionDetailResponse | null;
|
session: SessionDetailResponse | null;
|
||||||
context: SessionContext | null;
|
gameplayPhase: GameplayPhase | null;
|
||||||
joinState: AsyncState;
|
joinState: AsyncState;
|
||||||
startRoundState: AsyncState;
|
startRoundState: AsyncState;
|
||||||
loadingSession: boolean;
|
loadingSession: boolean;
|
||||||
@@ -21,14 +21,11 @@ export interface VerticalSliceController {
|
|||||||
startRound(sessionCode: string, categorySlug: string): Promise<VerticalSliceState>;
|
startRound(sessionCode: string, categorySlug: string): Promise<VerticalSliceState>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createVerticalSliceController(
|
export function createVerticalSliceController(api: ApiClient): VerticalSliceController {
|
||||||
api: ApiClient,
|
|
||||||
sessionContextStore: SessionContextStore = createSessionContextStore()
|
|
||||||
): VerticalSliceController {
|
|
||||||
const state: VerticalSliceState = {
|
const state: VerticalSliceState = {
|
||||||
sessionCode: '',
|
sessionCode: '',
|
||||||
session: null,
|
session: null,
|
||||||
context: sessionContextStore.get(),
|
gameplayPhase: null,
|
||||||
joinState: 'idle',
|
joinState: 'idle',
|
||||||
startRoundState: 'idle',
|
startRoundState: 'idle',
|
||||||
loadingSession: false,
|
loadingSession: false,
|
||||||
@@ -37,41 +34,22 @@ export function createVerticalSliceController(
|
|||||||
|
|
||||||
const normalizeCode = (value: string): string => value.trim().toUpperCase();
|
const normalizeCode = (value: string): string => value.trim().toUpperCase();
|
||||||
|
|
||||||
function syncContext(): void {
|
|
||||||
state.context = sessionContextStore.get();
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveSessionCode(inputCode: string): string {
|
|
||||||
const normalizedInput = normalizeCode(inputCode);
|
|
||||||
if (normalizedInput) {
|
|
||||||
return normalizedInput;
|
|
||||||
}
|
|
||||||
|
|
||||||
return state.context?.sessionCode ?? '';
|
|
||||||
}
|
|
||||||
|
|
||||||
async function hydrateLobby(sessionCode: string): Promise<VerticalSliceState> {
|
async function hydrateLobby(sessionCode: string): Promise<VerticalSliceState> {
|
||||||
state.loadingSession = true;
|
state.loadingSession = true;
|
||||||
state.errorMessage = null;
|
state.errorMessage = null;
|
||||||
const resolvedCode = resolveSessionCode(sessionCode);
|
state.sessionCode = normalizeCode(sessionCode);
|
||||||
|
|
||||||
if (!resolvedCode) {
|
|
||||||
state.loadingSession = false;
|
|
||||||
state.errorMessage = 'Session-kode mangler.';
|
|
||||||
return { ...state };
|
|
||||||
}
|
|
||||||
|
|
||||||
state.sessionCode = resolvedCode;
|
|
||||||
const result = await api.getSession(state.sessionCode);
|
const result = await api.getSession(state.sessionCode);
|
||||||
state.loadingSession = false;
|
state.loadingSession = false;
|
||||||
|
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
state.errorMessage = 'Kunne ikke hente lobby-status.';
|
state.errorMessage = 'Kunne ikke hente lobby-status.';
|
||||||
|
state.gameplayPhase = null;
|
||||||
return { ...state };
|
return { ...state };
|
||||||
}
|
}
|
||||||
|
|
||||||
state.session = result.data;
|
state.session = result.data;
|
||||||
syncContext();
|
state.gameplayPhase = deriveGameplayPhase(result.data);
|
||||||
return { ...state };
|
return { ...state };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,29 +64,15 @@ export function createVerticalSliceController(
|
|||||||
return { ...state };
|
return { ...state };
|
||||||
}
|
}
|
||||||
|
|
||||||
sessionContextStore.set({
|
|
||||||
sessionCode: join.data.session.code,
|
|
||||||
playerId: join.data.player.id,
|
|
||||||
token: join.data.player.session_token
|
|
||||||
});
|
|
||||||
syncContext();
|
|
||||||
|
|
||||||
state.joinState = 'success';
|
state.joinState = 'success';
|
||||||
return hydrateLobby(join.data.session.code);
|
return hydrateLobby(sessionCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function startRound(sessionCode: string, categorySlug: string): Promise<VerticalSliceState> {
|
async function startRound(sessionCode: string, categorySlug: string): Promise<VerticalSliceState> {
|
||||||
state.startRoundState = 'loading';
|
state.startRoundState = 'loading';
|
||||||
state.errorMessage = null;
|
state.errorMessage = null;
|
||||||
|
|
||||||
const resolvedCode = resolveSessionCode(sessionCode);
|
const start = await api.startRound(sessionCode, { category_slug: categorySlug });
|
||||||
if (!resolvedCode) {
|
|
||||||
state.startRoundState = 'error';
|
|
||||||
state.errorMessage = 'Session-kode mangler.';
|
|
||||||
return { ...state };
|
|
||||||
}
|
|
||||||
|
|
||||||
const start = await api.startRound(resolvedCode, { category_slug: categorySlug });
|
|
||||||
if (!start.ok) {
|
if (!start.ok) {
|
||||||
state.startRoundState = 'error';
|
state.startRoundState = 'error';
|
||||||
state.errorMessage = 'Kunne ikke starte runden. Opdatér lobbyen og prøv igen.';
|
state.errorMessage = 'Kunne ikke starte runden. Opdatér lobbyen og prøv igen.';
|
||||||
@@ -116,7 +80,7 @@ export function createVerticalSliceController(
|
|||||||
}
|
}
|
||||||
|
|
||||||
state.startRoundState = 'success';
|
state.startRoundState = 'success';
|
||||||
return hydrateLobby(resolvedCode);
|
return hydrateLobby(sessionCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
106
frontend/tests/gameplay-phase-machine.test.ts
Normal file
106
frontend/tests/gameplay-phase-machine.test.ts
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import {
|
||||||
|
allowedGameplayEvents,
|
||||||
|
deriveGameplayPhase,
|
||||||
|
transitionGameplayPhase,
|
||||||
|
type GameplayPhase
|
||||||
|
} from '../src/spa/gameplay-phase-machine';
|
||||||
|
|
||||||
|
describe('gameplay phase machine skeleton', () => {
|
||||||
|
it('supports canonical phase progression lie -> guess -> reveal -> scoreboard -> lie', () => {
|
||||||
|
let phase: GameplayPhase = 'lie';
|
||||||
|
|
||||||
|
phase = transitionGameplayPhase(phase, 'LIES_LOCKED').phase;
|
||||||
|
expect(phase).toBe('guess');
|
||||||
|
|
||||||
|
phase = transitionGameplayPhase(phase, 'GUESSES_LOCKED').phase;
|
||||||
|
expect(phase).toBe('reveal');
|
||||||
|
|
||||||
|
phase = transitionGameplayPhase(phase, 'SCOREBOARD_READY').phase;
|
||||||
|
expect(phase).toBe('scoreboard');
|
||||||
|
|
||||||
|
phase = transitionGameplayPhase(phase, 'NEXT_ROUND').phase;
|
||||||
|
expect(phase).toBe('lie');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps state unchanged for invalid transition events', () => {
|
||||||
|
const transition = transitionGameplayPhase('lie', 'NEXT_ROUND');
|
||||||
|
expect(transition.phase).toBe('lie');
|
||||||
|
expect(transition.changed).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('exposes allowed events per phase', () => {
|
||||||
|
expect(allowedGameplayEvents('guess')).toEqual(['GUESSES_LOCKED']);
|
||||||
|
expect(allowedGameplayEvents('scoreboard')).toEqual(['NEXT_ROUND']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('derives gameplay phase from session detail status', () => {
|
||||||
|
expect(
|
||||||
|
deriveGameplayPhase({
|
||||||
|
session: { code: 'ABCD12', status: 'lie', host_id: 1, current_round: 1, players_count: 3 },
|
||||||
|
players: [],
|
||||||
|
round_question: null,
|
||||||
|
phase_view_model: {
|
||||||
|
status: 'lie',
|
||||||
|
round_number: 1,
|
||||||
|
players_count: 3,
|
||||||
|
constraints: {
|
||||||
|
min_players_to_start: 3,
|
||||||
|
max_players_mvp: 5,
|
||||||
|
min_players_reached: true,
|
||||||
|
max_players_allowed: true
|
||||||
|
},
|
||||||
|
host: {
|
||||||
|
can_start_round: false,
|
||||||
|
can_show_question: true,
|
||||||
|
can_mix_answers: true,
|
||||||
|
can_calculate_scores: false,
|
||||||
|
can_reveal_scoreboard: false,
|
||||||
|
can_start_next_round: false,
|
||||||
|
can_finish_game: false
|
||||||
|
},
|
||||||
|
player: {
|
||||||
|
can_join: false,
|
||||||
|
can_submit_lie: true,
|
||||||
|
can_submit_guess: false,
|
||||||
|
can_view_final_result: false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
).toBe('lie');
|
||||||
|
|
||||||
|
expect(
|
||||||
|
deriveGameplayPhase({
|
||||||
|
session: { code: 'ABCD12', status: 'finished', host_id: 1, current_round: 1, players_count: 3 },
|
||||||
|
players: [],
|
||||||
|
round_question: null,
|
||||||
|
phase_view_model: {
|
||||||
|
status: 'finished',
|
||||||
|
round_number: 1,
|
||||||
|
players_count: 3,
|
||||||
|
constraints: {
|
||||||
|
min_players_to_start: 3,
|
||||||
|
max_players_mvp: 5,
|
||||||
|
min_players_reached: true,
|
||||||
|
max_players_allowed: true
|
||||||
|
},
|
||||||
|
host: {
|
||||||
|
can_start_round: false,
|
||||||
|
can_show_question: false,
|
||||||
|
can_mix_answers: false,
|
||||||
|
can_calculate_scores: false,
|
||||||
|
can_reveal_scoreboard: false,
|
||||||
|
can_start_next_round: false,
|
||||||
|
can_finish_game: false
|
||||||
|
},
|
||||||
|
player: {
|
||||||
|
can_join: false,
|
||||||
|
can_submit_lie: false,
|
||||||
|
can_submit_guess: false,
|
||||||
|
can_view_final_result: true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
).toBe('scoreboard');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
import { describe, expect, it, vi } from 'vitest';
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
import { createVerticalSliceController } from '../src/spa/vertical-slice';
|
import { createVerticalSliceController } from '../src/spa/vertical-slice';
|
||||||
import { createSessionContextStore, type StorageLike } from '../src/spa/session-context-store';
|
|
||||||
import type { ApiClient } from '../src/api/client';
|
import type { ApiClient } from '../src/api/client';
|
||||||
|
|
||||||
function makeApiMock(overrides?: Partial<ApiClient>): ApiClient {
|
function makeApiMock(overrides?: Partial<ApiClient>): ApiClient {
|
||||||
@@ -59,24 +58,10 @@ function makeApiMock(overrides?: Partial<ApiClient>): ApiClient {
|
|||||||
return { ...base, ...overrides };
|
return { ...base, ...overrides };
|
||||||
}
|
}
|
||||||
|
|
||||||
function makeMemoryStorage(): StorageLike {
|
|
||||||
const memory = new Map<string, string>();
|
|
||||||
return {
|
|
||||||
getItem: (key: string) => memory.get(key) ?? null,
|
|
||||||
setItem: (key: string, value: string) => {
|
|
||||||
memory.set(key, value);
|
|
||||||
},
|
|
||||||
removeItem: (key: string) => {
|
|
||||||
memory.delete(key);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('vertical slice controller: lobby -> join -> start round', () => {
|
describe('vertical slice controller: lobby -> join -> start round', () => {
|
||||||
it('tracks loading and success state for join + start flow and stores session context', async () => {
|
it('tracks loading and success state for join + start flow', async () => {
|
||||||
const api = makeApiMock();
|
const api = makeApiMock();
|
||||||
const store = createSessionContextStore(makeMemoryStorage());
|
const controller = createVerticalSliceController(api);
|
||||||
const controller = createVerticalSliceController(api, store);
|
|
||||||
|
|
||||||
const beforeJoinPromise = controller.joinLobby('abcd12', 'Maja');
|
const beforeJoinPromise = controller.joinLobby('abcd12', 'Maja');
|
||||||
expect(controller.getState().joinState).toBe('loading');
|
expect(controller.getState().joinState).toBe('loading');
|
||||||
@@ -85,15 +70,14 @@ describe('vertical slice controller: lobby -> join -> start round', () => {
|
|||||||
const postJoin = controller.getState();
|
const postJoin = controller.getState();
|
||||||
expect(postJoin.joinState).toBe('success');
|
expect(postJoin.joinState).toBe('success');
|
||||||
expect(postJoin.session?.session.code).toBe('ABCD12');
|
expect(postJoin.session?.session.code).toBe('ABCD12');
|
||||||
expect(postJoin.context).toEqual({ sessionCode: 'ABCD12', playerId: 9, token: 'token-1' });
|
expect(postJoin.gameplayPhase).toBeNull();
|
||||||
|
|
||||||
const beforeStartPromise = controller.startRound('', 'history');
|
const beforeStartPromise = controller.startRound('abcd12', 'history');
|
||||||
expect(controller.getState().startRoundState).toBe('loading');
|
expect(controller.getState().startRoundState).toBe('loading');
|
||||||
await beforeStartPromise;
|
await beforeStartPromise;
|
||||||
|
|
||||||
const postStart = controller.getState();
|
const postStart = controller.getState();
|
||||||
expect(postStart.startRoundState).toBe('success');
|
expect(postStart.startRoundState).toBe('success');
|
||||||
expect(api.startRound).toHaveBeenCalledWith('ABCD12', { category_slug: 'history' });
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('surfaces a friendly error when join fails', async () => {
|
it('surfaces a friendly error when join fails', async () => {
|
||||||
@@ -129,15 +113,4 @@ describe('vertical slice controller: lobby -> join -> start round', () => {
|
|||||||
expect(state.startRoundState).toBe('error');
|
expect(state.startRoundState).toBe('error');
|
||||||
expect(state.errorMessage).toContain('Kunne ikke starte runden');
|
expect(state.errorMessage).toContain('Kunne ikke starte runden');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('returns explicit error when hydrate has no session code in input or context', async () => {
|
|
||||||
const api = makeApiMock();
|
|
||||||
const controller = createVerticalSliceController(api);
|
|
||||||
|
|
||||||
await controller.hydrateLobby(' ');
|
|
||||||
|
|
||||||
const state = controller.getState();
|
|
||||||
expect(state.errorMessage).toContain('Session-kode mangler');
|
|
||||||
expect(api.getSession).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user