Skip to content

Commit

Permalink
Merge branch 'get-rid-of-chessjs'
Browse files Browse the repository at this point in the history
  • Loading branch information
franciscoBSalgueiro committed Feb 12, 2024
2 parents e874978 + 4e43985 commit 9c4ebeb
Show file tree
Hide file tree
Showing 16 changed files with 176 additions and 245 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"tauri": "tauri",
"format": "biome format --write ./src",
"test": "vitest run",
"lint": "biome check ./src",
"lint": "tsc --noEmit && biome check ./src",
"lint:fix": "biome check --apply ./src"
},
"dependencies": {
Expand Down
8 changes: 4 additions & 4 deletions src-tauri/src/chess.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ impl EngineProcess {

async fn set_options(&mut self, options: EngineOptions) -> Result<(), Error> {
let fen: Fen = options.fen.parse()?;
let mut pos: Chess = match fen.into_position(CastlingMode::Standard) {
let mut pos: Chess = match fen.into_position(CastlingMode::Chess960) {
Ok(p) => p,
Err(e) => e.ignore_too_much_material()?,
};
Expand Down Expand Up @@ -249,7 +249,7 @@ fn parse_uci_attrs(
) -> Result<BestMoves, Error> {
let mut best_moves = BestMoves::default();

let mut pos: Chess = match fen.clone().into_position(CastlingMode::Standard) {
let mut pos: Chess = match fen.clone().into_position(CastlingMode::Chess960) {
Ok(p) => p,
Err(e) => e.ignore_too_much_material()?,
};
Expand Down Expand Up @@ -586,7 +586,7 @@ pub async fn analyze_game(

let fen = Fen::from_ascii(options.fen.as_bytes())?;

let mut chess: Chess = fen.clone().into_position(CastlingMode::Standard)?;
let mut chess: Chess = fen.clone().into_position(CastlingMode::Chess960)?;
let mut fens: Vec<(Fen, Vec<String>, bool)> = vec![(fen, vec![], false)];

options.moves.iter().enumerate().for_each(|(i, m)| {
Expand Down Expand Up @@ -780,7 +780,7 @@ mod tests {

fn pos(fen: &str) -> Chess {
let fen: Fen = fen.parse().unwrap();
Chess::from_setup(fen.into_setup(), CastlingMode::Standard).unwrap()
Chess::from_setup(fen.into_setup(), CastlingMode::Chess960).unwrap()
}

#[test]
Expand Down
6 changes: 3 additions & 3 deletions src-tauri/src/db/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ pub enum PositionQuery {
impl PositionQuery {
pub fn exact_from_fen(fen: &str) -> Result<PositionQuery, Error> {
let position: Chess =
Fen::from_ascii(fen.as_bytes())?.into_position(shakmaty::CastlingMode::Standard)?;
Fen::from_ascii(fen.as_bytes())?.into_position(shakmaty::CastlingMode::Chess960)?;
let pawn_home = get_pawn_home(position.board());
let material = get_material_count(position.board());
Ok(PositionQuery::Exact(ExactData {
Expand Down Expand Up @@ -172,7 +172,7 @@ fn get_move_after_match(
) -> Result<Option<String>, Error> {
let mut chess = if let Some(fen) = fen {
let fen = Fen::from_ascii(fen.as_bytes())?;
Chess::from_setup(fen.into_setup(), shakmaty::CastlingMode::Standard)?
Chess::from_setup(fen.into_setup(), shakmaty::CastlingMode::Chess960)?
} else {
Chess::default()
};
Expand Down Expand Up @@ -415,7 +415,7 @@ mod tests {
fn assert_partial_match(fen1: &str, fen2: &str) {
let query = PositionQuery::partial_from_fen(fen1).unwrap();
let fen = Fen::from_ascii(fen2.as_bytes()).unwrap();
let chess = Chess::from_setup(fen.into_setup(), shakmaty::CastlingMode::Standard).unwrap();
let chess = Chess::from_setup(fen.into_setup(), shakmaty::CastlingMode::Chess960).unwrap();
assert!(query.matches(&chess));
}

Expand Down
32 changes: 22 additions & 10 deletions src/components/boards/Board.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,8 @@ import {
Annotation,
TimeControlField,
getMaterialDiff,
makeClk,
moveToKey,
parseKeyboardMove,
parseTimeControl,
parseUci,
} from "@/utils/chess";
import {
chessopsError,
Expand Down Expand Up @@ -56,8 +53,15 @@ import {
} from "@tabler/icons-react";
import { DrawShape } from "chessground/draw";
import { Color } from "chessground/types";
import { NormalMove, Square, SquareName, parseSquare } from "chessops";
import { chessgroundDests } from "chessops/compat";
import {
NormalMove,
Square,
SquareName,
makeSquare,
parseSquare,
parseUci,
} from "chessops";
import { chessgroundDests, chessgroundMove } from "chessops/compat";
import { makeSan } from "chessops/san";
import { useAtom, useAtomValue, useSetAtom } from "jotai";
import { memo, useContext, useEffect, useMemo, useState } from "react";
Expand Down Expand Up @@ -182,14 +186,14 @@ function Board({
setInvisible(false);
dispatch({
type: "MAKE_MOVE",
payload: san,
payload: move,
});
setPendingMove(null);
}
} else {
dispatch({
type: "MAKE_MOVE",
payload: san,
payload: move,
clock: pos.turn === "white" ? whiteTime : blackTime,
});
setPendingMove(null);
Expand All @@ -202,7 +206,9 @@ function Board({
for (const [i, moves] of entries) {
if (i < 4) {
for (const [j, move] of moves.entries()) {
const { from, to } = parseUci(move);
const m = parseUci(move)! as NormalMove;
const from = makeSquare(m.from)!;
const to = makeSquare(m.to)!;
if (shapes.find((s) => s.orig === from && s.dest === to)) continue;
shapes.push({
orig: from,
Expand Down Expand Up @@ -412,7 +418,7 @@ function Board({
{currentNode.annotation && currentNode.move && (
<AnnotationHint
orientation={orientation}
square={parseSquare(currentNode.move.to)}
square={currentNode.move.to}
annotation={currentNode.annotation}
/>
)}
Expand Down Expand Up @@ -484,7 +490,13 @@ function Board({
}}
turnColor={turn}
check={pos?.isCheck()}
lastMove={editingMode ? undefined : moveToKey(currentNode.move)}
lastMove={
editingMode
? undefined
: currentNode.move
? chessgroundMove(currentNode.move)
: undefined
}
premovable={{
enabled: false,
}}
Expand Down
5 changes: 3 additions & 2 deletions src/components/boards/BoardGame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
tabsAtom,
} from "@/atoms/atoms";
import { events, GoMode, commands } from "@/bindings";
import { TimeControlField, getMainLine, parseUci } from "@/utils/chess";
import { TimeControlField, getMainLine } from "@/utils/chess";
import { positionFromFen } from "@/utils/chessops";
import { EngineSettings, LocalEngine } from "@/utils/engines";
import { getNodeAtPath, treeIteratorMainLine } from "@/utils/treeReducer";
Expand All @@ -33,6 +33,7 @@ import {
IconPlus,
IconZoomCheck,
} from "@tabler/icons-react";
import { parseUci } from "chessops";
import { INITIAL_FEN } from "chessops/fen";
import { useAtom, useAtomValue } from "jotai";
import {
Expand Down Expand Up @@ -406,7 +407,7 @@ function BoardGame() {
) {
dispatch({
type: "APPEND_MOVE",
payload: parseUci(ev[0].uciMoves[0]),
payload: parseUci(ev[0].uciMoves[0])!,
clock: (pos.turn === "white" ? whiteTime : blackTime) ?? undefined,
});
}
Expand Down
2 changes: 1 addition & 1 deletion src/components/boards/CompleteMoveCell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ function CompleteMoveCell({
commentHTML: string;
annotation: Annotation;
showComments: boolean;
move?: string;
move?: string | null;
first?: boolean;
isCurrentVariation: boolean;
isStart: boolean;
Expand Down
4 changes: 2 additions & 2 deletions src/components/boards/GameNotation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ const RenderVariationTree = memo(
annotation={variation.annotation}
commentHTML={variation.commentHTML}
halfMoves={variation.halfMoves}
move={variation.move?.san}
move={variation.san}
movePath={[...path, variations.indexOf(variation)]}
showComments={showComments}
isCurrentVariation={shallowEqual(
Expand Down Expand Up @@ -252,7 +252,7 @@ const RenderVariationTree = memo(
annotation={variations[0].annotation}
commentHTML={variations[0].commentHTML}
halfMoves={variations[0].halfMoves}
move={variations[0].move?.san}
move={variations[0].san}
movePath={[...path, 0]}
showComments={showComments}
isCurrentVariation={shallowEqual([...path, 0], currentPath)}
Expand Down
8 changes: 4 additions & 4 deletions src/components/common/EvalChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const EvalChart = (props: EvalChartProps) => {
const [pos, error] = positionFromFen(node.fen);
if (pos) {
if (pos.isCheckmate()) {
return node.move?.color === "w" ? 1 : -1;
return pos?.turn === "white" ? 1 : -1;
}
if (pos.isStalemate()) {
return 0;
Expand Down Expand Up @@ -87,13 +87,13 @@ const EvalChart = (props: EvalChartProps) => {
const nodes = getNodes();
for (let i = 0; i < nodes.length; i++) {
const currentNode = nodes[i];
const move = currentNode.node.move!;
const yValue = getYValue(currentNode.node);
const [pos] = positionFromFen(currentNode.node.fen);

yield {
name: `${Math.ceil(currentNode.node.halfMoves / 2)}.${
move.color === "w" ? "" : ".."
} ${move.san}${currentNode.node.annotation}`,
pos?.turn === "white" ? "" : ".."
} ${currentNode.node.san}${currentNode.node.annotation}`,
evalText: getEvalText(currentNode.node),
yValue: yValue ?? "none",
movePath: currentNode.position,
Expand Down
4 changes: 2 additions & 2 deletions src/components/files/opening.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export function buildFromTree(
if (
item.node.children.length === 0 ||
isPrefix(item.position, start) ||
!item.node.children[0].move
!item.node.children[0].san
) {
continue;
}
Expand All @@ -35,7 +35,7 @@ export function buildFromTree(
cards.push({
fen: item.node.fen,
position: item.position,
answer: item.node.children[0].move?.san,
answer: item.node.children[0].san,
repetitions: 0,
level: "unseen",
});
Expand Down
3 changes: 2 additions & 1 deletion src/components/panels/analysis/TablebaseInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
Stack,
Text,
} from "@mantine/core";
import { parseUci } from "chessops";
import { useContext } from "react";
import useSWRImmutable from "swr/immutable";
import { P, match } from "ts-pattern";
Expand Down Expand Up @@ -72,7 +73,7 @@ function TablebaseInfo({
onClick={() => {
dispatch({
type: "MAKE_MOVE",
payload: m.san,
payload: parseUci(m.uci)!,
});
}}
className={classes.info}
Expand Down
47 changes: 19 additions & 28 deletions src/components/puzzles/PuzzleBoard.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
import { showCoordinatesAtom } from "@/atoms/atoms";
import { Chessground } from "@/chessground/Chessground";
import { chessboard } from "@/styles/Chessboard.css";
import { moveToKey } from "@/utils/chess";
import { positionFromFen } from "@/utils/chessops";
import { Completion, Puzzle } from "@/utils/puzzles";
import { getNodeAtPath, treeIteratorMainLine } from "@/utils/treeReducer";
import { Box } from "@mantine/core";
import { useForceUpdate } from "@mantine/hooks";
import { Chess, NormalMove, makeUci, parseSquare, parseUci } from "chessops";
import { chessgroundDests } from "chessops/compat";
import {
Chess,
Move,
NormalMove,
makeUci,
parseSquare,
parseUci,
} from "chessops";
import { chessgroundDests, chessgroundMove } from "chessops/compat";
import { parseFen, parsePiece } from "chessops/fen";
import equal from "fast-deep-equal";
import { useAtomValue } from "jotai";
Expand Down Expand Up @@ -52,16 +58,7 @@ function PuzzleBoard({
let currentMove = 0;
if (puzzle) {
for (const { node } of treeIter) {
if (
node.move &&
makeUci({
from: parseSquare(node.move.from),
to: parseSquare(node.move.to),
promotion: node.move.promotion
? parsePiece(node.move.promotion)?.role
: undefined,
}) === puzzle.moves[currentMove]
) {
if (node.move && makeUci(node.move) === puzzle.moves[currentMove]) {
currentMove++;
} else {
break;
Expand All @@ -79,14 +76,12 @@ function PuzzleBoard({
const turn = pos?.turn || "white";
const showCoordinates = useAtomValue(showCoordinatesAtom);

function checkMove(move: string) {
function checkMove(move: Move) {
if (!pos) return;
const newPos = pos.clone();
newPos.play(parseUci(move)!);
if (
puzzle &&
(puzzle.moves[currentMove] === move || newPos.isCheckmate())
) {
const uci = makeUci(move);
newPos.play(move);
if (puzzle && (puzzle.moves[currentMove] === uci || newPos.isCheckmate())) {
if (currentMove === puzzle.moves.length - 1) {
if (puzzle.completion !== "incorrect") {
changeCompletion("correct");
Expand Down Expand Up @@ -135,13 +130,7 @@ function PuzzleBoard({
cancelMove={() => setPendingMove(null)}
confirmMove={(p) => {
if (pendingMove) {
checkMove(
makeUci({
from: pendingMove.from,
to: pendingMove.to,
promotion: p,
}),
);
checkMove({ ...pendingMove, promotion: p });
setPendingMove(null);
}
}}
Expand Down Expand Up @@ -173,12 +162,14 @@ function PuzzleBoard({
) {
setPendingMove(move);
} else {
checkMove(makeUci(move));
checkMove(move);
}
},
},
}}
lastMove={moveToKey(currentNode.move)}
lastMove={
currentNode.move ? chessgroundMove(currentNode.move) : undefined
}
turnColor={turn}
fen={currentNode.fen}
check={pos?.isCheck()}
Expand Down
7 changes: 3 additions & 4 deletions src/components/puzzles/Puzzles.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
tabsAtom,
} from "@/atoms/atoms";
import { commands } from "@/bindings";
import { parseUci } from "@/utils/chess";
import { unwrap } from "@/utils/invoke";
import {
Completion,
Expand Down Expand Up @@ -34,7 +33,7 @@ import {
} from "@mantine/core";
import { useLocalStorage, useSessionStorage } from "@mantine/hooks";
import { IconPlus, IconX, IconZoomCheck } from "@tabler/icons-react";
import { Chess } from "chessops";
import { Chess, parseUci } from "chessops";
import { parseFen } from "chessops/fen";
import { useAtom, useSetAtom } from "jotai";
import { useContext, useEffect, useState } from "react";
Expand Down Expand Up @@ -82,7 +81,7 @@ function Puzzles({ id }: { id: string }) {

function setPuzzle(puzzle: { fen: string; moves: string[] }) {
dispatch({ type: "SET_FEN", payload: puzzle.fen });
dispatch({ type: "MAKE_MOVE", payload: parseUci(puzzle.moves[0]) });
dispatch({ type: "MAKE_MOVE", payload: parseUci(puzzle.moves[0])! });
}

function generatePuzzle(db: string) {
Expand Down Expand Up @@ -272,7 +271,7 @@ function Puzzles({ id }: { id: string }) {
for (let i = 0; i < curPuzzle.moves.length; i++) {
dispatch({
type: "MAKE_MOVE",
payload: parseUci(curPuzzle.moves[i]),
payload: parseUci(curPuzzle.moves[i])!,
mainline: true,
});
await new Promise((r) => setTimeout(r, 500));
Expand Down
Loading

0 comments on commit 9c4ebeb

Please sign in to comment.