Files
21/src/store/gameStore.ts
T

1348 lines
33 KiB
TypeScript

import * as FileSystem from 'expo-file-system/legacy';
import { create } from 'zustand';
import { createJSONStorage, persist, type StateStorage } from 'zustand/middleware';
import { type QualitySetting, isQualitySetting } from '../constants/quality';
import { DEFAULT_DICE_THEME, isDiceTheme } from '../constants/themes';
import { getLowestRankedPlayerIds, rankEntries } from '../services/rankingService';
import { getRollProbability } from '../utils/probability';
export type DicePair = [number, number];
export type GamePhase = 'setup' | 'playing' | 'tie-break' | 'round-summary';
export type RollSource = 'button' | 'shake' | 'rub';
export type GameSettings = {
enableShake: boolean;
enableRub: boolean;
enableMagicNumber: boolean;
endRoundPotFactor: number;
qualitySetting: QualitySetting;
};
export type Player = {
id: string;
name: string;
theme: string;
magicNumber: number | null;
drinksConsumed: number;
lastScore: number | null;
lastDice: DicePair | null;
};
export type TurnResult = {
playerId: string;
playerName: string;
score: number;
dice: DicePair;
rollsUsed: number;
probability: number;
badges: string[];
};
export type RankedTurn = TurnResult & {
rankTier: number;
rankValue: number;
};
export type RoundSummary = {
winnerName: string;
loserName: string;
basePotValue: number;
potValue: number;
appliedPotFactor: number;
endedBy31: boolean;
tieBreakRounds: number;
standings: RankedTurn[];
};
export type RollOutcome = {
score: number;
dice: DicePair;
probability: number;
potDelta: number;
specials: string[];
rareEvents: RareStatEvent[];
consecutiveSameCount: number;
endedTurn: boolean;
endedRound: boolean;
};
export type RollRecord = {
playerId: string;
playerName: string;
round: number;
phase: 'playing' | 'tie-break';
dice: DicePair;
score: number;
probability: number;
turnRollIndex: number;
timestamp: number;
};
export type RareStatEventKind = 'same-round-3' | 'same-game-6';
export type RareStatEvent = {
id: string;
kind: RareStatEventKind;
playerId: string;
playerName: string;
score: number;
count: number;
round: number;
probability: number;
message: string;
timestamp: number;
};
export type PlayerRollStats = {
totalRolls: number;
scoreCounts: Record<number, number>;
roundScoreCounts: Record<number, Record<number, number>>;
};
export type AllTimeLeaderboard = Record<string, number>;
export type SavedProfile = {
name: string;
magicNumber: number;
theme: string;
isDefault: boolean;
};
type SetupPayload = {
playerNames: string[];
magicNumbers: (number | null)[];
playerThemes: string[];
settings: GameSettings;
};
type GameStoreState = {
phase: GamePhase;
players: Player[];
settings: GameSettings;
allTimeLeaderboard: AllTimeLeaderboard;
savedProfiles: SavedProfile[];
persistedMagicNumberEnabled: boolean;
persistedQualitySetting: QualitySetting;
round: number;
pot: number;
currentPlayerIndex: number;
currentRollCount: number;
firstPlayerRollLimit: number | null;
currentDice: DicePair | null;
currentScore: number | null;
pendingRoll: boolean;
awaitingDecision: boolean;
awaitingNextPlayer: boolean;
turns: TurnResult[];
roundSummary: RoundSummary | null;
roundSummaryApplied: boolean;
lastRollSource: RollSource | null;
allRolls: RollRecord[];
playerRollStats: Record<string, PlayerRollStats>;
rareEvents: RareStatEvent[];
tieBreakPlayerIds: string[];
tieBreakTurns: TurnResult[];
tieBreakRound: number;
tieBreakBaseTurns: TurnResult[];
tieBreakEndedBy31: boolean;
setupGame: (payload: SetupPayload) => void;
requestRoll: (source?: RollSource) => boolean;
receiveRollResult: (dice: DicePair) => RollOutcome | null;
stopCurrentTurn: () => void;
goToNextPlayer: () => void;
resetPlayerDrinks: (playerId: string) => void;
resetAllTimePlayer: (playerName: string) => void;
saveProfile: (profileName: string, magicNumber: number, theme: string) => void;
toggleDefaultProfile: (profileName: string) => void;
removeProfile: (profileName: string) => void;
setPersistedMagicNumberEnabled: (enabled: boolean) => void;
setPersistedQualitySetting: (qualitySetting: QualitySetting) => void;
persistentPlayerThemes: string[];
setPersistedPlayerTheme: (index: number, theme: string) => void;
startNextRound: () => void;
openRoundSummary: () => void;
resetGame: () => void;
};
const defaultSettings: GameSettings = {
enableShake: true,
enableRub: true,
enableMagicNumber: false,
endRoundPotFactor: 1,
qualitySetting: 'high',
};
export const getScoreFromDice = (dice: DicePair): number => {
const [first, second] = dice;
const high = Math.max(first, second);
const low = Math.min(first, second);
return high * 10 + low;
};
const createPlayerId = (name: string, index: number): string => {
return `${name.toLowerCase().replace(/\s+/g, '-')}-${index}-${Date.now()}`;
};
const normalizeMagicNumber = (value: number | null): number | null => {
if (value === null || !Number.isInteger(value)) {
return null;
}
if (value < 11 || value > 66 || value === 31) {
return null;
}
const tens = Math.floor(value / 10);
const units = value % 10;
if (tens < units) {
return null;
}
return value;
};
const normalizeEndRoundPotFactor = (value: number): number => {
if (!Number.isFinite(value) || value <= 0) {
return 1;
}
return value;
};
const normalizeQualitySetting = (value: QualitySetting): QualitySetting => {
if (isQualitySetting(value)) {
return value;
}
return 'high';
};
const roundDrinkValue = (value: number): number => {
return Math.round(value * 100) / 100;
};
const computeEndRoundPotValue = (basePotValue: number, appliedPotFactor: number): number => {
const scaledValue = basePotValue * appliedPotFactor;
if (appliedPotFactor < 1) {
return Math.ceil(scaledValue);
}
return roundDrinkValue(scaledValue);
};
const sanitizeDice = (dice: DicePair): DicePair => {
const first = Math.min(6, Math.max(1, Math.round(dice[0])));
const second = Math.min(6, Math.max(1, Math.round(dice[1])));
return [first, second];
};
const getPotDeltaAndSpecials = (
score: number,
dice: DicePair,
enableMagicNumber: boolean,
playerMagicNumber: number | null,
allow31PotBonus = true,
) => {
let potDelta = 0;
const specials: string[] = [];
if (score === 21) {
potDelta += 10;
specials.push('21 (+10 pot)');
}
if (score === 31 && allow31PotBonus) {
potDelta += 10;
specials.push('31 (+10 pot)');
} else if (score === 31) {
specials.push('31 (bonus pot déjà accordé)');
}
if (dice[0] === dice[1]) {
const doubleBonus = dice[0] * 2;
potDelta += doubleBonus;
specials.push(`Double ${dice[0]} (+${doubleBonus} pot)`);
}
if (enableMagicNumber && playerMagicNumber !== null && score === playerMagicNumber) {
potDelta += 10;
specials.push('Chiffre magique (+10 pot)');
}
return { potDelta, specials };
};
const isDoubleScore = (score: number): boolean => {
const tens = Math.floor(score / 10);
const units = score % 10;
return tens === units;
};
const buildStandings = (
turns: TurnResult[],
players: Player[],
settings: GameSettings,
): RankedTurn[] => {
const magicNumberByPlayerId = players.reduce<Record<string, number | null>>(
(accumulator, player) => {
accumulator[player.id] = player.magicNumber;
return accumulator;
},
{},
);
return rankEntries(turns, {
enableMagicNumber: settings.enableMagicNumber,
magicNumberByPlayerId,
}) as RankedTurn[];
};
const getLowestTiePlayerIds = (standings: RankedTurn[]): string[] => {
return getLowestRankedPlayerIds(standings);
};
const rotatePlayersFromIndex = (players: Player[], startIndex: number): Player[] => {
if (startIndex <= 0 || startIndex >= players.length) {
return players;
}
return [...players.slice(startIndex), ...players.slice(0, startIndex)];
};
const getInitialState = (): Omit<
GameStoreState,
| 'setupGame'
| 'requestRoll'
| 'receiveRollResult'
| 'stopCurrentTurn'
| 'goToNextPlayer'
| 'resetPlayerDrinks'
| 'resetAllTimePlayer'
| 'saveProfile'
| 'toggleDefaultProfile'
| 'removeProfile'
| 'setPersistedMagicNumberEnabled'
| 'setPersistedQualitySetting'
| 'setPersistedPlayerTheme'
| 'startNextRound'
| 'openRoundSummary'
| 'resetGame'
> => ({
phase: 'setup',
players: [],
settings: defaultSettings,
allTimeLeaderboard: {},
savedProfiles: [],
persistentPlayerThemes: [],
persistedMagicNumberEnabled: false,
persistedQualitySetting: 'high',
round: 1,
pot: 0,
currentPlayerIndex: 0,
currentRollCount: 0,
firstPlayerRollLimit: null,
currentDice: null,
currentScore: null,
pendingRoll: false,
awaitingDecision: false,
awaitingNextPlayer: false,
turns: [],
roundSummary: null,
roundSummaryApplied: false,
lastRollSource: null,
allRolls: [],
playerRollStats: {},
rareEvents: [],
tieBreakPlayerIds: [],
tieBreakTurns: [],
tieBreakRound: 0,
tieBreakBaseTurns: [],
tieBreakEndedBy31: false,
});
const createEmptyPlayerRollStats = (): PlayerRollStats => ({
totalRolls: 0,
scoreCounts: {},
roundScoreCounts: {},
});
const getPersistFileUri = (storageKey: string): string | null => {
const baseDirectory = FileSystem.documentDirectory ?? FileSystem.cacheDirectory;
if (!baseDirectory) {
return null;
}
return `${baseDirectory}zustand-${storageKey}.json`;
};
const fileStateStorage: StateStorage = {
getItem: async (name) => {
const fileUri = getPersistFileUri(name);
if (!fileUri) {
return null;
}
try {
return await FileSystem.readAsStringAsync(fileUri);
} catch {
return null;
}
},
setItem: async (name, value) => {
const fileUri = getPersistFileUri(name);
if (!fileUri) {
return;
}
try {
await FileSystem.writeAsStringAsync(fileUri, value);
} catch {
return;
}
},
removeItem: async (name) => {
const fileUri = getPersistFileUri(name);
if (!fileUri) {
return;
}
try {
await FileSystem.deleteAsync(fileUri, { idempotent: true });
} catch {
return;
}
},
};
const scoreSingleRollProbability = (score: number): number => {
return isDoubleScore(score) ? 1 / 36 : 2 / 36;
};
const formatProbabilityPercent = (probability: number): string => {
const percent = probability * 100;
if (percent < 0.01) {
return `${percent.toFixed(4)}%`;
}
if (percent < 0.1) {
return `${percent.toFixed(3)}%`;
}
return `${percent.toFixed(2)}%`;
};
const buildRareStatMessage = (
kind: RareStatEventKind,
playerName: string,
score: number,
count: number,
probability: number,
round: number,
): string => {
if (kind === 'same-round-3') {
return `⚡ ${playerName} a fait ${score} x${count} sur le tour ${round} (proba ≈ ${formatProbabilityPercent(
probability,
)}).`;
}
return `💥 ${playerName} a fait ${score} x${count} sur toute la partie (proba ≈ ${formatProbabilityPercent(
probability,
)}).`;
};
const incrementScoreCount = (
counts: Record<number, number>,
score: number,
): Record<number, number> => {
return {
...counts,
[score]: (counts[score] ?? 0) + 1,
};
};
const getConsecutiveSameScoreCount = (
allRolls: RollRecord[],
playerId: string,
score: number,
): number => {
let count = 1;
for (let index = allRolls.length - 1; index >= 0; index -= 1) {
const previous = allRolls[index];
if (previous.playerId !== playerId) {
continue;
}
if (previous.score === score) {
count += 1;
continue;
}
break;
}
return count;
};
const trackRollStatistics = (
state: GameStoreState,
player: Player,
dice: DicePair,
score: number,
probability: number,
) => {
const playerStats = state.playerRollStats[player.id] ?? createEmptyPlayerRollStats();
const roundCounts = playerStats.roundScoreCounts[state.round] ?? {};
const nextScoreCounts = incrementScoreCount(playerStats.scoreCounts, score);
const nextRoundCounts = incrementScoreCount(roundCounts, score);
const nextPlayerStats: PlayerRollStats = {
totalRolls: playerStats.totalRolls + 1,
scoreCounts: nextScoreCounts,
roundScoreCounts: {
...playerStats.roundScoreCounts,
[state.round]: nextRoundCounts,
},
};
const nextPlayerRollStats = {
...state.playerRollStats,
[player.id]: nextPlayerStats,
};
const turnRollIndex = state.currentRollCount + 1;
const timestamp = Date.now();
const record: RollRecord = {
playerId: player.id,
playerName: player.name,
round: state.round,
phase: state.phase === 'tie-break' ? 'tie-break' : 'playing',
dice,
score,
probability,
turnRollIndex,
timestamp,
};
const nextAllRolls = [...state.allRolls, record];
const newRareEvents: RareStatEvent[] = [];
const singleRollProbability = scoreSingleRollProbability(score);
const roundCount = nextRoundCounts[score] ?? 0;
if (roundCount === 3) {
const eventProbability = Math.pow(singleRollProbability, 3);
newRareEvents.push({
id: `${player.id}-same-round-3-${score}-${state.round}-${timestamp}`,
kind: 'same-round-3',
playerId: player.id,
playerName: player.name,
score,
count: roundCount,
round: state.round,
probability: eventProbability,
message: buildRareStatMessage(
'same-round-3',
player.name,
score,
roundCount,
eventProbability,
state.round,
),
timestamp,
});
}
const gameCount = nextScoreCounts[score] ?? 0;
if (gameCount === 6) {
const eventProbability = Math.pow(singleRollProbability, 6);
newRareEvents.push({
id: `${player.id}-same-game-6-${score}-${state.round}-${timestamp}`,
kind: 'same-game-6',
playerId: player.id,
playerName: player.name,
score,
count: gameCount,
round: state.round,
probability: eventProbability,
message: buildRareStatMessage(
'same-game-6',
player.name,
score,
gameCount,
eventProbability,
state.round,
),
timestamp,
});
}
const nextRareEvents = [...state.rareEvents, ...newRareEvents];
return {
nextAllRolls,
nextPlayerRollStats,
nextRareEvents,
newRareEvents,
};
};
export const useGameStore = create<GameStoreState>()(
persist(
(set, get) => {
const finishRound = (
turns: TurnResult[],
endedBy31: boolean,
loserIdOverride?: string,
) => {
const state = get();
if (turns.length === 0) {
return;
}
let standings = buildStandings(turns, state.players, state.settings);
const winner = standings[0];
let loser = standings[standings.length - 1];
if (loserIdOverride) {
const forcedLoser = standings.find((entry) => entry.playerId === loserIdOverride);
if (forcedLoser) {
loser = forcedLoser;
standings = [
...standings.filter((entry) => entry.playerId !== forcedLoser.playerId),
forcedLoser,
];
}
}
const basePotValue = state.pot;
const appliedPotFactor = normalizeEndRoundPotFactor(
state.settings.endRoundPotFactor,
);
const potValue = computeEndRoundPotValue(basePotValue, appliedPotFactor);
set({
phase: 'playing',
pot: basePotValue,
pendingRoll: false,
awaitingDecision: false,
awaitingNextPlayer: false,
tieBreakPlayerIds: [],
tieBreakTurns: [],
tieBreakBaseTurns: [],
tieBreakEndedBy31: false,
lastRollSource: null,
roundSummaryApplied: false,
roundSummary: {
winnerName: winner.playerName,
loserName: loser.playerName,
basePotValue,
potValue,
appliedPotFactor,
endedBy31,
tieBreakRounds: state.tieBreakRound,
standings,
},
});
};
const startTieBreak = (
playerIds: string[],
baseTurns: TurnResult[],
endedBy31: boolean,
round: number,
) => {
if (playerIds.length <= 1) {
finishRound(baseTurns, endedBy31, playerIds[0]);
return;
}
const state = get();
const firstPlayerIndex = state.players.findIndex((player) => player.id === playerIds[0]);
set({
phase: 'tie-break',
tieBreakPlayerIds: playerIds,
tieBreakTurns: [],
tieBreakRound: round,
tieBreakBaseTurns: baseTurns,
tieBreakEndedBy31: endedBy31,
currentPlayerIndex: Math.max(0, firstPlayerIndex),
currentRollCount: 0,
firstPlayerRollLimit: 1,
currentScore: null,
pendingRoll: false,
awaitingDecision: false,
awaitingNextPlayer: false,
lastRollSource: null,
});
};
const resolveMainRoundEnd = (turns: TurnResult[], endedBy31: boolean) => {
const state = get();
const standings = buildStandings(turns, state.players, state.settings);
const tiedLowestIds = getLowestTiePlayerIds(standings);
if (tiedLowestIds.length > 1) {
startTieBreak(tiedLowestIds, turns, endedBy31, 1);
return;
}
finishRound(turns, endedBy31, tiedLowestIds[0]);
};
const finalizeMainTurn = () => {
const state = get();
if (state.phase !== 'playing') {
return;
}
const currentPlayer = state.players[state.currentPlayerIndex];
if (!currentPlayer || state.currentScore === null || !state.currentDice) {
return;
}
const turnSpecials = getPotDeltaAndSpecials(
state.currentScore,
state.currentDice,
state.settings.enableMagicNumber,
currentPlayer.magicNumber,
!state.turns.some((turn) => turn.score === 31),
);
const turn: TurnResult = {
playerId: currentPlayer.id,
playerName: currentPlayer.name,
score: state.currentScore,
dice: state.currentDice,
rollsUsed: state.currentRollCount,
probability: getRollProbability(state.currentDice),
badges: turnSpecials.specials,
};
const turns = [...state.turns, turn];
const nextPot = state.pot + turnSpecials.potDelta;
const computedFirstLimit =
state.firstPlayerRollLimit ??
(state.currentPlayerIndex === 0 ? state.currentRollCount : null);
const isLastPlayer = state.currentPlayerIndex >= state.players.length - 1;
const shouldEndRound = isLastPlayer;
if (shouldEndRound) {
set({
turns,
pot: nextPot,
firstPlayerRollLimit: computedFirstLimit,
pendingRoll: false,
awaitingDecision: false,
awaitingNextPlayer: false,
});
resolveMainRoundEnd(turns, false);
return;
}
set({
turns,
pot: nextPot,
firstPlayerRollLimit: computedFirstLimit,
pendingRoll: false,
awaitingDecision: false,
awaitingNextPlayer: true,
lastRollSource: null,
});
};
return {
...getInitialState(),
setupGame: ({ playerNames, magicNumbers, playerThemes, settings }) => {
const cleanNames = playerNames.map((name) => name.trim()).filter(Boolean);
if (cleanNames.length < 2) {
return;
}
const normalizedSettings: GameSettings = {
enableShake: settings.enableShake,
enableRub: settings.enableRub,
enableMagicNumber: settings.enableMagicNumber,
endRoundPotFactor: normalizeEndRoundPotFactor(settings.endRoundPotFactor),
qualitySetting: normalizeQualitySetting(settings.qualitySetting),
};
const players = cleanNames.map((name, index) => ({
id: createPlayerId(name, index),
name,
theme: isDiceTheme(playerThemes[index]) ? playerThemes[index] : DEFAULT_DICE_THEME,
magicNumber: normalizedSettings.enableMagicNumber
? normalizeMagicNumber(magicNumbers[index] ?? null)
: null,
drinksConsumed: 0,
lastScore: null,
lastDice: null,
}));
const playerRollStats = players.reduce<Record<string, PlayerRollStats>>(
(accumulator, player) => {
accumulator[player.id] = createEmptyPlayerRollStats();
return accumulator;
},
{},
);
set({
phase: 'playing',
players,
settings: normalizedSettings,
persistedMagicNumberEnabled: normalizedSettings.enableMagicNumber,
persistedQualitySetting: normalizedSettings.qualitySetting,
persistentPlayerThemes: playerThemes,
round: 1,
pot: 2,
currentPlayerIndex: 0,
currentRollCount: 0,
firstPlayerRollLimit: null,
currentDice: null,
currentScore: null,
pendingRoll: false,
awaitingDecision: false,
awaitingNextPlayer: false,
turns: [],
roundSummary: null,
roundSummaryApplied: false,
lastRollSource: null,
allRolls: [],
playerRollStats,
rareEvents: [],
tieBreakPlayerIds: [],
tieBreakTurns: [],
tieBreakRound: 0,
tieBreakBaseTurns: [],
tieBreakEndedBy31: false,
});
},
requestRoll: (source = 'button') => {
const state = get();
if (
state.phase === 'setup' ||
state.phase === 'round-summary' ||
state.awaitingNextPlayer ||
Boolean(state.roundSummary)
) {
return false;
}
if (state.phase === 'tie-break') {
const canRoll = !state.pendingRoll && state.currentRollCount === 0;
if (!canRoll) {
return false;
}
set({
pendingRoll: true,
awaitingDecision: false,
awaitingNextPlayer: false,
lastRollSource: source,
});
return true;
}
const maxRolls = state.firstPlayerRollLimit ?? 3;
const canRoll =
!state.pendingRoll &&
state.currentRollCount < maxRolls &&
(state.currentRollCount === 0 || state.awaitingDecision);
if (!canRoll) {
return false;
}
set({
pendingRoll: true,
awaitingDecision: false,
awaitingNextPlayer: false,
lastRollSource: source,
});
return true;
},
receiveRollResult: (dice) => {
const state = get();
if (
(state.phase !== 'playing' && state.phase !== 'tie-break') ||
!state.pendingRoll
) {
return null;
}
const currentPlayer = state.players[state.currentPlayerIndex];
if (!currentPlayer) {
set({ pendingRoll: false });
return null;
}
const normalizedDice = sanitizeDice(dice);
const score = getScoreFromDice(normalizedDice);
const probability = getRollProbability(normalizedDice);
const consecutiveSameCount = getConsecutiveSameScoreCount(
state.allRolls,
currentPlayer.id,
score,
);
const trackedStats = trackRollStatistics(
state,
currentPlayer,
normalizedDice,
score,
probability,
);
if (state.phase === 'tie-break') {
const tieTurn: TurnResult = {
playerId: currentPlayer.id,
playerName: currentPlayer.name,
score,
dice: normalizedDice,
rollsUsed: 1,
probability,
badges: [`Départage ${state.tieBreakRound}`],
};
const updatedTieTurns = [...state.tieBreakTurns, tieTurn];
const currentTieIndex = state.tieBreakPlayerIds.findIndex(
(playerId) => playerId === currentPlayer.id,
);
const hasMorePlayers = currentTieIndex < state.tieBreakPlayerIds.length - 1;
if (hasMorePlayers) {
const nextPlayerId = state.tieBreakPlayerIds[currentTieIndex + 1];
const nextPlayerIndex = state.players.findIndex(
(player) => player.id === nextPlayerId,
);
set({
allRolls: trackedStats.nextAllRolls,
playerRollStats: trackedStats.nextPlayerRollStats,
rareEvents: trackedStats.nextRareEvents,
tieBreakTurns: updatedTieTurns,
currentPlayerIndex: Math.max(0, nextPlayerIndex),
currentRollCount: 0,
currentScore: null,
pendingRoll: false,
awaitingDecision: false,
lastRollSource: null,
players: state.players.map((player, index) => {
if (index === state.currentPlayerIndex) {
return {
...player,
lastScore: score,
lastDice: normalizedDice,
};
}
return player;
}),
});
} else {
const lowestScore = Math.min(...updatedTieTurns.map((turn) => turn.score));
const tiedAgainIds = updatedTieTurns
.filter((turn) => turn.score === lowestScore)
.map((turn) => turn.playerId);
if (tiedAgainIds.length === 1) {
set({
allRolls: trackedStats.nextAllRolls,
playerRollStats: trackedStats.nextPlayerRollStats,
rareEvents: trackedStats.nextRareEvents,
tieBreakTurns: updatedTieTurns,
players: state.players.map((player, index) => {
if (index === state.currentPlayerIndex) {
return {
...player,
lastScore: score,
lastDice: normalizedDice,
};
}
return player;
}),
});
finishRound(
state.tieBreakBaseTurns,
state.tieBreakEndedBy31,
tiedAgainIds[0],
);
} else {
const firstNextId = tiedAgainIds[0];
const firstNextIndex = state.players.findIndex(
(player) => player.id === firstNextId,
);
set({
allRolls: trackedStats.nextAllRolls,
playerRollStats: trackedStats.nextPlayerRollStats,
rareEvents: trackedStats.nextRareEvents,
tieBreakPlayerIds: tiedAgainIds,
tieBreakTurns: [],
tieBreakRound: state.tieBreakRound + 1,
currentPlayerIndex: Math.max(0, firstNextIndex),
currentRollCount: 0,
currentScore: null,
pendingRoll: false,
awaitingDecision: false,
lastRollSource: null,
players: state.players.map((player, index) => {
if (index === state.currentPlayerIndex) {
return {
...player,
lastScore: score,
lastDice: normalizedDice,
};
}
return player;
}),
});
}
}
return {
score,
dice: normalizedDice,
probability,
potDelta: 0,
specials: ['Départage en cours'],
rareEvents: trackedStats.newRareEvents,
consecutiveSameCount,
endedTurn: true,
endedRound: get().phase === 'round-summary',
};
}
const { potDelta, specials } = getPotDeltaAndSpecials(
score,
normalizedDice,
state.settings.enableMagicNumber,
currentPlayer.magicNumber,
!state.turns.some((turn) => turn.score === 31),
);
const endedBy31 = score === 31;
const nextRollCount = state.currentRollCount + 1;
const maxRolls = state.firstPlayerRollLimit ?? 3;
set({
allRolls: trackedStats.nextAllRolls,
playerRollStats: trackedStats.nextPlayerRollStats,
rareEvents: trackedStats.nextRareEvents,
currentDice: normalizedDice,
currentScore: score,
currentRollCount: nextRollCount,
pendingRoll: false,
awaitingDecision: false,
players: state.players.map((player, index) => {
if (index === state.currentPlayerIndex) {
return {
...player,
lastScore: score,
lastDice: normalizedDice,
};
}
return player;
}),
});
const endedTurn = endedBy31 || nextRollCount >= maxRolls;
if (endedTurn) {
finalizeMainTurn();
} else {
set({ awaitingDecision: true });
}
return {
score,
dice: normalizedDice,
probability,
potDelta,
specials,
rareEvents: trackedStats.newRareEvents,
consecutiveSameCount,
endedTurn,
endedRound: get().phase === 'round-summary',
};
},
stopCurrentTurn: () => {
const state = get();
if (
state.phase !== 'playing' ||
state.awaitingNextPlayer ||
state.pendingRoll ||
state.currentRollCount === 0
) {
return;
}
finalizeMainTurn();
},
goToNextPlayer: () => {
const state = get();
if (state.phase !== 'playing' || !state.awaitingNextPlayer) {
return;
}
if (state.currentPlayerIndex >= state.players.length - 1) {
return;
}
set({
currentPlayerIndex: state.currentPlayerIndex + 1,
currentRollCount: 0,
currentScore: null,
currentDice: null,
pendingRoll: false,
awaitingDecision: false,
awaitingNextPlayer: false,
lastRollSource: null,
});
},
resetPlayerDrinks: (playerId) => {
const state = get();
set({
players: state.players.map((player) => {
if (player.id === playerId) {
return {
...player,
drinksConsumed: 0,
};
}
return player;
}),
});
},
resetAllTimePlayer: (playerName) => {
const state = get();
if (!(playerName in state.allTimeLeaderboard)) {
return;
}
const nextLeaderboard = { ...state.allTimeLeaderboard };
delete nextLeaderboard[playerName];
set({
allTimeLeaderboard: nextLeaderboard,
});
},
saveProfile: (profileName, magicNumber, theme) => {
const cleanName = profileName.trim();
const normalizedMagicNumber = normalizeMagicNumber(magicNumber);
const normalizedTheme = isDiceTheme(theme) ? theme : DEFAULT_DICE_THEME;
if (!cleanName || normalizedMagicNumber === null) {
return;
}
const state = get();
const existingProfile = state.savedProfiles.find(
(profile) => profile.name === cleanName,
);
if (existingProfile) {
set({
savedProfiles: state.savedProfiles.map((profile) => {
if (profile.name === cleanName) {
return {
...profile,
magicNumber: normalizedMagicNumber,
theme: normalizedTheme,
};
}
return profile;
}),
});
return;
}
set({
savedProfiles: [
...state.savedProfiles,
{
name: cleanName,
magicNumber: normalizedMagicNumber,
theme: normalizedTheme,
isDefault: false,
},
],
});
},
toggleDefaultProfile: (profileName) => {
const state = get();
set({
savedProfiles: state.savedProfiles.map((profile) => {
if (profile.name === profileName) {
return {
...profile,
isDefault: !profile.isDefault,
};
}
return profile;
}),
});
},
removeProfile: (profileName) => {
const state = get();
set({
savedProfiles: state.savedProfiles.filter(
(profile) => profile.name !== profileName,
),
});
},
setPersistedMagicNumberEnabled: (enabled) => {
set({
persistedMagicNumberEnabled: enabled,
});
},
setPersistedQualitySetting: (qualitySetting) => {
const normalizedQuality = normalizeQualitySetting(qualitySetting);
set((state) => ({
persistedQualitySetting: normalizedQuality,
settings: {
...state.settings,
qualitySetting: normalizedQuality,
},
}));
},
setPersistedPlayerTheme: (index, theme) => {
set((state) => {
const next = [...state.persistentPlayerThemes];
next[index] = isDiceTheme(theme) ? theme : DEFAULT_DICE_THEME;
return { persistentPlayerThemes: next };
});
},
startNextRound: () => {
const state = get();
if (state.players.length < 2) {
return;
}
const lastRoundLoserId = state.roundSummary?.standings[
state.roundSummary.standings.length - 1
]?.playerId;
const nextStartingPlayerIndex = lastRoundLoserId
? state.players.findIndex((player) => player.id === lastRoundLoserId)
: -1;
const rotatedPlayers = rotatePlayersFromIndex(
state.players,
nextStartingPlayerIndex > -1 ? nextStartingPlayerIndex : 0,
);
set({
phase: 'playing',
round: state.round + 1,
pot: 2,
currentPlayerIndex: 0,
currentRollCount: 0,
firstPlayerRollLimit: null,
currentScore: null,
pendingRoll: false,
awaitingDecision: false,
awaitingNextPlayer: false,
turns: [],
roundSummary: null,
roundSummaryApplied: false,
lastRollSource: null,
tieBreakPlayerIds: [],
tieBreakTurns: [],
tieBreakRound: 0,
tieBreakBaseTurns: [],
tieBreakEndedBy31: false,
players: rotatedPlayers.map((player) => ({
...player,
lastScore: null,
lastDice: null,
})),
});
},
openRoundSummary: () => {
const state = get();
if (!state.roundSummary) {
return;
}
const loser = state.roundSummary.standings[state.roundSummary.standings.length - 1];
let nextPlayers = state.players;
let nextAllTimeLeaderboard = state.allTimeLeaderboard;
const summaryPotValue = state.roundSummary.potValue;
if (!state.roundSummaryApplied && loser && summaryPotValue > 0) {
nextPlayers = state.players.map((player) => {
if (player.id === loser.playerId) {
return {
...player,
drinksConsumed: roundDrinkValue(
player.drinksConsumed + summaryPotValue,
),
};
}
return player;
});
nextAllTimeLeaderboard = {
...state.allTimeLeaderboard,
[loser.playerName]: roundDrinkValue(
(state.allTimeLeaderboard[loser.playerName] ?? 0) + summaryPotValue,
),
};
}
set({
phase: 'round-summary',
players: nextPlayers,
allTimeLeaderboard: nextAllTimeLeaderboard,
roundSummaryApplied: true,
pendingRoll: false,
awaitingDecision: false,
awaitingNextPlayer: false,
});
},
resetGame: () => {
set((state) => ({
...getInitialState(),
allTimeLeaderboard: state.allTimeLeaderboard,
savedProfiles: state.savedProfiles,
persistedMagicNumberEnabled: state.persistedMagicNumberEnabled,
persistedQualitySetting: state.persistedQualitySetting,
persistentPlayerThemes: state.persistentPlayerThemes,
settings: {
...defaultSettings,
enableMagicNumber: state.persistedMagicNumberEnabled,
qualitySetting: state.persistedQualitySetting,
},
}));
},
};
},
{
name: 'game-store',
storage: createJSONStorage(() => fileStateStorage),
partialize: (state) => ({
allTimeLeaderboard: state.allTimeLeaderboard,
savedProfiles: state.savedProfiles,
persistedMagicNumberEnabled: state.persistedMagicNumberEnabled,
persistedQualitySetting: state.persistedQualitySetting,
persistentPlayerThemes: state.persistentPlayerThemes,
}),
},
),
);