feat : add board interactions

This commit is contained in:
GuillaumeSD
2024-02-23 04:01:18 +01:00
parent 2af0959e82
commit 814d3ecf09
19 changed files with 458 additions and 107 deletions

View File

@@ -1,4 +1,4 @@
import { Chess } from "chess.js";
import { Chess, Move } from "chess.js";
import { PrimitiveAtom, useAtom } from "jotai";
export const useChessActions = (chessAtom: PrimitiveAtom<Chess>) => {
@@ -20,10 +20,16 @@ export const useChessActions = (chessAtom: PrimitiveAtom<Chess>) => {
return newGame;
};
const move = (move: { from: string; to: string; promotion?: string }) => {
const move = (move: {
from: string;
to: string;
promotion?: string;
}): Move | null => {
const newGame = copyGame();
newGame.move(move);
const result = newGame.move(move);
setGame(newGame);
return result;
};
const undo = () => {

View File

@@ -0,0 +1,31 @@
import { boardAtom, gameAtom, gameEvalAtom } from "@/sections/analysis/states";
import { useAtomValue } from "jotai";
import { useMemo } from "react";
export const useCurrentMove = () => {
const gameEval = useAtomValue(gameEvalAtom);
const game = useAtomValue(gameAtom);
const board = useAtomValue(boardAtom);
const currentEvalMove = useMemo(() => {
if (!gameEval) return undefined;
const boardHistory = board.history();
const gameHistory = game.history();
if (
boardHistory.length >= gameHistory.length ||
gameHistory.slice(0, boardHistory.length).join() !== boardHistory.join()
)
return;
const evalIndex = board.history().length;
return {
...board.history({ verbose: true }).at(-1),
eval: gameEval.moves[evalIndex],
lastEval: evalIndex > 0 ? gameEval.moves[evalIndex - 1] : undefined,
};
}, [gameEval, board, game]);
return currentEvalMove;
};

View File

@@ -55,9 +55,11 @@ export const useGameDatabase = (shouldFetchGames?: boolean) => {
if (!db) throw new Error("Database not initialized");
const gameToAdd = formatGameToDatabase(game);
await db.add("games", gameToAdd as Game);
const gameId = await db.add("games", gameToAdd as Game);
loadGames();
return gameId;
};
const setGameEval = async (gameId: number, evaluation: GameEval) => {