diff --git a/lib/chesstrainer/endgames.ex b/lib/chesstrainer/endgames.ex index 510f332..10fc6d0 100644 --- a/lib/chesstrainer/endgames.ex +++ b/lib/chesstrainer/endgames.ex @@ -105,6 +105,22 @@ defmodule Chesstrainer.Endgames do Endgame.changeset(endgame, attrs) end + @doc """ + Records the start of an attempt, incrementing `times_attempted`. + """ + def record_attempt(%Endgame{id: id}), do: increment(id, times_attempted: 1) + + @doc """ + Records a solved attempt, incrementing `times_solved`. + """ + def record_solve(%Endgame{id: id}), do: increment(id, times_solved: 1) + + defp increment(id, increments) do + Repo.update_all(from(e in Endgame, where: e.id == ^id), inc: increments) + + {:ok, Repo.get!(Endgame, id)} + end + def add_tag(endgame, tag) do endgame |> Repo.preload(:tags) diff --git a/lib/chesstrainer_web/live/endgame_live/play.ex b/lib/chesstrainer_web/live/endgame_live/play.ex index 53569f2..9139f50 100644 --- a/lib/chesstrainer_web/live/endgame_live/play.ex +++ b/lib/chesstrainer_web/live/endgame_live/play.ex @@ -11,7 +11,8 @@ defmodule ChesstrainerWeb.EndgameLive.Play do <.header> Play endgame {@endgame.key} <:subtitle> - {@endgame.color |> Atom.to_string() |> String.capitalize()} to move · Rating: {@endgame.rating} + {@endgame.color |> Atom.to_string() |> String.capitalize()} to move · Rating: {@endgame.rating} · Attempts: {@endgame.times_attempted || + 0} · Solved: {@endgame.times_solved || 0} <:actions> <.button navigate={~p"/endgames"}> @@ -38,6 +39,14 @@ defmodule ChesstrainerWeb.EndgameLive.Play do <% @status == :blocked -> %>

Tablebase unavailable

{@blocked_reason}

+ <% @status == :solved -> %> +

Solved!

+ <% @status == :failed -> %> +

Failed

+

That move throws away the win.

+ <%= if @best_move do %> +

Best was: {@best_move}

+ <% end %> <% @awaiting_reply -> %>

Opponent is replying…

