From 164a20a202c1d310ad992dd6b22682f23a4613b5 Mon Sep 17 00:00:00 2001 From: Francisco Salgueiro Date: Sun, 14 Jan 2024 12:12:00 +0000 Subject: [PATCH] add more chessdb information --- src/utils/chessdb.ts | 75 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 60 insertions(+), 15 deletions(-) diff --git a/src/utils/chessdb.ts b/src/utils/chessdb.ts index c5baa200..3fe44761 100644 --- a/src/utils/chessdb.ts +++ b/src/utils/chessdb.ts @@ -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; @@ -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(); +type CachedResult = { + uci: string[]; + san: string[]; + score: number; + rank: number; + note: string; + depth?: number; + winrate?: string; +}; + +const cache = new Map(); -async function queryPosition(fen: string): Promise { +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(url.toString()); + const res = await fetch(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(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; }