Skip to content

Commit

Permalink
better turn logic management for single player games
Browse files Browse the repository at this point in the history
  • Loading branch information
barrymun committed Mar 12, 2024
1 parent f908f83 commit fa2d6b8
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
4 changes: 3 additions & 1 deletion client/src/components/chess-board.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ let selectedPiece: HTMLDivElement | null = null;
interface ChessBoardProps {}

const ChessBoard: FC<ChessBoardProps> = () => {
const { isMultiplayer, gameRecord, setGameRecord } = useGameState();
const { isMultiplayer, gameRecord, setGameRecord, completeTurn } = useGameState();
const { currentPlayer, makeNetworkMove } = useNetwork();

const boardRef = useRef<HTMLDivElement | null>(null);
Expand Down Expand Up @@ -209,6 +209,8 @@ const ChessBoard: FC<ChessBoardProps> = () => {
setGameRecord(updatedGameRecord);
if (isMultiplayer && makeNetworkMove !== undefined) {
makeNetworkMove(updatedGameRecord);
} else {
completeTurn();
}
},
[gameRecord.boardState, gameRecord.playerTurn],
Expand Down
18 changes: 13 additions & 5 deletions client/src/hooks/use-game-state.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const GameStateContext = createContext(
isMultiplayer: boolean;
gameRecord: GameRecord;
setGameRecord: React.Dispatch<React.SetStateAction<GameRecord>>;
completeTurn: () => void;
},
);

Expand All @@ -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
*/
Expand Down Expand Up @@ -66,10 +77,6 @@ const GameStateProvider = ({ isMultiplayer = false, children }: GameStateProvide
}));
return;
}
setGameRecord((prevGameRecord) => ({
...prevGameRecord,
playerTurn: prevGameRecord.playerTurn === "white" ? "black" : "white",
}));
}, [gameRecord.boardState.board]);

useEffect(() => {
Expand Down Expand Up @@ -100,8 +107,9 @@ const GameStateProvider = ({ isMultiplayer = false, children }: GameStateProvide
isMultiplayer,
gameRecord,
setGameRecord,
completeTurn,
}),
[gameRecord, setGameRecord],
[isMultiplayer, gameRecord, setGameRecord, completeTurn],
);

return <GameStateContext.Provider value={value}>{children}</GameStateContext.Provider>;
Expand Down

0 comments on commit fa2d6b8

Please sign in to comment.