Skip to content

Commit

Permalink
add more chessdb information
Browse files Browse the repository at this point in the history
  • Loading branch information
franciscoBSalgueiro committed Jan 14, 2024
1 parent acaba41 commit 164a20a
Showing 1 changed file with 60 additions and 15 deletions.
75 changes: 60 additions & 15 deletions src/utils/chessdb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,19 @@ import { fetch } from "@tauri-apps/api/http";

const endpoint = "https://www.chessdb.cn/cdb.php";

type Response = {
type AllResponse = {
status: string;
moves: ChessDBData[];
};

type BestResponse = {
status: string;
depth: number;
score: number;
pv: string[];
pvSAN: string[];
};

type ChessDBData = {
uci: string;
san: string;
Expand All @@ -28,40 +36,77 @@ export async function getBestMoves(
moves.slice(0, options.multipv).map((m, i) => ({
score: { type: "cp", value: m.score },
nodes: 0,
depth: 0,
depth: m.depth ?? 0,
multipv: i + 1,
nps: 0,
sanMoves: [m.san],
uciMoves: [m.uci],
sanMoves: m.san,
uciMoves: m.uci,
})),
];
}

const cache = new Map<string, ChessDBData[]>();
type CachedResult = {
uci: string[];
san: string[];
score: number;
rank: number;
note: string;
depth?: number;
winrate?: string;
};

const cache = new Map<string, CachedResult[]>();

async function queryPosition(fen: string): Promise<ChessDBData[]> {
async function queryPosition(fen: string) {
if (cache.has(fen)) {
return cache.get(fen)!;
}
const side = fen.split(" ")[1];

const url = new URL(endpoint);
url.searchParams.append("action", "queryall");
url.searchParams.append("json", "1");
url.searchParams.append("board", fen);
const res = await fetch<Response>(url.toString());
const res = await fetch<AllResponse>(url.toString());

const side = fen.split(" ")[1];
if (res.data.status !== "ok") {
return [];
}

let data: ChessDBData[] = [];
if (res.data.status === "ok") {
data = res.data.moves;
const data: CachedResult[] = res.data.moves.map((m) => ({
...m,
score: side === "b" ? -m.score : m.score,
uci: [m.uci],
san: [m.san],
}));

const best = await queryBest(fen);
if (best) {
data[0].depth = best.depth;
data[0].uci = best.pv;
data[0].san = best.pvSAN;
}

cache.set(fen, data);
return data;
}

async function queryBest(fen: string) {
const url = new URL(endpoint);
url.searchParams.append("action", "querypv");
url.searchParams.append("json", "1");
url.searchParams.append("board", fen);
const res = await fetch<BestResponse>(url.toString());

if (res.data.status !== "ok") {
return null;
}

const data = res.data;
const side = fen.split(" ")[1];
if (side === "b") {
data.forEach((m) => {
m.score *= -1;
});
data.score *= -1;
}

cache.set(fen, data);
return data;
}

0 comments on commit 164a20a

Please sign in to comment.