Play the opponent's optimal defence after a passing move

#8: after a passing move, fetch the post-move position's tablebase and
reply with moves[0] (the defender's optimal defence). The client applies
and animates the reply, reports the resulting FEN, and the server fetches
that position's tablebase before resuming the user's turn.

Losing moves and terminal positions do not trigger a reply; a failed
post-reply fetch blocks the attempt. The board stays locked during the
reply round-trip so play cannot get out of sync.
This commit is contained in:
2026-11-01 21:45:32 +01:00
parent cadc842010
commit 248504cc58
3 changed files with 171 additions and 7 deletions
+49
View File
@@ -5,6 +5,7 @@ export const ChessBoard = {
mounted() {
this.chess = new Chess();
this.ground = null;
this.playerColor = "white";
this.handleEvent("init_board", (payload) => {
this.initBoard(payload);
@@ -37,6 +38,14 @@ export const ChessBoard = {
}
});
this.handleEvent("opponent_move", ({ from, to, promotion, san }) => {
this.applyOpponentMove({ from, to, promotion, san });
});
this.handleEvent("resume_board", () => {
this.resumeBoard();
});
this.initBoard({
fen: this.chess.fen(),
orientation: "white",
@@ -56,6 +65,8 @@ export const ChessBoard = {
return;
}
this.playerColor = player_color;
if (this.ground) {
this.ground.destroy();
}
@@ -171,4 +182,42 @@ export const ChessBoard = {
this.ground.set({ fen: this.chess.fen() });
}
},
applyOpponentMove({ from, to, promotion, san }) {
const move = promotion
? this.chess.move({ from, to, promotion })
: this.chess.move({ from, to });
if (!move) {
console.error("Opponent move rejected by chess.js", { from, to, promotion, san });
return;
}
const nextTurnColor = this.chess.turn() === "w" ? "white" : "black";
this.ground.set({
fen: this.chess.fen(),
turnColor: nextTurnColor,
movable: { color: null, dests: new Map() },
});
this.pushEvent("opponent_reply_applied", {
fen: this.chess.fen(),
san: move.san,
});
},
resumeBoard() {
const turnColor = this.chess.turn() === "w" ? "white" : "black";
this.ground.set({
fen: this.chess.fen(),
turnColor,
movable: {
color: this.playerColor || turnColor,
free: false,
dests: this.getValidDests(),
},
});
},
};
+73 -6
View File
@@ -38,6 +38,8 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
<% @status == :blocked -> %>
<p class="font-semibold text-red-600">Tablebase unavailable</p>
<p class="text-red-500">{@blocked_reason}</p>
<% @awaiting_reply -> %>
<p class="text-gray-500">Opponent is replying…</p>
<% @last_grade == :optimal -> %>
<p class="font-semibold text-emerald-600">Optimal move</p>
<% @last_grade == :winning -> %>
@@ -97,6 +99,7 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
|> assign(:last_san, "None yet")
|> assign(:last_from_to, "None yet")
|> assign(:last_grade, nil)
|> assign(:awaiting_reply, false)
{:ok, load_attempt(socket)}
end
@@ -106,6 +109,7 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
%{"from" => from, "to" => to, "san" => san} = params
promotion = params["promotion"]
prev_fen = params["prev_fen"] || socket.assigns.fen
fen_after = params["fen"] || socket.assigns.fen
cond do
socket.assigns.status != :playing ->
@@ -117,7 +121,32 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
put_flash(socket, :error, "That move is out of sequence. Press Reset to try again.")}
true ->
grade_and_record(socket, from, to, promotion, san)
grade_and_record(socket, from, to, promotion, san, fen_after)
end
end
def handle_event("opponent_reply_applied", %{"fen" => fen}, socket) do
if socket.assigns.awaiting_reply do
case Tablebase.new(fen) do
{:ok, tablebase} ->
{:noreply,
socket
|> assign(:fen, fen)
|> assign(:tablebase, tablebase)
|> assign(:awaiting_reply, false)
|> assign(:status, :playing)
|> assign(:blocked_reason, nil)
|> push_event("resume_board", %{})}
other ->
{:noreply,
socket
|> assign(:awaiting_reply, false)
|> assign(:status, :blocked)
|> assign(:blocked_reason, blocked_reason(other))}
end
else
{:noreply, socket}
end
end
@@ -151,7 +180,7 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
defp load_attempt(socket) do
fen = socket.assigns.endgame.fen
socket = assign(socket, :fen, fen)
socket = socket |> assign(:fen, fen) |> assign(:awaiting_reply, false)
if connected?(socket) do
case Tablebase.new(fen) do
@@ -200,20 +229,58 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
"The tablebase is unavailable (#{inspect(reason)})."
end
defp grade_and_record(socket, from, to, promotion, san) do
defp grade_and_record(socket, from, to, promotion, san, fen_after) do
case find_move(socket.assigns.tablebase, from, to, promotion) do
nil ->
{:noreply, put_flash(socket, :error, "Could not identify that move in the tablebase.")}
move ->
{:noreply,
grade = grade_move(socket.assigns.tablebase, move)
socket =
socket
|> assign(:last_from_to, "#{from} ➔ #{to}")
|> assign(:last_san, san)
|> assign(:last_grade, grade_move(socket.assigns.tablebase, move))
|> assign(:move_list, socket.assigns.move_list ++ [san])}
|> assign(:last_grade, grade)
|> assign(:move_list, socket.assigns.move_list ++ [san])
if grade in [:optimal, :winning] and
not same_position?(fen_after, socket.assigns.fen) do
start_opponent_reply(socket, fen_after)
else
{:noreply, socket}
end
end
end
defp start_opponent_reply(socket, fen_after) do
case Tablebase.new(fen_after) do
{:ok, %Tablebase{moves: [reply | _]}} ->
{:noreply,
socket
|> assign(:awaiting_reply, true)
|> push_event("opponent_move", reply_payload(reply))}
{:ok, %Tablebase{moves: []}} ->
# Terminal position (checkmate/stalemate): there is no reply to play.
{:noreply, socket}
other ->
{:noreply,
socket
|> assign(:status, :blocked)
|> assign(:blocked_reason, blocked_reason(other))}
end
end
defp reply_payload(%Tablebase.Move{uci: uci, san: san}) do
%{
from: String.slice(uci, 0, 2),
to: String.slice(uci, 2, 2),
promotion: String.at(uci, 4),
san: san
}
end
defp find_move(%Tablebase{moves: moves}, from, to, promotion) when is_list(moves) do
uci = "#{from}#{to}#{promotion || ""}"
@@ -176,6 +176,54 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
end
end
describe "opponent reply" do
test "plays the opponent's optimal defence and resumes the user's turn", %{conn: conn} do
endgame = endgame_fixture()
fen_after = "8/8/8/8/8/8/8/8 b - - 0 1"
fen_after_reply = "8/8/8/8/8/8/8/8 w - - 0 1"
reply = %Tablebase.Move{uci: "e8e7", san: "Ke7", category: :loss, dtz: -3}
seed_tablebase(endgame.fen, moves: grading_moves())
seed_tablebase(fen_after, category: :loss, moves: [reply])
seed_tablebase(fen_after_reply, category: :win, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play")
render_hook(view, "endgame_move_played", %{
"from" => "d1",
"to" => "d7",
"san" => "Qd7+",
"prev_fen" => endgame.fen,
"fen" => fen_after,
"endgame_id" => endgame.id
})
%{proxy: {ref, _topic, _}} = view
assert_receive {^ref, {:push_event, "opponent_move", payload}}, 100
assert payload == %{from: "e8", to: "e7", promotion: nil, san: "Ke7"}
render_hook(view, "opponent_reply_applied", %{"fen" => fen_after_reply})
assert_receive {^ref, {:push_event, "resume_board", _payload}}, 100
end
test "does not reply when the move throws the win away", %{conn: conn} do
endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play")
play_move(view, endgame, "d1", "d4", "Qd4")
%{proxy: {ref, _topic, _}} = view
refute_receive {^ref, {:push_event, "opponent_move", _payload}}, 100
assert render(view) =~ "Losing move"
end
end
describe "reset" do
test "clears the move list and grade, and re-pushes init_board", %{conn: conn} do
endgame = endgame_fixture()