Broken updates

This commit is contained in:
Administrator
2025-02-13 18:09:28 -05:00
parent 6155f8b253
commit 9027d9c52b
6 changed files with 440 additions and 124 deletions

View File

@@ -1,33 +1,25 @@
// src/context/ScoreContext.js
import React, { createContext, useContext, useReducer, useEffect } from 'react';
// Define action types
export const ACTIONS = {
ADD_ARROW: 'ADD_ARROW',
START_NEW_ROUND: 'START_NEW_ROUND',
RESET_GAME: 'RESET_GAME',
};
// Initial state structure
const initialState = {
currentGame: {
gameType: null, // '450' or '300'
rounds: [], // Array of rounds
totalScore: 0,
totalBullseyes: 0,
dateStarted: null,
},
games: [], // Historical games
LOAD_SAVED_GAME: 'LOAD_SAVED_GAME',
START_NEW_GAME: 'START_NEW_GAME',
SAVE_GAME: 'SAVE_GAME',
UPDATE_HANDICAP: 'UPDATE_HANDICAP'
};
// Reducer function
const scoreReducer = (state, action) => {
let newState;
switch (action.type) {
case ACTIONS.ADD_ARROW:
const { roundIndex, score, isBullseye } = action.payload;
const updatedRounds = [...state.currentGame.rounds];
// Update the specific round
if (!updatedRounds[roundIndex]) {
updatedRounds[roundIndex] = { arrows: [], total: 0, bullseyes: 0 };
}
@@ -39,11 +31,10 @@ const scoreReducer = (state, action) => {
bullseyes: updatedRounds[roundIndex].bullseyes + (isBullseye ? 1 : 0),
};
// Calculate new totals
const totalScore = updatedRounds.reduce((sum, round) => sum + round.total, 0);
const totalBullseyes = updatedRounds.reduce((sum, round) => sum + round.bullseyes, 0);
return {
newState = {
...state,
currentGame: {
...state.currentGame,
@@ -52,29 +43,41 @@ const scoreReducer = (state, action) => {
totalBullseyes,
},
};
break;
case ACTIONS.START_NEW_ROUND:
const { gameType } = action.payload;
return {
...state,
// If there's a current game, save it to history
const gamesHistory = state.currentGame.gameType ?
[...state.games, state.currentGame] :
state.games;
newState = {
games: gamesHistory,
currentGame: {
gameType,
gameType: action.payload.gameType,
rounds: [],
totalScore: 0,
totalBullseyes: 0,
dateStarted: new Date().toISOString(),
},
};
break;
case ACTIONS.RESET_GAME:
return {
...state,
currentGame: initialState.currentGame,
};
newState = initialState;
break;
case ACTIONS.LOAD_SAVED_GAME:
newState = action.payload;
break;
default:
return state;
}
// Save to localStorage after every state change
localStorage.setItem('archeryScores', JSON.stringify(newState));
return newState;
};
// Create context
@@ -84,15 +87,21 @@ const ScoreContext = createContext();
export const ScoreProvider = ({ children }) => {
// Load state from localStorage on initial render
const [state, dispatch] = useReducer(scoreReducer, initialState, () => {
const localData = localStorage.getItem('archeryScores');
return localData ? JSON.parse(localData) : initialState;
try {
const localData = localStorage.getItem('archeryScores');
if (localData) {
const parsedData = JSON.parse(localData);
// Verify the data structure
if (parsedData.currentGame && parsedData.games) {
return parsedData;
}
}
} catch (error) {
console.error('Error loading saved game:', error);
}
return initialState;
});
// Save to localStorage whenever state changes
useEffect(() => {
localStorage.setItem('archeryScores', JSON.stringify(state));
}, [state]);
return (
<ScoreContext.Provider value={{ state, dispatch }}>
{children}
@@ -108,3 +117,122 @@ export const useScore = () => {
}
return context;
};
// src/context/ScoreContext.js
// ... (keeping existing imports and initial setup)
const initialState = {
currentGame: {
id: null,
gameType: null, // '450' or '300'
category: null, // 'league' or 'practice'
rounds: [],
totalScore: 0,
totalBullseyes: 0,
dateStarted: null,
dateCompleted: null,
handicap: null,
},
games: {
league: [],
practice: [],
},
statistics: {
handicapHistory: [],
averageScores: {
league: { '450': 0, '300': 0 },
practice: { '450': 0, '300': 0 },
},
},
};
// Handicap calculation function (basic version - can be adjusted based on your league's rules)
const calculateHandicap = (scores) => {
if (scores.length < 3) return null;
// Take the average of the last 3 scores
const lastThree = scores.slice(-3);
const average = lastThree.reduce((sum, game) => sum + game.totalScore, 0) / 3;
// Example handicap calculation (adjust formula as needed)
const maxPossibleScore = scores[0].gameType === '450' ? 450 : 300;
const handicap = Math.round((maxPossibleScore - average) * 0.8);
return Math.max(0, Math.min(100, handicap)); // Cap between 0 and 100
};
const scoreReducer = (state, action) => {
switch (action.type) {
case ACTIONS.START_NEW_GAME:
const { gameType, category } = action.payload;
return {
...state,
currentGame: {
...initialState.currentGame,
id: Date.now(),
gameType,
category,
dateStarted: new Date().toISOString(),
},
};
case ACTIONS.SAVE_GAME:
const completedGame = {
...state.currentGame,
dateCompleted: new Date().toISOString(),
};
// Calculate handicap for league games
if (completedGame.category === 'league') {
const relevantGames = [...state.games.league, completedGame]
.filter(game => game.gameType === completedGame.gameType)
.sort((a, b) => new Date(b.dateCompleted) - new Date(a.dateCompleted));
completedGame.handicap = calculateHandicap(relevantGames);
}
const newGames = {
...state.games,
[completedGame.category]: [
...state.games[completedGame.category],
completedGame,
],
};
// Update statistics
const updateAverages = (games, type, category) => {
const relevantGames = games.filter(game => game.gameType === type);
return relevantGames.length > 0
? relevantGames.reduce((sum, game) => sum + game.totalScore, 0) / relevantGames.length
: 0;
};
const newStatistics = {
...state.statistics,
averageScores: {
league: {
'450': updateAverages(newGames.league, '450', 'league'),
'300': updateAverages(newGames.league, '300', 'league'),
},
practice: {
'450': updateAverages(newGames.practice, '450', 'practice'),
'300': updateAverages(newGames.practice, '300', 'practice'),
},
},
};
return {
...state,
currentGame: initialState.currentGame,
games: newGames,
statistics: newStatistics,
};
// ... (existing cases)
default:
return state;
}
};
// ... (rest of the context implementation)