<% @last_grade == :optimal -> %> @@ -74,7 +83,8 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
<.button phx-click="reset" variant="primary"> - <.icon name="hero-arrow-path" /> Reset + <.icon name="hero-arrow-path" /> + {if @status in [:solved, :failed], do: "Try again", else: "Reset"}
@@ -95,6 +105,7 @@ defmodule ChesstrainerWeb.EndgameLive.Play do |> assign(:tablebase, nil) |> assign(:status, :loading) |> assign(:blocked_reason, nil) + |> assign(:best_move, nil) |> assign(:move_list, []) |> assign(:last_san, "None yet") |> assign(:last_from_to, "None yet") @@ -112,10 +123,13 @@ defmodule ChesstrainerWeb.EndgameLive.Play do fen_after = params["fen"] || socket.assigns.fen cond do - socket.assigns.status != :playing -> + socket.assigns.status == :blocked -> {:noreply, put_flash(socket, :error, "The tablebase is unavailable, so this move cannot be graded.")} + socket.assigns.status != :playing -> + {:noreply, socket} + not same_position?(prev_fen, socket.assigns.fen) -> {:noreply, put_flash(socket, :error, "That move is out of sequence. Press Reset to try again.")} @@ -180,12 +194,20 @@ defmodule ChesstrainerWeb.EndgameLive.Play do defp load_attempt(socket) do fen = socket.assigns.endgame.fen - socket = socket |> assign(:fen, fen) |> assign(:awaiting_reply, false) + + socket = + socket + |> assign(:fen, fen) + |> assign(:awaiting_reply, false) + |> assign(:best_move, nil) if connected?(socket) do case Tablebase.new(fen) do {:ok, tablebase} -> + {:ok, endgame} = Endgames.record_attempt(socket.assigns.endgame) + socket + |> assign(:endgame, endgame) |> assign(:tablebase, tablebase) |> assign(:status, :playing) |> assign(:blocked_reason, nil) @@ -244,25 +266,37 @@ defmodule ChesstrainerWeb.EndgameLive.Play do |> 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} + cond do + grade == :losing -> + fail_attempt(socket) + + grade in [:optimal, :winning] and not is_nil(promotion) -> + # Conversion cutoff: a promotion that keeps the win ends the puzzle. + solve_attempt(socket) + + grade in [:optimal, :winning] and + not same_position?(fen_after, socket.assigns.fen) -> + start_opponent_reply(socket, fen_after) + + true -> + {:noreply, socket} end end end defp start_opponent_reply(socket, fen_after) do case Tablebase.new(fen_after) do + {:ok, %Tablebase{checkmate: true}} -> + solve_attempt(socket) + {: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. + {:ok, %Tablebase{}} -> + # Terminal non-mate position (stalemate/insufficient): no reply to play. {:noreply, socket} other -> @@ -273,6 +307,47 @@ defmodule ChesstrainerWeb.EndgameLive.Play do end end + defp solve_attempt(socket) do + {:ok, endgame} = Endgames.record_solve(socket.assigns.endgame) + + {:noreply, + socket + |> assign(:status, :solved) + |> assign(:endgame, endgame) + |> assign(:awaiting_reply, false) + |> assign(:best_move, nil)} + end + + defp fail_attempt(socket) do + {:noreply, + socket + |> assign(:status, :failed) + |> assign(:awaiting_reply, false) + |> assign(:best_move, best_move_text(socket.assigns.tablebase))} + end + + defp best_move_text(%Tablebase{category: category, moves: [best | _] = moves}) do + best_rank = outcome_rank(category) + + if is_nil(best_rank) do + nil + else + san = + moves + |> Enum.filter(fn move -> + outcome_rank(mover_outcome(move.category)) == best_rank and move.dtz == best.dtz + end) + |> Enum.map(& &1.san) + |> Enum.reject(&is_nil/1) + |> Enum.take(3) + |> Enum.join(", ") + + if san == "", do: nil, else: san + end + end + + defp best_move_text(_tablebase), do: nil + defp reply_payload(%Tablebase.Move{uci: uci, san: san}) do %{ from: String.slice(uci, 0, 2), diff --git a/test/chesstrainer_web/live/endgame_live/play_test.exs b/test/chesstrainer_web/live/endgame_live/play_test.exs index 1c0b2d3..cfb89d4 100644 --- a/test/chesstrainer_web/live/endgame_live/play_test.exs +++ b/test/chesstrainer_web/live/endgame_live/play_test.exs @@ -4,6 +4,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do import Phoenix.LiveViewTest import Chesstrainer.EndgamesFixtures + alias Chesstrainer.Endgames alias Chesstrainer.Endgames.Tablebase alias Chesstrainer.Endgames.Tablebase.Cache, as: TablebaseCache alias Chesstrainer.Ratelimiters @@ -22,6 +23,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do defp seed_tablebase(fen, opts \\ []) do tablebase = %Tablebase{ category: Keyword.get(opts, :category, :win), + checkmate: Keyword.get(opts, :checkmate, false), moves: Keyword.get(opts, :moves, []) } @@ -146,7 +148,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do assert render(view) =~ "Winning — but not the sharpest" end - test "grades a move that throws the win away as losing", %{conn: conn} do + test "fails a move that throws the win away", %{conn: conn} do endgame = endgame_fixture() seed_tablebase(endgame.fen, moves: grading_moves()) @@ -154,7 +156,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do play_move(view, endgame, "d1", "d4", "Qd4") - assert render(view) =~ "Losing move" + assert render(view) =~ "Failed" end test "rejects a move that is out of sequence", %{conn: conn} do @@ -220,7 +222,75 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do %{proxy: {ref, _topic, _}} = view refute_receive {^ref, {:push_event, "opponent_move", _payload}}, 100 - assert render(view) =~ "Losing move" + assert render(view) =~ "Failed" + end + end + + describe "attempt outcome" do + test "records an attempt on start", %{conn: conn} do + endgame = endgame_fixture() + seed_tablebase(endgame.fen) + + {:ok, _view, _html} = live(conn, ~p"/endgames/#{endgame}/play") + + assert Endgames.get_endgame!(endgame.id).times_attempted == 1 + end + + test "solves on checkmate", %{conn: conn} do + endgame = endgame_fixture() + fen_after = "8/8/8/8/8/8/8/8 b - - 0 1" + + seed_tablebase(endgame.fen, moves: grading_moves()) + seed_tablebase(fen_after, checkmate: true, 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 + }) + + assert render(view) =~ "Solved!" + assert Endgames.get_endgame!(endgame.id).times_solved == 1 + end + + test "solves on a promotion that keeps the win", %{conn: conn} do + endgame = endgame_fixture() + moves = [%Tablebase.Move{uci: "a7a8q", san: "a8=Q", category: :loss, dtz: -1}] + seed_tablebase(endgame.fen, moves: moves) + + {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") + + render_hook(view, "endgame_move_played", %{ + "from" => "a7", + "to" => "a8", + "san" => "a8=Q", + "promotion" => "q", + "prev_fen" => endgame.fen, + "fen" => endgame.fen, + "endgame_id" => endgame.id + }) + + assert render(view) =~ "Solved!" + assert Endgames.get_endgame!(endgame.id).times_solved == 1 + end + + test "fails on a losing move and reveals the best move", %{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") + + html = render(view) + assert html =~ "Failed" + assert html =~ "Qd7+" + assert Endgames.get_endgame!(endgame.id).times_solved == 0 end end @@ -240,6 +310,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do assert html =~ "No Moves" refute html =~ "Optimal move" assert_init_board(view, endgame.fen, "white", "white") + assert Endgames.get_endgame!(endgame.id).times_attempted == 2 end end end