feat : undo last played move
This commit is contained in:
@@ -3,6 +3,7 @@ import { useAtom, useAtomValue } from "jotai";
|
|||||||
import { gameAtom, isGameInProgressAtom } from "./states";
|
import { gameAtom, isGameInProgressAtom } from "./states";
|
||||||
import { useEffect } from "react";
|
import { useEffect } from "react";
|
||||||
import { playGameEndSound } from "@/lib/sounds";
|
import { playGameEndSound } from "@/lib/sounds";
|
||||||
|
import UndoMoveButton from "./undoMoveButton";
|
||||||
|
|
||||||
export default function GameInProgress() {
|
export default function GameInProgress() {
|
||||||
const game = useAtomValue(gameAtom);
|
const game = useAtomValue(gameAtom);
|
||||||
@@ -40,14 +41,11 @@ export default function GameInProgress() {
|
|||||||
<CircularProgress size={20} color="info" />
|
<CircularProgress size={20} color="info" />
|
||||||
</Grid>
|
</Grid>
|
||||||
|
|
||||||
<Grid
|
<Grid item container justifyContent="center" alignItems="center" xs={12}>
|
||||||
item
|
<UndoMoveButton />
|
||||||
container
|
</Grid>
|
||||||
justifyContent="center"
|
|
||||||
alignItems="center"
|
<Grid item container justifyContent="center" alignItems="center" xs={12}>
|
||||||
xs={12}
|
|
||||||
gap={2}
|
|
||||||
>
|
|
||||||
<Button variant="outlined" onClick={handleResign}>
|
<Button variant="outlined" onClick={handleResign}>
|
||||||
Resign
|
Resign
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
32
src/sections/play/undoMoveButton.tsx
Normal file
32
src/sections/play/undoMoveButton.tsx
Normal file
@@ -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 (
|
||||||
|
<Button variant="outlined" onClick={handleClick}>
|
||||||
|
Undo your last move
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user