From fa2d6b8f8714e34adcfa93f62438372bc6b8bfea Mon Sep 17 00:00:00 2001 From: Neil Murphy Date: Tue, 12 Mar 2024 14:17:51 +0000 Subject: [PATCH] better turn logic management for single player games --- client/src/components/chess-board.tsx | 4 +++- client/src/hooks/use-game-state.tsx | 18 +++++++++++++----- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/client/src/components/chess-board.tsx b/client/src/components/chess-board.tsx index bc02c48..64d7177 100644 --- a/client/src/components/chess-board.tsx +++ b/client/src/components/chess-board.tsx @@ -21,7 +21,7 @@ let selectedPiece: HTMLDivElement | null = null; interface ChessBoardProps {} const ChessBoard: FC = () => { - const { isMultiplayer, gameRecord, setGameRecord } = useGameState(); + const { isMultiplayer, gameRecord, setGameRecord, completeTurn } = useGameState(); const { currentPlayer, makeNetworkMove } = useNetwork(); const boardRef = useRef(null); @@ -209,6 +209,8 @@ const ChessBoard: FC = () => { setGameRecord(updatedGameRecord); if (isMultiplayer && makeNetworkMove !== undefined) { makeNetworkMove(updatedGameRecord); + } else { + completeTurn(); } }, [gameRecord.boardState, gameRecord.playerTurn], diff --git a/client/src/hooks/use-game-state.tsx b/client/src/hooks/use-game-state.tsx index 10cf4d9..375af86 100644 --- a/client/src/hooks/use-game-state.tsx +++ b/client/src/hooks/use-game-state.tsx @@ -14,6 +14,7 @@ const GameStateContext = createContext( isMultiplayer: boolean; gameRecord: GameRecord; setGameRecord: React.Dispatch>; + completeTurn: () => void; }, ); @@ -27,6 +28,16 @@ const GameStateProvider = ({ isMultiplayer = false, children }: GameStateProvide : defaultGameRecord, ); + const completeTurn = () => { + if (isMultiplayer) { + return; + } + setGameRecord((prevGameRecord) => ({ + ...prevGameRecord, + playerTurn: prevGameRecord.playerTurn === "white" ? "black" : "white", + })); + }; + /** * save singleplayer game record to local storage when it changes */ @@ -66,10 +77,6 @@ const GameStateProvider = ({ isMultiplayer = false, children }: GameStateProvide })); return; } - setGameRecord((prevGameRecord) => ({ - ...prevGameRecord, - playerTurn: prevGameRecord.playerTurn === "white" ? "black" : "white", - })); }, [gameRecord.boardState.board]); useEffect(() => { @@ -100,8 +107,9 @@ const GameStateProvider = ({ isMultiplayer = false, children }: GameStateProvide isMultiplayer, gameRecord, setGameRecord, + completeTurn, }), - [gameRecord, setGameRecord], + [isMultiplayer, gameRecord, setGameRecord, completeTurn], ); return {children};