feat : add board interactions
This commit is contained in:
@@ -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 = () => {
|
||||
|
||||
31
src/hooks/useCurrentMove.ts
Normal file
31
src/hooks/useCurrentMove.ts
Normal 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;
|
||||
};
|
||||
@@ -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) => {
|
||||
|
||||
Reference in New Issue
Block a user