Refine setup flow and round resolution: reorderable players, profile quick-add, deferred summary scoring, and non-stacking 31 pot bonus #3

Merged
admin-backup merged 3 commits from copilot/modify-game-configuration-features into main 2026-04-12 14:02:27 +02:00
5 changed files with 232 additions and 92 deletions

No files matched your search

+2 -2
View File
@@ -13,7 +13,7 @@ const rules = [
'Chaque joueur garde son dernier lancer, pas son meilleur lancer.', 'Chaque joueur garde son dernier lancer, pas son meilleur lancer.',
'Le plus petit score boit tout le pot commun en fin de tour.', 'Le plus petit score boit tout le pot commun en fin de tour.',
'21 : meilleur score normal (+10 dans le pot).', '21 : meilleur score normal (+10 dans le pot).',
'31 : pire score (+10 dans le pot) et fin du tour du joueur uniquement (la manche continue).', '31 : pire score (+10 dans le pot une seule fois par manche) et fin du tour du joueur uniquement (la manche continue).',
'Priorités de score: chiffre magique > 21 > 66 > 55 > 44 > 33 > 22 > 11 > les autres > 31.', 'Priorités de score: chiffre magique > 21 > 66 > 55 > 44 > 33 > 22 > 11 > les autres > 31.',
'Doubles : 11(+2), 22(+4), 33(+6), 44(+8), 55(+10), 66(+12) dans le pot.', 'Doubles : 11(+2), 22(+4), 33(+6), 44(+8), 55(+10), 66(+12) dans le pot.',
'Chiffre magique : défini une fois au setup pour chaque joueur (11 à 66, sauf 31). Quand un joueur le fait, +10 dans le pot.', 'Chiffre magique : défini une fois au setup pour chaque joueur (11 à 66, sauf 31). Quand un joueur le fait, +10 dans le pot.',
@@ -81,4 +81,4 @@ const styles = StyleSheet.create({
...presets.text.button, ...presets.text.button,
fontWeight: textWeight.bold, fontWeight: textWeight.bold,
}, },
}); });
+27
View File
@@ -1,8 +1,11 @@
import { NativeStackScreenProps } from '@react-navigation/native-stack'; import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { useFocusEffect } from '@react-navigation/native';
import { Accelerometer } from 'expo-sensors'; import { Accelerometer } from 'expo-sensors';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { import {
ActivityIndicator, ActivityIndicator,
Alert,
BackHandler,
LayoutChangeEvent, LayoutChangeEvent,
PanResponder, PanResponder,
Pressable, Pressable,
@@ -66,6 +69,7 @@ export function GameScreen({ navigation }: GameScreenProps) {
goToNextPlayer, goToNextPlayer,
openRoundSummary, openRoundSummary,
resetPlayerDrinks, resetPlayerDrinks,
resetGame,
} = useGameStore(); } = useGameStore();
const [rollSignal, setRollSignal] = useState(0); const [rollSignal, setRollSignal] = useState(0);
@@ -185,6 +189,29 @@ export function GameScreen({ navigation }: GameScreenProps) {
} }
}, [navigation, phase]); }, [navigation, phase]);
useFocusEffect(
useCallback(() => {
const backSubscription = BackHandler.addEventListener('hardwareBackPress', () => {
Alert.alert('Quitter la partie ?', 'Retourner au setup et abandonner la manche en cours ?', [
{ text: 'Annuler', style: 'cancel' },
{
text: 'Quitter',
style: 'destructive',
onPress: () => {
resetGame();
navigation.replace('Setup');
},
},
]);
return true;
});
return () => {
backSubscription.remove();
};
}, [navigation, resetGame]),
);
const launchRoll = useCallback( const launchRoll = useCallback(
(source: RollSource) => { (source: RollSource) => {
if (!webReady) { if (!webReady) {
+59 -14
View File
@@ -1,6 +1,7 @@
import { NativeStackScreenProps } from '@react-navigation/native-stack'; import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { useEffect, useMemo } from 'react'; import { useFocusEffect } from '@react-navigation/native';
import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native'; import { useCallback, useEffect, useMemo } from 'react';
import { Alert, BackHandler, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context'; import { SafeAreaView } from 'react-native-safe-area-context';
import Animated, { import Animated, {
FadeInDown, FadeInDown,
@@ -34,6 +35,36 @@ export function ScoreScreen({ navigation }: ScoreScreenProps) {
} }
}, [navigation, phase, roundSummary]); }, [navigation, phase, roundSummary]);
useFocusEffect(
useCallback(
() => {
const backSubscription = BackHandler.addEventListener('hardwareBackPress', () => {
Alert.alert(
'Quitter la partie ?',
'Retourner au setup et abandonner la manche en cours ?',
[
{ text: 'Annuler', style: 'cancel' },
{
text: 'Quitter',
style: 'destructive',
onPress: () => {
resetGame();
navigation.replace('Setup');
},
},
],
);
return true;
});
return () => {
backSubscription.remove();
};
},
[navigation, resetGame],
),
);
useEffect(() => { useEffect(() => {
pulse.value = withRepeat( pulse.value = withRepeat(
withSequence(withTiming(1.1, { duration: 340 }), withTiming(1, { duration: 340 })), withSequence(withTiming(1.1, { duration: 340 }), withTiming(1, { duration: 340 })),
@@ -88,7 +119,7 @@ export function ScoreScreen({ navigation }: ScoreScreenProps) {
}; };
return ( return (
<SafeAreaView style={styles.container} edges={['top']}> <SafeAreaView style={styles.container} edges={['top', 'bottom']}>
<ScrollView contentContainerStyle={styles.content}> <ScrollView contentContainerStyle={styles.content}>
<Text style={styles.title}>Fin du tour</Text> <Text style={styles.title}>Fin du tour</Text>
<Text style={styles.subtitle}> <Text style={styles.subtitle}>
@@ -161,15 +192,23 @@ export function ScoreScreen({ navigation }: ScoreScreenProps) {
))} ))}
</View> </View>
<View style={styles.buttonsRow}>
<Pressable style={styles.buttonPrimary} onPress={goToNextRound}>
<Text style={styles.buttonLabel}>Tour suivant</Text>
</Pressable>
<Pressable style={styles.buttonSecondary} onPress={goToSetup}>
<Text style={styles.buttonLabel}>Nouveau setup</Text>
</Pressable>
</View>
</ScrollView> </ScrollView>
<View style={styles.footerButtonsRow}>
<Pressable
style={styles.buttonSecondary}
onPress={goToSetup}
accessibilityHint="Retournera à la configuration et remettra la partie à zéro."
>
<Text style={styles.buttonLabel}>Nouveau setup</Text>
</Pressable>
<Pressable
style={styles.buttonPrimary}
onPress={goToNextRound}
accessibilityHint="Lancera immédiatement la manche suivante."
>
<Text style={styles.buttonLabel}>Tour suivant</Text>
</Pressable>
</View>
</SafeAreaView> </SafeAreaView>
); );
} }
@@ -180,6 +219,7 @@ const styles = StyleSheet.create({
}, },
content: { content: {
...presets.screen.content, ...presets.screen.content,
paddingBottom: ui.space.lg,
}, },
centered: { centered: {
flex: 1, flex: 1,
@@ -283,10 +323,15 @@ const styles = StyleSheet.create({
minHeight: 112, minHeight: 112,
backgroundColor: ui.color.surfaceMuted, backgroundColor: ui.color.surfaceMuted,
}, },
buttonsRow: { footerButtonsRow: {
marginTop: ui.space.md, paddingHorizontal: ui.space.md,
paddingTop: ui.space.xs,
paddingBottom: ui.space.sm,
flexDirection: 'row', flexDirection: 'row',
columnGap: ui.space.xs, columnGap: ui.space.xs,
backgroundColor: ui.color.bg,
borderTopWidth: 1,
borderTopColor: ui.color.border,
}, },
buttonPrimary: { buttonPrimary: {
...presets.button.prominent, ...presets.button.prominent,
@@ -301,4 +346,4 @@ const styles = StyleSheet.create({
buttonLabel: { buttonLabel: {
...presets.text.button, ...presets.text.button,
}, },
}); });
+103 -58
View File
@@ -37,7 +37,6 @@ export function SetupScreen({ navigation }: SetupScreenProps) {
const setupGame = useGameStore((state) => state.setupGame); const setupGame = useGameStore((state) => state.setupGame);
const savedProfiles = useGameStore((state) => state.savedProfiles); const savedProfiles = useGameStore((state) => state.savedProfiles);
const saveProfile = useGameStore((state) => state.saveProfile); const saveProfile = useGameStore((state) => state.saveProfile);
const toggleDefaultProfile = useGameStore((state) => state.toggleDefaultProfile);
const removeProfile = useGameStore((state) => state.removeProfile); const removeProfile = useGameStore((state) => state.removeProfile);
const persistedMagicNumberEnabled = useGameStore( const persistedMagicNumberEnabled = useGameStore(
(state) => state.persistedMagicNumberEnabled, (state) => state.persistedMagicNumberEnabled,
@@ -75,11 +74,6 @@ export function SetupScreen({ navigation }: SetupScreenProps) {
[], [],
); );
const defaultProfiles = useMemo(
() => savedProfiles.filter((profile) => profile.isDefault),
[savedProfiles],
);
useEffect(() => { useEffect(() => {
setEnableMagicNumber(persistedMagicNumberEnabled); setEnableMagicNumber(persistedMagicNumberEnabled);
}, [persistedMagicNumberEnabled]); }, [persistedMagicNumberEnabled]);
@@ -88,26 +82,6 @@ export function SetupScreen({ navigation }: SetupScreenProps) {
setQualitySetting(persistedQualitySetting); setQualitySetting(persistedQualitySetting);
}, [persistedQualitySetting]); }, [persistedQualitySetting]);
useEffect(() => {
if (defaultProfiles.length === 0) {
return;
}
const names = defaultProfiles.map((profile) => profile.name);
const magicNumbers = defaultProfiles.map((profile) => `${profile.magicNumber}`);
const themes = defaultProfiles.map((profile) => profile.theme ?? DEFAULT_DICE_THEME);
while (names.length < MIN_PLAYERS) {
names.push(`Joueur ${names.length + 1}`);
magicNumbers.push('');
themes.push(DEFAULT_DICE_THEME);
}
setPlayerNames(names);
setMagicNumbersByPlayer(magicNumbers);
setPlayerThemes(themes);
}, [defaultProfiles]);
const canStart = useMemo(() => sanitizeNames(playerNames).length >= MIN_PLAYERS, [playerNames]); const canStart = useMemo(() => sanitizeNames(playerNames).length >= MIN_PLAYERS, [playerNames]);
const selectedEndRoundPotFactorIndex = useMemo(() => { const selectedEndRoundPotFactorIndex = useMemo(() => {
@@ -148,6 +122,39 @@ export function SetupScreen({ navigation }: SetupScreenProps) {
setPlayerThemes((previous) => [...previous, DEFAULT_DICE_THEME]); setPlayerThemes((previous) => [...previous, DEFAULT_DICE_THEME]);
}; };
const movePlayer = (fromIndex: number, toIndex: number) => {
if (
fromIndex === toIndex ||
fromIndex < 0 ||
toIndex < 0 ||
fromIndex >= playerNames.length ||
toIndex >= playerNames.length
) {
return;
}
const reorder = <T,>(entries: T[]): T[] => {
const next = [...entries];
const [moved] = next.splice(fromIndex, 1);
next.splice(toIndex, 0, moved);
return next;
};
setPlayerNames((previous) => reorder(previous));
setMagicNumbersByPlayer((previous) => reorder(previous));
setPlayerThemes((previous) => reorder(previous));
};
const addProfileAsPlayer = (
profileName: string,
profileMagicNumber: number,
profileTheme?: string,
) => {
setPlayerNames((previous) => [...previous, profileName]);
setMagicNumbersByPlayer((previous) => [...previous, `${profileMagicNumber}`]);
setPlayerThemes((previous) => [...previous, profileTheme ?? DEFAULT_DICE_THEME]);
};
const removePlayer = (index: number) => { const removePlayer = (index: number) => {
if (playerNames.length <= MIN_PLAYERS) { if (playerNames.length <= MIN_PLAYERS) {
return; return;
@@ -292,6 +299,28 @@ export function SetupScreen({ navigation }: SetupScreenProps) {
{playerNames.map((name, index) => ( {playerNames.map((name, index) => (
<View key={`player-${index}`} style={styles.playerBlock}> <View key={`player-${index}`} style={styles.playerBlock}>
<View style={styles.playerRow}> <View style={styles.playerRow}>
<View style={styles.reorderButtonsColumn}>
<Pressable
style={[
styles.reorderButton,
index === 0 && styles.reorderButtonDisabled,
]}
disabled={index === 0}
onPress={() => movePlayer(index, index - 1)}
>
<Text style={styles.reorderLabel}>↑</Text>
</Pressable>
<Pressable
style={[
styles.reorderButton,
index === playerNames.length - 1 && styles.reorderButtonDisabled,
]}
disabled={index === playerNames.length - 1}
onPress={() => movePlayer(index, index + 1)}
>
<Text style={styles.reorderLabel}>↓</Text>
</Pressable>
</View>
<TextInput <TextInput
value={name} value={name}
onChangeText={(value) => updatePlayerName(index, value)} onChangeText={(value) => updatePlayerName(index, value)}
@@ -446,18 +475,6 @@ export function SetupScreen({ navigation }: SetupScreenProps) {
) : ( ) : (
savedProfiles.map((profile) => ( savedProfiles.map((profile) => (
<View key={profile.name} style={styles.profileRow}> <View key={profile.name} style={styles.profileRow}>
<Pressable
style={[
styles.profileDefaultToggle,
profile.isDefault && styles.profileDefaultToggleActive,
]}
onPress={() => toggleDefaultProfile(profile.name)}
>
<Text style={styles.profileDefaultToggleLabel}>
{profile.isDefault ? '✓' : ''}
</Text>
</Pressable>
<View style={styles.profileInfo}> <View style={styles.profileInfo}>
<Text style={styles.profileNameText}>{profile.name}</Text> <Text style={styles.profileNameText}>{profile.name}</Text>
<View style={styles.profileMetaRow}> <View style={styles.profileMetaRow}>
@@ -480,6 +497,19 @@ export function SetupScreen({ navigation }: SetupScreenProps) {
</View> </View>
</View> </View>
<Pressable
style={styles.profileAddButton}
onPress={() =>
addProfileAsPlayer(
profile.name,
profile.magicNumber,
profile.theme,
)
}
>
<Text style={styles.profileAddLabel}>+</Text>
</Pressable>
<Pressable <Pressable
style={styles.profileDeleteButton} style={styles.profileDeleteButton}
onPress={() => removeProfile(profile.name)} onPress={() => removeProfile(profile.name)}
@@ -680,6 +710,29 @@ const styles = StyleSheet.create({
flexDirection: 'row', flexDirection: 'row',
alignItems: 'center', alignItems: 'center',
}, },
reorderButtonsColumn: {
marginRight: ui.space.xs,
},
reorderButton: {
width: ui.size.iconButton,
height: ui.size.iconButton,
borderRadius: ui.radius.md,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: ui.color.surfaceAlt,
borderWidth: 1,
borderColor: ui.color.borderStrong,
marginBottom: ui.space.xxs,
},
reorderButtonDisabled: {
opacity: ui.opacity.disabled,
},
reorderLabel: {
color: ui.color.textPrimary,
fontWeight: textWeight.bold,
fontSize: ui.fontSize.sm,
lineHeight: ui.lineHeight.sm,
},
playerBlock: { playerBlock: {
marginBottom: ui.space.sm, marginBottom: ui.space.sm,
}, },
@@ -776,27 +829,8 @@ const styles = StyleSheet.create({
flexDirection: 'row', flexDirection: 'row',
alignItems: 'center', alignItems: 'center',
}, },
profileDefaultToggle: {
width: ui.size.toggle,
height: ui.size.toggle,
borderRadius: ui.radius.sm,
borderWidth: 1,
borderColor: ui.color.toggleBorder,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: ui.color.surfaceMuted,
},
profileDefaultToggleActive: {
backgroundColor: ui.color.accent,
borderColor: ui.color.accent,
},
profileDefaultToggleLabel: {
color: ui.color.onAccent,
fontWeight: textWeight.extraBold,
},
profileInfo: { profileInfo: {
flex: 1, flex: 1,
marginLeft: ui.space.xs,
marginRight: ui.space.xs, marginRight: ui.space.xs,
}, },
profileNameText: { profileNameText: {
@@ -825,6 +859,17 @@ const styles = StyleSheet.create({
...presets.button.toneDanger, ...presets.button.toneDanger,
borderRadius: ui.radius.md, borderRadius: ui.radius.md,
}, },
profileAddButton: {
...presets.button.compact,
...presets.button.tonePrimary,
borderRadius: ui.radius.md,
marginRight: ui.space.xs,
minWidth: 34,
},
profileAddLabel: {
...presets.text.button,
color: ui.color.onAccent,
},
profileDeleteLabel: { profileDeleteLabel: {
...presets.text.buttonDanger, ...presets.text.buttonDanger,
}, },
@@ -937,4 +982,4 @@ const styles = StyleSheet.create({
color: ui.color.textPrimary, color: ui.color.textPrimary,
fontWeight: textWeight.semibold, fontWeight: textWeight.semibold,
}, },
}); });
+41 -18
View File
@@ -135,6 +135,7 @@ type GameStoreState = {
awaitingNextPlayer: boolean; awaitingNextPlayer: boolean;
turns: TurnResult[]; turns: TurnResult[];
roundSummary: RoundSummary | null; roundSummary: RoundSummary | null;
roundSummaryApplied: boolean;
lastRollSource: RollSource | null; lastRollSource: RollSource | null;
allRolls: RollRecord[]; allRolls: RollRecord[];
playerRollStats: Record<string, PlayerRollStats>; playerRollStats: Record<string, PlayerRollStats>;
@@ -240,6 +241,7 @@ const getPotDeltaAndSpecials = (
dice: DicePair, dice: DicePair,
enableMagicNumber: boolean, enableMagicNumber: boolean,
playerMagicNumber: number | null, playerMagicNumber: number | null,
allow31PotBonus = true,
) => { ) => {
let potDelta = 0; let potDelta = 0;
const specials: string[] = []; const specials: string[] = [];
@@ -249,9 +251,11 @@ const getPotDeltaAndSpecials = (
specials.push('21 (+10 pot)'); specials.push('21 (+10 pot)');
} }
if (score === 31) { if (score === 31 && allow31PotBonus) {
potDelta += 10; potDelta += 10;
specials.push('31 (+10 pot)'); specials.push('31 (+10 pot)');
} else if (score === 31) {
specials.push('31 (bonus pot déjà accordé)');
} }
if (dice[0] === dice[1]) { if (dice[0] === dice[1]) {
@@ -344,6 +348,7 @@ const getInitialState = (): Omit<
awaitingNextPlayer: false, awaitingNextPlayer: false,
turns: [], turns: [],
roundSummary: null, roundSummary: null,
roundSummaryApplied: false,
lastRollSource: null, lastRollSource: null,
allRolls: [], allRolls: [],
playerRollStats: {}, playerRollStats: {},
@@ -612,25 +617,8 @@ export const useGameStore = create<GameStoreState>()(
state.settings.endRoundPotFactor, state.settings.endRoundPotFactor,
); );
const potValue = computeEndRoundPotValue(basePotValue, appliedPotFactor); const potValue = computeEndRoundPotValue(basePotValue, appliedPotFactor);
const updatedPlayers = state.players.map((player) => {
if (player.id === loser.playerId && potValue > 0) {
return {
...player,
drinksConsumed: roundDrinkValue(player.drinksConsumed + potValue),
};
}
return player;
});
const updatedAllTimeLeaderboard = { ...state.allTimeLeaderboard };
if (potValue > 0) {
updatedAllTimeLeaderboard[loser.playerName] =
roundDrinkValue((updatedAllTimeLeaderboard[loser.playerName] ?? 0) + potValue);
}
set({ set({
players: updatedPlayers,
allTimeLeaderboard: updatedAllTimeLeaderboard,
phase: 'playing', phase: 'playing',
pot: basePotValue, pot: basePotValue,
pendingRoll: false, pendingRoll: false,
@@ -641,6 +629,7 @@ export const useGameStore = create<GameStoreState>()(
tieBreakBaseTurns: [], tieBreakBaseTurns: [],
tieBreakEndedBy31: false, tieBreakEndedBy31: false,
lastRollSource: null, lastRollSource: null,
roundSummaryApplied: false,
roundSummary: { roundSummary: {
winnerName: winner.playerName, winnerName: winner.playerName,
loserName: loser.playerName, loserName: loser.playerName,
@@ -715,6 +704,7 @@ export const useGameStore = create<GameStoreState>()(
state.currentDice, state.currentDice,
state.settings.enableMagicNumber, state.settings.enableMagicNumber,
currentPlayer.magicNumber, currentPlayer.magicNumber,
!state.turns.some((turn) => turn.score === 31),
); );
const turn: TurnResult = { const turn: TurnResult = {
@@ -815,6 +805,7 @@ export const useGameStore = create<GameStoreState>()(
awaitingNextPlayer: false, awaitingNextPlayer: false,
turns: [], turns: [],
roundSummary: null, roundSummary: null,
roundSummaryApplied: false,
lastRollSource: null, lastRollSource: null,
allRolls: [], allRolls: [],
playerRollStats, playerRollStats,
@@ -1028,6 +1019,7 @@ export const useGameStore = create<GameStoreState>()(
normalizedDice, normalizedDice,
state.settings.enableMagicNumber, state.settings.enableMagicNumber,
currentPlayer.magicNumber, currentPlayer.magicNumber,
!state.turns.some((turn) => turn.score === 31),
); );
const endedBy31 = score === 31; const endedBy31 = score === 31;
const nextRollCount = state.currentRollCount + 1; const nextRollCount = state.currentRollCount + 1;
@@ -1264,6 +1256,7 @@ export const useGameStore = create<GameStoreState>()(
awaitingNextPlayer: false, awaitingNextPlayer: false,
turns: [], turns: [],
roundSummary: null, roundSummary: null,
roundSummaryApplied: false,
lastRollSource: null, lastRollSource: null,
tieBreakPlayerIds: [], tieBreakPlayerIds: [],
tieBreakTurns: [], tieBreakTurns: [],
@@ -1284,8 +1277,38 @@ export const useGameStore = create<GameStoreState>()(
return; 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({ set({
phase: 'round-summary', phase: 'round-summary',
players: nextPlayers,
allTimeLeaderboard: nextAllTimeLeaderboard,
roundSummaryApplied: true,
pendingRoll: false, pendingRoll: false,
awaitingDecision: false, awaitingDecision: false,
awaitingNextPlayer: false, awaitingNextPlayer: false,