From 7a6bce6b2473eb9e12d02fad5b517112cd526b57 Mon Sep 17 00:00:00 2001 From: GuillaumeSD Date: Sat, 6 Apr 2024 02:21:58 +0200 Subject: [PATCH] feat : undo last played move --- src/sections/play/gameInProgress.tsx | 14 ++++++------ src/sections/play/undoMoveButton.tsx | 32 ++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 8 deletions(-) create mode 100644 src/sections/play/undoMoveButton.tsx diff --git a/src/sections/play/gameInProgress.tsx b/src/sections/play/gameInProgress.tsx index 8e353c2..7f53ae6 100644 --- a/src/sections/play/gameInProgress.tsx +++ b/src/sections/play/gameInProgress.tsx @@ -3,6 +3,7 @@ import { useAtom, useAtomValue } from "jotai"; import { gameAtom, isGameInProgressAtom } from "./states"; import { useEffect } from "react"; import { playGameEndSound } from "@/lib/sounds"; +import UndoMoveButton from "./undoMoveButton"; export default function GameInProgress() { const game = useAtomValue(gameAtom); @@ -40,14 +41,11 @@ export default function GameInProgress() { - + + + + + diff --git a/src/sections/play/undoMoveButton.tsx b/src/sections/play/undoMoveButton.tsx new file mode 100644 index 0000000..285c5c1 --- /dev/null +++ b/src/sections/play/undoMoveButton.tsx @@ -0,0 +1,32 @@ +import { Button } from "@mui/material"; +import { gameAtom, playerColorAtom } from "./states"; +import { useAtomValue } from "jotai"; +import { useChessActions } from "@/hooks/useChessActions"; +import { Color } from "@/types/enums"; + +export default function UndoMoveButton() { + const game = useAtomValue(gameAtom); + const { goToMove, undoMove } = useChessActions(gameAtom); + const playerColor = useAtomValue(playerColorAtom); + + const handleClick = () => { + const gameHistory = game.history(); + const turnColor = game.turn(); + if ( + (turnColor === "w" && playerColor === Color.White) || + (turnColor === "b" && playerColor === Color.Black) + ) { + if (gameHistory.length < 2) return; + goToMove(gameHistory.length - 2, game); + } else { + if (!gameHistory.length) return; + undoMove(); + } + }; + + return ( + + ); +}