diff --git a/GLOSSARY.md b/GLOSSARY.md index 0b4b154..ffdb50a 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -24,7 +24,7 @@ _Avoid_: Random puzzle, featured puzzle **Attempt**: A recorded playthrough of a puzzle by a user, ending solved or failed; a per-user record, distinct from an endgame's global attempt and solve counts. -_Avoid_: Run, session, game +_Avoid_: Run, game **Theme**: A label describing an endgame's technique or goal, such as "mate in 2", "Lucena" or @@ -93,6 +93,12 @@ The decisive zeroing move — a promotion — that ends a conversion-type puzzle The terminal condition short of mate at which a puzzle counts as solved: promotion (still winning) for conversion puzzles, mate otherwise. +**Session**: +One continuous spell of puzzle play, begun by choosing a difficulty, that +carries a start time and a rating baseline for the timer and rating-gain +monitor. Ephemeral — it lives only in the running LiveView, never persisted. +_Avoid_: Run, game, attempt + ## Ratings **Rating**: @@ -115,6 +121,14 @@ A measure of how erratic a competitor's recent results are, used by some rating systems; the trainer deliberately does not track it. _Avoid_: Variance, inconsistency +**Difficulty**: +A choice — `easy`, `medium` or `hard` — that selects which puzzles to serve +relative to the current user's rating: `medium` is near the user's rating, +`easy` below it, `hard` above it. The band width is a configured constant. It is +a property of a session, not of an endgame — the same endgame is easy for one +user and hard for another. +_Avoid_: Level, rank, tier + ## Infrastructure **Tablebase**: diff --git a/ROADMAP.md b/ROADMAP.md index a488cd7..ec5fa9c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -15,7 +15,7 @@ Target: Q1 2027 - [x] Log in - [x] Rating of user and puzzles - [x] Implement core API endpoints with input validation. - - [ ] Traverse puzzles in easy/medium/hard mode with session timer/rating+/- + - [x] Traverse puzzles in easy/medium/hard mode with session timer/rating+/- --- diff --git a/TODO.md b/TODO.md index eae8d8e..84de409 100644 --- a/TODO.md +++ b/TODO.md @@ -9,7 +9,7 @@ Granular tasks and operational scratchpad for active development. - [x] Apply design to the rest of the site - [x] Create reusable components such as button - [x] Organise nav bar -- [ ] Display puzzles and move to next +- [x] Display puzzles and move to next - [x] Create footer --- diff --git a/assets/css/base/_globals.css b/assets/css/base/_globals.css index 3db7cf1..fb6af15 100644 --- a/assets/css/base/_globals.css +++ b/assets/css/base/_globals.css @@ -6,6 +6,10 @@ html { scroll-behavior: smooth; } body { min-width: 320px; + min-height: 100vh; + min-height: 100dvh; + display: flex; + flex-direction: column; background: var(--color-canvas); color: var(--color-body); font-family: 'DM Sans', sans-serif; @@ -14,7 +18,7 @@ button { cursor: pointer; } } -main { overflow: hidden; } +main { overflow: hidden; flex: 1 0 auto; } /* LiveView */ @custom-variant phx-click-loading (.phx-click-loading&, .phx-click-loading &); diff --git a/assets/js/app.js b/assets/js/app.js index 5a666a3..101a591 100644 --- a/assets/js/app.js +++ b/assets/js/app.js @@ -28,11 +28,13 @@ import { hooks as colocatedHooks } from "phoenix-colocated/chesstrainer"; import topbar from "../vendor/topbar"; import { ChessBoard } from "./hooks/chessBoard"; import { CopyFen } from "./hooks/copyFen"; +import { SessionClock } from "./hooks/sessionClock"; let Hooks = { ...colocatedHooks, ChessBoard, CopyFen, + SessionClock, }; const csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content"); diff --git a/assets/js/hooks/sessionClock.js b/assets/js/hooks/sessionClock.js new file mode 100644 index 0000000..4af40ec --- /dev/null +++ b/assets/js/hooks/sessionClock.js @@ -0,0 +1,27 @@ +// Ticks a session clock in mm:ss from its `data-started-at` (unix ms) so the +// timer advances without a server round-trip. The server renders the initial +// value, so a re-render stays in sync with the client. +export const SessionClock = { + mounted() { + this.tick(); + this.timer = setInterval(() => this.tick(), 1000); + }, + + updated() { + this.tick(); + }, + + destroyed() { + clearInterval(this.timer); + }, + + tick() { + const startedAt = parseInt(this.el.dataset.startedAt, 10); + if (!startedAt) return; + + const total = Math.max(0, Math.floor((Date.now() - startedAt) / 1000)); + const minutes = String(Math.floor(total / 60)).padStart(2, "0"); + const seconds = String(total % 60).padStart(2, "0"); + this.el.textContent = `${minutes}:${seconds}`; + }, +}; diff --git a/config/config.exs b/config/config.exs index 8823068..435185d 100644 --- a/config/config.exs +++ b/config/config.exs @@ -36,6 +36,12 @@ config :chesstrainer, :ratings, window_days: 7, rd_inflation_c: 10.0 +# Difficulty bands for puzzle sessions. An endgame is "medium" when its rating +# falls within `band_width` of the user's rating, "easy" below that band and +# "hard" above it. Tweak to widen or narrow the served difficulty (e.g. 150 or +# 200). +config :chesstrainer, :puzzles, band_width: 100 + # Public codes of the endgames pinned to the landing-page puzzle grid, in # display order. When empty (or short) the grid is topped up with a date-seeded # selection from the database, so it stays stable for a given day. diff --git a/docs/adr/0009-ephemeral-puzzle-sessions.md b/docs/adr/0009-ephemeral-puzzle-sessions.md new file mode 100644 index 0000000..e0e96dc --- /dev/null +++ b/docs/adr/0009-ephemeral-puzzle-sessions.md @@ -0,0 +1,31 @@ +# Puzzle sessions are ephemeral and share one play surface + +A session — one continuous spell of puzzle play, started by choosing a +difficulty — carries a start time and a rating baseline for the timer and +rating-gain monitor, and lives only in the running `Train` LiveView. Nothing is +persisted: attempts are still recorded per endgame, but the session itself has +no table. + +The alternative was to keep `EndgameLive.Play` as the play surface and navigate +from puzzle to puzzle (e.g. `/endgames/:code/play?session=...`), carrying the +session in the URL or a short-lived server token. Navigation kills the LiveView +socket, so the timer, per-puzzle times, baseline and completed count would all +have to be carried or re-derived; that fights the "ephemeral" decision and +leaks session state into URLs. Instead the session owns one socket and swaps the +current endgame in place, which keeps every session value in one place. + +To avoid a second copy of the move grading and best-line review, the play +surface (board, grading, opponent reply, review, retry) is extracted into a +shared module used by both `EndgameLive.Play` (standalone, optional auth, used +by daily/curated deep links) and the new `EndgameLive.Train` (session, login +only). Both keep their own `handle_event` entry points, which delegate to the +shared logic, so the existing play tests and event contract are unchanged. + +## Consequences + +- `/endgames/:public_code/play` stays a standalone play surface; `/train` is the + session front door. +- Session state (difficulty, start time, baseline, completed count, per-puzzle + timing) never leaves the `Train` socket and disappears when the page closes. +- Difficulty is relative to the current user's rating, not an absolute property + of an endgame; its band width is a config constant. diff --git a/lib/chesstrainer/attempts.ex b/lib/chesstrainer/attempts.ex index 99175ba..b07de97 100644 --- a/lib/chesstrainer/attempts.ex +++ b/lib/chesstrainer/attempts.ex @@ -59,5 +59,21 @@ defmodule Chesstrainer.Attempts do |> Repo.one() end + @doc """ + The distinct endgame ids `user_id` has attempted in the last `days` days. + + Used by puzzle selection to prefer fresh puzzles; a retry still counts as an + attempt, even though the rating window leaves it unrated. + """ + def recent_endgame_ids(user_id, days \\ 30) do + cutoff = DateTime.add(DateTime.utc_now(), -days, :day) + + Attempt + |> where([a], a.user_id == ^user_id and a.inserted_at >= ^cutoff) + |> distinct(true) + |> select([a], a.endgame_id) + |> Repo.all() + end + defp rated(query), do: where(query, [a], not is_nil(a.rated_at)) end diff --git a/lib/chesstrainer/puzzles.ex b/lib/chesstrainer/puzzles.ex new file mode 100644 index 0000000..9b13ac0 --- /dev/null +++ b/lib/chesstrainer/puzzles.ex @@ -0,0 +1,111 @@ +defmodule Chesstrainer.Puzzles do + @moduledoc """ + Selects endgames to serve as puzzles. + + A puzzle is played at one of three difficulties — `:easy`, `:medium` or + `:hard` — defined relative to the current user's rating: `:medium` is within + a configurable band of the user's rating, `:easy` below it and `:hard` above + it. The same endgame is therefore easy for one player and hard for another. + + Selection prefers endgames the user has not attempted in the last 30 days. + When that pool is empty it falls back to any endgame in the band; the rating + window keeps a recent replay unrated until it expires. + """ + + import Ecto.Query, warn: false + + alias Chesstrainer.Repo + alias Chesstrainer.Accounts.User + alias Chesstrainer.Attempts + alias Chesstrainer.Endgames.Endgame + + @default_band_width 100 + @difficulties [:easy, :medium, :hard] + + @doc "The difficulties a session can be played at." + def difficulties, do: @difficulties + + @doc """ + The half-width of the medium band, in rating points. + + Configured under `:chesstrainer, :puzzles, :band_width`. + """ + def band_width do + :chesstrainer + |> Application.get_env(:puzzles, []) + |> Keyword.get(:band_width, @default_band_width) + end + + @doc """ + The `{min, max}` rating range for `difficulty` relative to `rating`. + + A `nil` bound is open-ended. + """ + def difficulty_range(rating, difficulty) when difficulty in @difficulties do + width = band_width() + + case difficulty do + :easy -> {nil, rating - width} + :medium -> {rating - width, rating + width} + :hard -> {rating + width, nil} + end + end + + @doc """ + Picks the next puzzle for `user` at `difficulty`, using `user.rating` as the + baseline. + + `:exclude_ids` (default `[]`) skips endgames by id — used to avoid repeating + the puzzle just played. Returns `nil` when no endgame exists at all. + """ + def next_endgame(%User{} = user, difficulty, opts \\ []) + when difficulty in @difficulties do + exclude_ids = Keyword.get(opts, :exclude_ids, []) + band = difficulty_range(user.rating, difficulty) + recent_ids = Attempts.recent_endgame_ids(user.id) + + fresh = + Endgame + |> in_band(band) + |> skip_ids(exclude_ids) + |> skip_ids(recent_ids) + |> random_one() + + fresh || fallback(user.rating, band, exclude_ids) + end + + defp fallback(rating, band, exclude_ids) do + Endgame + |> in_band(band) + |> skip_ids(exclude_ids) + |> random_one() + |> case do + nil -> nearest(rating, exclude_ids) + endgame -> endgame + end + end + + defp nearest(rating, exclude_ids) do + Endgame + |> skip_ids(exclude_ids) + |> order_by([e], asc: fragment("ABS(? - ?)", e.rating, ^rating)) + |> limit(1) + |> Repo.one() + end + + defp random_one(query) do + query + |> order_by([e], fragment("RANDOM()")) + |> limit(1) + |> Repo.one() + end + + defp in_band(query, {nil, max}), do: where(query, [e], e.rating <= ^max) + defp in_band(query, {min, nil}), do: where(query, [e], e.rating >= ^min) + + defp in_band(query, {min, max}), + do: where(query, [e], e.rating >= ^min and e.rating <= ^max) + + defp skip_ids(query, []), do: query + defp skip_ids(query, ids), do: where(query, [e], e.id not in ^ids) +end diff --git a/lib/chesstrainer/ratings.ex b/lib/chesstrainer/ratings.ex index a9d0b3d..7ae3611 100644 --- a/lib/chesstrainer/ratings.ex +++ b/lib/chesstrainer/ratings.ex @@ -27,8 +27,10 @@ defmodule Chesstrainer.Ratings do Rates both sides of a finished attempt and stamps it as rated. A solve scores 1 for the user and 0 for the endgame; a failure scores 0 for - the user and 1 for the endgame. Returns `{:ok, %{user, endgame, attempt}}`, or + the user and 1 for the endgame. Returns + `{:ok, %{user, endgame, attempt, user_delta, endgame_delta}}`, or `{:skipped, attempt}` when the pair was already rated inside the window. + The deltas are the signed change applied to each side's rating. """ def rate_attempt(%Attempt{outcome: outcome} = attempt) do now = DateTime.utc_now(:second) @@ -74,6 +76,9 @@ defmodule Chesstrainer.Ratings do end defp persist(user, endgame, attempt, new_user, new_endgame, now) do + user_delta = new_user.rating - user.rating + endgame_delta = new_endgame.rating - endgame.rating + Repo.transaction(fn -> user = user @@ -96,7 +101,13 @@ defmodule Chesstrainer.Ratings do |> Ecto.Changeset.change(rated_at: now) |> Repo.update!() - %{user: user, endgame: endgame, attempt: attempt} + %{ + user: user, + endgame: endgame, + attempt: attempt, + user_delta: user_delta, + endgame_delta: endgame_delta + } end) end diff --git a/lib/chesstrainer_web/components/layouts.ex b/lib/chesstrainer_web/components/layouts.ex index 264bb06..5361b44 100644 --- a/lib/chesstrainer_web/components/layouts.ex +++ b/lib/chesstrainer_web/components/layouts.ex @@ -62,7 +62,10 @@ defmodule ChesstrainerWeb.Layouts do doc: "the current [scope](https://phoenix.hexdocs.pm/scopes.html)" def navbar(assigns) do - assigns = assign(assigns, :nav_links, nav_links(assigns.current_scope)) + assigns = + assigns + |> assign(:nav_links, nav_links(assigns.current_scope)) + |> assign(:start_href, start_href(assigns.current_scope)) ~H"""
@@ -95,7 +98,7 @@ defmodule ChesstrainerWeb.Layouts do <% end %> <% end %> - <.pill_button variant={:nav} href="/endgames"> + <.pill_button variant={:nav} href={@start_href}> Start training <.icon_arrow /> @@ -139,6 +142,10 @@ defmodule ChesstrainerWeb.Layouts do defp admin?(%{user: %{role: role}}), do: Role.admin?(role) defp admin?(_scope), do: false + # Signed-in users start a puzzle session; visitors browse the public list. + defp start_href(%{user: %{}}), do: ~p"/train" + defp start_href(_scope), do: ~p"/endgames" + @doc """ Renders the site-wide footer. @@ -183,7 +190,11 @@ defmodule ChesstrainerWeb.Layouts do def flash_group(assigns) do ~H""" -
+
<.flash kind={:info} flash={@flash} /> <.flash kind={:error} flash={@flash} /> diff --git a/lib/chesstrainer_web/components/play_components.ex b/lib/chesstrainer_web/components/play_components.ex new file mode 100644 index 0000000..4a2f694 --- /dev/null +++ b/lib/chesstrainer_web/components/play_components.ex @@ -0,0 +1,268 @@ +defmodule ChesstrainerWeb.PlayComponents do + @moduledoc """ + The shared board and side panel for playing an endgame. + + Used by the standalone play screen and by a training session, which adds the + "Next puzzle" action via `session={true}`. + """ + + use ChesstrainerWeb, :html + + alias ChesstrainerWeb.EndgameLive.PlayCore + + attr :endgame, :any, required: true + attr :status, :atom, required: true + attr :blocked_reason, :string, default: nil + attr :best_move, :string, default: nil + attr :plies, :list, required: true + attr :line, :list, required: true + attr :reviewing, :boolean, required: true + attr :review_index, :integer, required: true + attr :review_tablebase, :any, default: nil + attr :review_blocked, :string, default: nil + attr :awaiting_reply, :boolean, required: true + attr :last_grade, :atom, default: nil + attr :awaiting_best_line, :boolean, default: false + attr :session, :boolean, default: false + + def play_surface(assigns) do + ~H""" +
+
+
+ +
+
+

+ {turn_label(@status, @awaiting_reply)} + You play {colour_name(@endgame.color)} +

+
+ +
+ <%= cond do %> + <% @status == :loading -> %> +

Loading tablebase…

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

Tablebase unavailable

+

{@blocked_reason}

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

+ {if @endgame.result == :draw, do: "Draw held!", else: "Solved!"} +

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

Failed

+

+ {if @endgame.result == :draw, + do: "That move loses the draw.", + else: "That move throws away the win."} +

+ <%= if @best_move && @plies != [] do %> +

+ You played {List.last(@plies).san}; best was: {@best_move} +

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

Opponent is replying…

+ <% @last_grade == :optimal -> %> +

Optimal move

+ <% @last_grade == :winning -> %> +

+ {if @endgame.result == :draw, + do: "Keeps the draw — but not the sharpest", + else: "Winning — but not the sharpest"} +

+ <% @last_grade == :losing -> %> +

+ {if @endgame.result == :draw, + do: "Losing move — this loses the draw", + else: "Losing move — this throws away the win"} +

+ <% @last_grade == :unknown -> %> +

Could not grade that move

+ <% true -> %> +

Make a move to have it graded.

+ <% end %> +

+ Puzzle rating: {round(@endgame.rating)} +

+
+ +
+ <%= cond do %> + <% @review_blocked -> %> +

Best move unavailable here

+

{@review_blocked}

+ <% @review_tablebase -> %> +

Best move:

+

{PlayCore.best_move_text(@review_tablebase) || "—"}

+ <%= if played_ply = played_ply_at(@line, @review_index) do %> +

Played: {played_ply.san}

+ <% end %> + <% true -> %> +

No best move.

+ <% end %> +
+ +
+ <% plies = display_plies(@reviewing, @line, @plies) %> +

Moves:

+
+ <%= if plies == [] do %> +

No Moves

+ <% else %> + <%= for {[white_ply, black_ply], move_no} <- move_rows(plies, @endgame.color) do %> +
+ {move_no}. + <%= if white_ply do %> + <.ply + ply={white_ply} + reviewing={@reviewing} + review_index={@review_index} + result={@endgame.result} + /> + <% else %> + ... + <% end %> + <%= if black_ply do %> + <.ply + ply={black_ply} + reviewing={@reviewing} + review_index={@review_index} + result={@endgame.result} + /> + <% end %> +
+ <% end %> + <% end %> +
+
+ +
+ <.button + :if={@status in [:solved, :failed] and not @reviewing} + phx-click="review" + > + <.icon name="hero-eye" /> Review + + <.button phx-click="reset" variant="primary"> + <.icon name="hero-arrow-path" /> + {if @status in [:solved, :failed], do: "Try again", else: "Reset"} + + <.button + :if={@session and @status in [:solved, :failed] and not @reviewing} + id="next-puzzle-button" + phx-click="next_puzzle" + variant="primary" + > + Next puzzle + +
+ +
+ <.button phx-click="review_prev" disabled={@review_index <= 0}>← + <.button phx-click="review_next" disabled={@review_index >= length(@line)}>→ + <.button + :if={@review_tablebase && PlayCore.best_move_text(@review_tablebase)} + phx-click="play_best_line" + disabled={@awaiting_best_line} + > + Play best line + + <.button :if={@line != @plies} phx-click="back_to_game">Back to game +
+
+
+ """ + end + + attr :ply, :map, required: true + attr :reviewing, :boolean, required: true + attr :review_index, :integer, required: true + attr :result, :atom, required: true + + defp ply(assigns) do + ~H""" + <%= if @reviewing do %> + + <% else %> + + {@ply.san} + + <% end %> + """ + end + + defp move_rows(plies, color) do + padded = if color in [:black, "black"], do: [nil | plies], else: plies + + padded + |> Enum.chunk_every(2, 2, [nil]) + |> Enum.with_index(1) + end + + defp display_plies(true, line, _plies), do: line + defp display_plies(false, _line, plies), do: plies + + defp turn_label(:playing, false), do: "Your move" + defp turn_label(:playing, true), do: "Opponent's move" + defp turn_label(:solved, _awaiting_reply), do: "Solved" + defp turn_label(:failed, _awaiting_reply), do: "Finished" + defp turn_label(:blocked, _awaiting_reply), do: "Unavailable" + defp turn_label(_status, _awaiting_reply), do: "Loading…" + + defp colour_name(:white), do: "White" + defp colour_name(:black), do: "Black" + defp colour_name(colour), do: colour |> to_string() |> String.capitalize() + + defp current_ply?(%{index: index}, review_index), do: index + 1 == review_index + + defp played_ply_at(line, review_index) do + case Enum.at(line, review_index) do + %{best_line: true} -> nil + ply -> ply + end + end + + defp ply_class(%{best_line: true}), do: "text-info italic" + defp ply_class(ply), do: grade_class(ply.grade) + + defp ply_title(%{best_line: true}, _result), do: "Best line" + defp ply_title(ply, result), do: grade_label(ply.grade, result) + + defp grade_class(:optimal), do: "text-success-text" + defp grade_class(:winning), do: "text-warning" + defp grade_class(:losing), do: "text-error" + defp grade_class(_), do: "text-body" + + defp grade_label(nil, _result), do: nil + defp grade_label(:optimal, _result), do: "Optimal move" + defp grade_label(:winning, :draw), do: "Keeps the draw — but not the sharpest" + defp grade_label(:winning, _result), do: "Winning — but not the sharpest" + defp grade_label(:losing, :draw), do: "Loses the draw" + defp grade_label(:losing, _result), do: "Throws away the win" + defp grade_label(:unknown, _result), do: "Not graded" +end diff --git a/lib/chesstrainer_web/live/endgame_live/play.ex b/lib/chesstrainer_web/live/endgame_live/play.ex index 8eef963..af2b3b4 100644 --- a/lib/chesstrainer_web/live/endgame_live/play.ex +++ b/lib/chesstrainer_web/live/endgame_live/play.ex @@ -1,10 +1,9 @@ defmodule ChesstrainerWeb.EndgameLive.Play do use ChesstrainerWeb, :live_view - alias Chesstrainer.Attempts alias Chesstrainer.Endgames - alias Chesstrainer.Endgames.Tablebase - alias Chesstrainer.Ratings + alias ChesstrainerWeb.EndgameLive.PlayCore + alias ChesstrainerWeb.PlayComponents @impl true def render(assigns) do @@ -39,140 +38,21 @@ defmodule ChesstrainerWeb.EndgameLive.Play do -
-
-
- -
-
- <%= cond do %> - <% @status == :loading -> %> -

Loading tablebase…

- <% @status == :blocked -> %> -

Tablebase unavailable

-

{@blocked_reason}

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

- {if @endgame.result == :draw, do: "Draw held!", else: "Solved!"} -

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

Failed

-

- {if @endgame.result == :draw, - do: "That move loses the draw.", - else: "That move throws away the win."} -

- <%= if @best_move && @plies != [] do %> -

- You played {List.last(@plies).san}; best was: {@best_move} -

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

Opponent is replying…

- <% @last_grade == :optimal -> %> -

Optimal move

- <% @last_grade == :winning -> %> -

- {if @endgame.result == :draw, - do: "Keeps the draw — but not the sharpest", - else: "Winning — but not the sharpest"} -

- <% @last_grade == :losing -> %> -

- {if @endgame.result == :draw, - do: "Losing move — this loses the draw", - else: "Losing move — this throws away the win"} -

- <% @last_grade == :unknown -> %> -

Could not grade that move

- <% true -> %> -

Make a move to have it graded.

- <% end %> -
- -
- <%= cond do %> - <% @review_blocked -> %> -

Best move unavailable here

-

{@review_blocked}

- <% @review_tablebase -> %> -

Best move:

-

{best_move_text(@review_tablebase) || "—"}

- <%= if played_ply = played_ply_at(@line, @review_index) do %> -

Played: {played_ply.san}

- <% end %> - <% true -> %> -

No best move.

- <% end %> -
- -
- <% plies = display_plies(@reviewing, @line, @plies) %> -

Moves:

-
- <%= if plies == [] do %> -

No Moves

- <% else %> - <%= for {[white_ply, black_ply], move_no} <- move_rows(plies, @endgame.color) do %> -
- {move_no}. - <%= if white_ply do %> - <.ply - ply={white_ply} - reviewing={@reviewing} - review_index={@review_index} - result={@endgame.result} - /> - <% else %> - ... - <% end %> - <%= if black_ply do %> - <.ply - ply={black_ply} - reviewing={@reviewing} - review_index={@review_index} - result={@endgame.result} - /> - <% end %> -
- <% end %> - <% end %> -
-
- -
- <.button - :if={@status in [:solved, :failed] and not @reviewing} - phx-click="review" - > - <.icon name="hero-eye" /> Review - - <.button phx-click="reset" variant="primary"> - <.icon name="hero-arrow-path" /> - {if @status in [:solved, :failed], do: "Try again", else: "Reset"} - -
- -
- <.button phx-click="review_prev" disabled={@review_index <= 0}>← - <.button phx-click="review_next" disabled={@review_index >= length(@line)}>→ - <.button - :if={@review_tablebase && best_move_text(@review_tablebase)} - phx-click="play_best_line" - disabled={@awaiting_best_line} - > - Play best line - - <.button :if={@line != @plies} phx-click="back_to_game">Back to game -
-
-
+ """ end @@ -181,637 +61,34 @@ defmodule ChesstrainerWeb.EndgameLive.Play do def mount(%{"public_code" => public_code}, _session, socket) do endgame = Endgames.get_endgame_by_public_code!(public_code) - socket = - socket - |> assign(:page_title, "Play endgame") - |> assign(:endgame, endgame) - |> assign(:user_rating, user_rating(socket.assigns.current_scope)) - |> assign(:fen, endgame.fen) - |> assign(:tablebase, nil) - |> assign(:status, :loading) - |> assign(:blocked_reason, nil) - |> assign(:best_move, nil) - |> assign(:plies, []) - |> assign(:reviewing, false) - |> assign(:review_index, 0) - |> assign(:pending_reply, nil) - |> assign(:snapshots, %{}) - |> assign(:line, []) - |> assign(:review_tablebase, nil) - |> assign(:review_blocked, nil) - |> assign(:awaiting_best_line, false) - |> assign(:pending_best_move, nil) - |> assign(:last_san, "None yet") - |> assign(:last_from_to, "None yet") - |> assign(:last_grade, nil) - |> assign(:awaiting_reply, false) - - {:ok, load_attempt(socket)} + {:ok, PlayCore.init(socket, endgame)} end @impl true - def handle_event("endgame_move_played", params, socket) do - %{"from" => from, "to" => to, "san" => san} = params - promotion = params["promotion"] - draw = params["draw"] || false - prev_fen = params["prev_fen"] || socket.assigns.fen - fen_after = params["fen"] || socket.assigns.fen + def handle_event("endgame_move_played", params, socket), + do: PlayCore.move_played(socket, params) - cond do - socket.assigns.status == :blocked -> - {:noreply, - put_flash(socket, :error, "The tablebase is unavailable, so this move cannot be graded.")} + def handle_event("opponent_reply_applied", params, socket), + do: PlayCore.opponent_reply_applied(socket, params) - socket.assigns.status != :playing -> - {:noreply, socket} + def handle_event("chess_fen_invalid", params, socket), + do: PlayCore.fen_invalid(socket, params) - not same_position?(prev_fen, socket.assigns.fen) -> - {:noreply, - put_flash(socket, :error, "That move is out of sequence. Press Reset to try again.")} + def handle_event("reset", _params, socket), do: PlayCore.reset(socket) - true -> - grade_and_record(socket, from, to, promotion, san, fen_after, draw) - end - end + def handle_event("review", _params, socket), do: PlayCore.review(socket) - def handle_event("opponent_reply_applied", params, socket) do - %{"fen" => fen} = params - draw = params["draw"] || false + def handle_event("review_prev", _params, socket), do: PlayCore.review_prev(socket) - cond do - not socket.assigns.awaiting_reply -> - {:noreply, socket} + def handle_event("review_next", _params, socket), do: PlayCore.review_next(socket) - true -> - socket = record_opponent_ply(socket, fen, params["san"]) + def handle_event("review_step", %{"index" => index}, socket), + do: PlayCore.review_step(socket, index) - if draw and socket.assigns.endgame.result == :draw do - solve_attempt(socket) - else - case Tablebase.new(fen) do - {:ok, tablebase} -> - {:noreply, - socket - |> assign(:fen, fen) - |> assign(:tablebase, tablebase) - |> snapshot(fen, tablebase) - |> assign(:awaiting_reply, false) - |> assign(:status, :playing) - |> assign(:blocked_reason, nil) - |> push_event("resume_board", %{})} + def handle_event("play_best_line", _params, socket), do: PlayCore.play_best_line(socket) - other -> - {:noreply, - socket - |> assign(:awaiting_reply, false) - |> assign(:status, :blocked) - |> assign(:blocked_reason, blocked_reason(other))} - end - end - end - end + def handle_event("best_line_move_applied", params, socket), + do: PlayCore.best_line_move_applied(socket, params) - def handle_event("chess_fen_invalid", %{"fen" => fen, "message" => message}, socket) do - {:noreply, - put_flash( - socket, - :error, - "Endgame FEN is invalid and the board cannot be loaded: #{message} (#{fen})" - )} - end - - def handle_event("reset", _params, socket) do - socket = - socket - |> assign(:plies, []) - |> assign(:reviewing, false) - |> assign(:review_index, 0) - |> assign(:pending_reply, nil) - |> assign(:snapshots, %{}) - |> assign(:line, []) - |> assign(:review_tablebase, nil) - |> assign(:review_blocked, nil) - |> assign(:awaiting_best_line, false) - |> assign(:pending_best_move, nil) - |> assign(:last_san, "None yet") - |> assign(:last_from_to, "None yet") - |> assign(:last_grade, nil) - - {:noreply, load_attempt(socket)} - end - - def handle_event("review", _params, socket) do - if socket.assigns.status in [:solved, :failed] do - socket = - socket - |> assign(:reviewing, true) - |> assign(:line, socket.assigns.plies) - |> set_review_index(length(socket.assigns.plies)) - - {:noreply, push_review_position(socket)} - else - {:noreply, socket} - end - end - - def handle_event("review_prev", _params, socket), do: step_review(socket, -1) - - def handle_event("review_next", _params, socket), do: step_review(socket, 1) - - def handle_event("review_step", %{"index" => index}, socket) do - if socket.assigns.reviewing do - last = length(socket.assigns.line) - index = parse_index(index) |> max(0) |> min(last) - - {:noreply, push_review_position(set_review_index(socket, index))} - else - {:noreply, socket} - end - end - - def handle_event("play_best_line", _params, socket) do - with true <- socket.assigns.reviewing, - %Tablebase{} = tablebase <- socket.assigns.review_tablebase, - %Tablebase.Move{} = move <- pick_best_move(tablebase) do - # Branch the review line at the current position, then play one best move. - {:noreply, - socket - |> assign(:line, Enum.take(socket.assigns.line, socket.assigns.review_index)) - |> assign(:awaiting_best_line, true) - |> assign(:pending_best_move, move) - |> push_event("best_line_move", reply_payload(move))} - else - _ -> {:noreply, socket} - end - end - - def handle_event("best_line_move_applied", %{"fen" => fen}, socket) do - if socket.assigns.awaiting_best_line do - move = socket.assigns.pending_best_move - - line = - socket.assigns.line ++ - [ - %{ - index: length(socket.assigns.line), - san: move.san, - fen_after: fen, - grade: nil, - best_line: true - } - ] - - socket = - socket - |> assign(:line, line) - |> assign(:awaiting_best_line, false) - |> assign(:pending_best_move, nil) - |> set_review_index(length(line)) - - {:noreply, push_review_position(socket)} - else - {:noreply, socket} - end - end - - def handle_event("back_to_game", _params, socket) do - if socket.assigns.reviewing do - socket = - socket - |> assign(:line, socket.assigns.plies) - |> set_review_index(length(socket.assigns.plies)) - - {:noreply, push_review_position(socket)} - else - {:noreply, socket} - end - end - - attr :ply, :map, required: true - attr :reviewing, :boolean, required: true - attr :review_index, :integer, required: true - attr :result, :atom, required: true - - defp ply(assigns) do - ~H""" - <%= if @reviewing do %> - - <% else %> - - {@ply.san} - - <% end %> - """ - end - - defp move_rows(plies, color) do - padded = if color in [:black, "black"], do: [nil | plies], else: plies - - padded - |> Enum.chunk_every(2, 2, [nil]) - |> Enum.with_index(1) - end - - defp positions(start_fen, plies), do: [start_fen | Enum.map(plies, & &1.fen_after)] - - defp display_plies(true, line, _plies), do: line - defp display_plies(false, _line, plies), do: plies - - defp push_review_position(socket) do - fen = - socket.assigns.endgame.fen - |> positions(socket.assigns.line) - |> Enum.at(socket.assigns.review_index) - - push_event(socket, "review_position", %{fen: fen}) - end - - defp set_review_index(socket, index) do - socket - |> assign(:review_index, index) - |> update_review_tablebase() - end - - defp update_review_tablebase(socket) do - fen = - socket.assigns.endgame.fen - |> positions(socket.assigns.line) - |> Enum.at(socket.assigns.review_index) - - case snapshot_or_fetch(socket, fen) do - {:ok, tablebase, socket} -> - assign(socket, review_tablebase: tablebase, review_blocked: nil) - - {:unavailable, reason, socket} -> - assign(socket, review_tablebase: nil, review_blocked: reason) - end - end - - defp snapshot_or_fetch(socket, fen) do - case Map.fetch(socket.assigns.snapshots, fen) do - {:ok, tablebase} -> - {:ok, tablebase, socket} - - :error -> - case Tablebase.new(fen) do - {:ok, tablebase} -> {:ok, tablebase, snapshot(socket, fen, tablebase)} - other -> {:unavailable, blocked_reason(other), socket} - end - end - end - - defp snapshot(socket, fen, tablebase) do - assign(socket, :snapshots, Map.put(socket.assigns.snapshots, fen, tablebase)) - end - - defp step_review(socket, delta) do - if socket.assigns.reviewing do - last = length(socket.assigns.line) - index = (socket.assigns.review_index + delta) |> max(0) |> min(last) - - {:noreply, socket |> set_review_index(index) |> push_review_position()} - else - {:noreply, socket} - end - end - - defp parse_index(index) when is_integer(index), do: index - defp parse_index(index) when is_binary(index), do: String.to_integer(index) - - defp current_ply?(%{index: index}, review_index), do: index + 1 == review_index - - defp played_ply_at(line, review_index) do - case Enum.at(line, review_index) do - %{best_line: true} -> nil - ply -> ply - end - end - - defp ply_class(%{best_line: true}), do: "text-info italic" - defp ply_class(ply), do: grade_class(ply.grade) - - defp ply_title(%{best_line: true}, _result), do: "Best line" - defp ply_title(ply, result), do: grade_label(ply.grade, result) - - defp grade_class(:optimal), do: "text-success-text" - defp grade_class(:winning), do: "text-warning" - defp grade_class(:losing), do: "text-error" - defp grade_class(_), do: "text-body" - - defp grade_label(nil, _result), do: nil - defp grade_label(:optimal, _result), do: "Optimal move" - defp grade_label(:winning, :draw), do: "Keeps the draw — but not the sharpest" - defp grade_label(:winning, _result), do: "Winning — but not the sharpest" - defp grade_label(:losing, :draw), do: "Loses the draw" - defp grade_label(:losing, _result), do: "Throws away the win" - defp grade_label(:unknown, _result), do: "Not graded" - - defp load_attempt(socket) do - fen = socket.assigns.endgame.fen - - 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) - |> snapshot(fen, tablebase) - |> assign(:status, :playing) - |> assign(:blocked_reason, nil) - |> push_init_board(fen) - - other -> - socket - |> assign(:tablebase, nil) - |> assign(:status, :blocked) - |> assign(:blocked_reason, blocked_reason(other)) - |> push_init_board(fen) - end - else - assign(socket, :status, :loading) - end - end - - defp push_init_board(socket, fen) do - push_event(socket, "init_board", %{ - fen: fen, - orientation: Atom.to_string(socket.assigns.endgame.color), - player_color: Atom.to_string(socket.assigns.endgame.color), - blocked: socket.assigns.status == :blocked - }) - end - - defp blocked_reason({:cooldown, remaining_ms}) do - seconds = max(div(remaining_ms + 999, 1000), 1) - "The tablebase is rate-limited. Try again in about #{seconds}s." - end - - defp blocked_reason({:error, {:too_many_requests, _, _}}) do - "The tablebase is rate-limited. Try again in a minute." - end - - defp blocked_reason({:error, {:client_error, 404, _}}) do - "This position is not covered by the tablebase." - end - - defp blocked_reason({:error, :not_covered}) do - "This position is not covered by the tablebase." - end - - defp blocked_reason({:error, reason}) do - "The tablebase is unavailable (#{inspect(reason)})." - end - - defp grade_and_record(socket, from, to, promotion, san, fen_after, draw) 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 -> - grade = grade_move(socket.assigns.tablebase, move) - - ply = %{ - index: length(socket.assigns.plies), - san: san, - fen_after: fen_after, - grade: grade - } - - socket = - socket - |> assign(:last_from_to, "#{from} ➔ #{to}") - |> assign(:last_san, san) - |> assign(:last_grade, grade) - |> assign(:plies, socket.assigns.plies ++ [ply]) - - cond do - grade == :losing -> - fail_attempt(socket) - - grade not in [:optimal, :winning] -> - {:noreply, socket} - - draw and socket.assigns.endgame.result == :draw -> - # A drawn-by-rule position is the goal of a draw puzzle. - solve_attempt(socket) - - socket.assigns.endgame.result == :win and not is_nil(promotion) -> - # Conversion cutoff: a promotion that keeps the win ends a win puzzle. - solve_attempt(socket) - - 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} -> - socket = snapshot(socket, fen_after, tablebase) - reply_to(socket, tablebase) - - other -> - {:noreply, - socket - |> assign(:status, :blocked) - |> assign(:blocked_reason, blocked_reason(other))} - end - end - - defp reply_to(socket, %Tablebase{checkmate: true}), do: solve_attempt(socket) - - defp reply_to(socket, %Tablebase{moves: [reply | _]}) do - {:noreply, - socket - |> assign(:awaiting_reply, true) - |> assign(:pending_reply, %{san: reply.san, uci: reply.uci}) - |> push_event("opponent_move", reply_payload(reply))} - end - - defp reply_to(socket, %Tablebase{}) do - # Terminal non-mate position (stalemate/insufficient): no reply to play. - {:noreply, socket} - end - - defp solve_attempt(socket) do - {:ok, endgame} = Endgames.record_solve(socket.assigns.endgame) - - socket = - socket - |> assign(:endgame, endgame) - |> record_attempt(:solved) - - {:noreply, - socket - |> assign(:status, :solved) - |> assign(:awaiting_reply, false) - |> assign(:best_move, nil)} - end - - defp fail_attempt(socket) do - socket = record_attempt(socket, :failed) - - {:noreply, - socket - |> assign(:status, :failed) - |> assign(:awaiting_reply, false) - |> assign(:best_move, best_move_text(socket.assigns.tablebase))} - end - - defp record_attempt(socket, outcome) do - case Attempts.record_attempt(socket.assigns.current_scope, socket.assigns.endgame, outcome) do - {:ok, attempt} -> - case Ratings.rate_attempt(attempt) do - {:ok, %{user: user, endgame: endgame}} -> - socket - |> assign(:endgame, endgame) - |> assign(:user_rating, user.rating) - - {:skipped, _attempt} -> - put_flash( - socket, - :info, - "Replay recorded. Your rating is unchanged because you played this recently." - ) - end - - _ -> - socket - end - end - - defp user_rating(%{user: %{rating: rating}}), do: rating - defp user_rating(_), do: nil - - defp best_move_text(tablebase) do - san = - tablebase - |> best_moves() - |> Enum.map(& &1.san) - |> Enum.reject(&is_nil/1) - |> Enum.take(3) - |> Enum.join(", ") - - if san == "", do: nil, else: san - end - - defp pick_best_move(tablebase), do: tablebase |> best_moves() |> List.first() - - defp best_moves(%Tablebase{moves: moves} = tablebase) when is_list(moves) do - case {outcome_rank(tablebase.category), moves} do - {nil, _} -> - [] - - {_best_rank, []} -> - [] - - {best_rank, [best | _]} -> - Enum.filter(moves, fn move -> - outcome_rank(mover_outcome(move.category)) == best_rank and move.dtz == best.dtz - end) - end - end - - defp best_moves(_tablebase), do: [] - - defp record_opponent_ply(socket, fen, client_san) do - san = - case socket.assigns.pending_reply do - %{san: san} when is_binary(san) -> san - _ -> client_san || "…" - end - - ply = %{ - index: length(socket.assigns.plies), - san: san, - fen_after: fen, - grade: nil - } - - socket - |> assign(:plies, socket.assigns.plies ++ [ply]) - |> assign(:pending_reply, nil) - 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 || ""}" - Enum.find(moves, &(&1.uci == uci)) - end - - defp find_move(_tablebase, _from, _to, _promotion), do: nil - - # Compare only the board and side to move: chess.js may normalise the rest - # (castling/en-passant/halfmove/fullmove) differently from the stored FEN. - defp same_position?(fen_a, fen_b), do: position_key(fen_a) == position_key(fen_b) - - defp position_key(fen) do - case String.split(fen, " ") do - [board, active | _] -> {board, active} - _ -> fen - end - end - - defp grade_move(%Tablebase{moves: []}, _move), do: :unknown - - defp grade_move(%Tablebase{category: position_category, moves: [best | _]}, move) do - best_rank = outcome_rank(position_category) - move_rank = outcome_rank(mover_outcome(move.category)) - - cond do - is_nil(best_rank) or is_nil(move_rank) -> :unknown - move_rank < best_rank -> :losing - move.dtz == best.dtz -> :optimal - true -> :winning - end - end - - # The mover's outcome is the flip of `category`, which is reported from the - # perspective of the side to move *after* the move. - defp mover_outcome(:loss), do: :win - defp mover_outcome(:win), do: :loss - defp mover_outcome(:draw), do: :draw - defp mover_outcome(_), do: :unknown - - defp outcome_rank(:win), do: 2 - defp outcome_rank(:draw), do: 1 - defp outcome_rank(:loss), do: 0 - defp outcome_rank(_), do: nil + def handle_event("back_to_game", _params, socket), do: PlayCore.back_to_game(socket) end diff --git a/lib/chesstrainer_web/live/endgame_live/play_core.ex b/lib/chesstrainer_web/live/endgame_live/play_core.ex new file mode 100644 index 0000000..7ae5732 --- /dev/null +++ b/lib/chesstrainer_web/live/endgame_live/play_core.ex @@ -0,0 +1,591 @@ +defmodule ChesstrainerWeb.EndgameLive.PlayCore do + @moduledoc """ + Shared per-puzzle play logic. + + Used by `ChesstrainerWeb.EndgameLive.Play` (standalone play, optional auth) + and `ChesstrainerWeb.EndgameLive.Train` (a session of puzzles). Every public + function takes and returns the LiveView socket, or a `{:noreply, socket}` + tuple, so each LiveView keeps its own `handle_event/3` entry points and + delegates here. + + The board hook pushes events to whichever LiveView renders it, so this module + never assumes a particular parent. + """ + + import Phoenix.Component, only: [assign: 2, assign: 3, assign_new: 3] + import Phoenix.LiveView, only: [connected?: 1, push_event: 3, put_flash: 3] + + alias Chesstrainer.Attempts + alias Chesstrainer.Endgames + alias Chesstrainer.Endgames.Tablebase + alias Chesstrainer.Ratings + + @doc """ + Loads `endgame` and starts an attempt on it. + + `:page_title` overrides the default "Play endgame". The user's rating is only + assigned when it is not already present, so a session keeps the rating it has + already advanced. + """ + def init(socket, endgame, opts \\ []) do + socket + |> assign(:page_title, Keyword.get(opts, :page_title, "Play endgame")) + |> assign(:endgame, endgame) + |> assign_new(:user_rating, fn -> user_rating(socket.assigns.current_scope) end) + |> assign(:fen, endgame.fen) + |> assign(:tablebase, nil) + |> assign(:status, :loading) + |> assign(:blocked_reason, nil) + |> assign(:best_move, nil) + |> assign(:plies, []) + |> assign(:reviewing, false) + |> assign(:review_index, 0) + |> assign(:pending_reply, nil) + |> assign(:snapshots, %{}) + |> assign(:line, []) + |> assign(:review_tablebase, nil) + |> assign(:review_blocked, nil) + |> assign(:awaiting_best_line, false) + |> assign(:pending_best_move, nil) + |> assign(:last_san, "None yet") + |> assign(:last_from_to, "None yet") + |> assign(:last_grade, nil) + |> assign(:awaiting_reply, false) + |> assign(:last_rating_delta, nil) + |> load_attempt() + end + + def move_played(socket, params) do + %{"from" => from, "to" => to, "san" => san} = params + promotion = params["promotion"] + draw = params["draw"] || false + prev_fen = params["prev_fen"] || socket.assigns.fen + fen_after = params["fen"] || socket.assigns.fen + + cond do + 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.")} + + true -> + grade_and_record(socket, from, to, promotion, san, fen_after, draw) + end + end + + def opponent_reply_applied(socket, params) do + %{"fen" => fen} = params + draw = params["draw"] || false + + if socket.assigns.awaiting_reply do + socket = record_opponent_ply(socket, fen, params["san"]) + + if draw and socket.assigns.endgame.result == :draw do + solve_attempt(socket) + else + case Tablebase.new(fen) do + {:ok, tablebase} -> + {:noreply, + socket + |> assign(:fen, fen) + |> assign(:tablebase, tablebase) + |> snapshot(fen, 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 + end + else + {:noreply, socket} + end + end + + def fen_invalid(socket, %{"fen" => fen, "message" => message}) do + {:noreply, + put_flash( + socket, + :error, + "Endgame FEN is invalid and the board cannot be loaded: #{message} (#{fen})" + )} + end + + def reset(socket) do + socket = + socket + |> assign(:plies, []) + |> assign(:reviewing, false) + |> assign(:review_index, 0) + |> assign(:pending_reply, nil) + |> assign(:snapshots, %{}) + |> assign(:line, []) + |> assign(:review_tablebase, nil) + |> assign(:review_blocked, nil) + |> assign(:awaiting_best_line, false) + |> assign(:pending_best_move, nil) + |> assign(:last_san, "None yet") + |> assign(:last_from_to, "None yet") + |> assign(:last_grade, nil) + |> assign(:last_rating_delta, nil) + + {:noreply, load_attempt(socket)} + end + + def review(socket) do + if socket.assigns.status in [:solved, :failed] do + socket = + socket + |> assign(:reviewing, true) + |> assign(:line, socket.assigns.plies) + |> set_review_index(length(socket.assigns.plies)) + + {:noreply, push_review_position(socket)} + else + {:noreply, socket} + end + end + + def review_prev(socket), do: step_review(socket, -1) + + def review_next(socket), do: step_review(socket, 1) + + def review_step(socket, index) do + if socket.assigns.reviewing do + last = length(socket.assigns.line) + index = parse_index(index) |> max(0) |> min(last) + + {:noreply, push_review_position(set_review_index(socket, index))} + else + {:noreply, socket} + end + end + + def play_best_line(socket) do + with true <- socket.assigns.reviewing, + %Tablebase{} = tablebase <- socket.assigns.review_tablebase, + %Tablebase.Move{} = move <- pick_best_move(tablebase) do + # Branch the review line at the current position, then play one best move. + {:noreply, + socket + |> assign(:line, Enum.take(socket.assigns.line, socket.assigns.review_index)) + |> assign(:awaiting_best_line, true) + |> assign(:pending_best_move, move) + |> push_event("best_line_move", reply_payload(move))} + else + _ -> {:noreply, socket} + end + end + + def best_line_move_applied(socket, %{"fen" => fen}) do + if socket.assigns.awaiting_best_line do + move = socket.assigns.pending_best_move + + line = + socket.assigns.line ++ + [ + %{ + index: length(socket.assigns.line), + san: move.san, + fen_after: fen, + grade: nil, + best_line: true + } + ] + + socket = + socket + |> assign(:line, line) + |> assign(:awaiting_best_line, false) + |> assign(:pending_best_move, nil) + |> set_review_index(length(line)) + + {:noreply, push_review_position(socket)} + else + {:noreply, socket} + end + end + + def back_to_game(socket) do + if socket.assigns.reviewing do + socket = + socket + |> assign(:line, socket.assigns.plies) + |> set_review_index(length(socket.assigns.plies)) + + {:noreply, push_review_position(socket)} + else + {:noreply, socket} + end + end + + @doc "The best available move as a display string, or nil." + def best_move_text(tablebase) do + san = + tablebase + |> best_moves() + |> Enum.map(& &1.san) + |> Enum.reject(&is_nil/1) + |> Enum.take(3) + |> Enum.join(", ") + + if san == "", do: nil, else: san + end + + defp load_attempt(socket) do + fen = socket.assigns.endgame.fen + + 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) + |> snapshot(fen, tablebase) + |> assign(:status, :playing) + |> assign(:blocked_reason, nil) + |> push_init_board(fen) + + other -> + socket + |> assign(:tablebase, nil) + |> assign(:status, :blocked) + |> assign(:blocked_reason, blocked_reason(other)) + |> push_init_board(fen) + end + else + assign(socket, :status, :loading) + end + end + + defp push_init_board(socket, fen) do + push_event(socket, "init_board", %{ + fen: fen, + orientation: Atom.to_string(socket.assigns.endgame.color), + player_color: Atom.to_string(socket.assigns.endgame.color), + blocked: socket.assigns.status == :blocked + }) + end + + defp blocked_reason({:cooldown, remaining_ms}) do + seconds = max(div(remaining_ms + 999, 1000), 1) + "The tablebase is rate-limited. Try again in about #{seconds}s." + end + + defp blocked_reason({:error, {:too_many_requests, _, _}}) do + "The tablebase is rate-limited. Try again in a minute." + end + + defp blocked_reason({:error, {:client_error, 404, _}}) do + "This position is not covered by the tablebase." + end + + defp blocked_reason({:error, :not_covered}) do + "This position is not covered by the tablebase." + end + + defp blocked_reason({:error, reason}) do + "The tablebase is unavailable (#{inspect(reason)})." + end + + defp grade_and_record(socket, from, to, promotion, san, fen_after, draw) 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 -> + grade = grade_move(socket.assigns.tablebase, move) + + ply = %{ + index: length(socket.assigns.plies), + san: san, + fen_after: fen_after, + grade: grade + } + + socket = + socket + |> assign(:last_from_to, "#{from} ➔ #{to}") + |> assign(:last_san, san) + |> assign(:last_grade, grade) + |> assign(:plies, socket.assigns.plies ++ [ply]) + + cond do + grade == :losing -> + fail_attempt(socket) + + grade not in [:optimal, :winning] -> + {:noreply, socket} + + draw and socket.assigns.endgame.result == :draw -> + # A drawn-by-rule position is the goal of a draw puzzle. + solve_attempt(socket) + + socket.assigns.endgame.result == :win and not is_nil(promotion) -> + # Conversion cutoff: a promotion that keeps the win ends a win puzzle. + solve_attempt(socket) + + 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} -> + socket = snapshot(socket, fen_after, tablebase) + reply_to(socket, tablebase) + + other -> + {:noreply, + socket + |> assign(:status, :blocked) + |> assign(:blocked_reason, blocked_reason(other))} + end + end + + defp reply_to(socket, %Tablebase{checkmate: true}), do: solve_attempt(socket) + + defp reply_to(socket, %Tablebase{moves: [reply | _]}) do + {:noreply, + socket + |> assign(:awaiting_reply, true) + |> assign(:pending_reply, %{san: reply.san, uci: reply.uci}) + |> push_event("opponent_move", reply_payload(reply))} + end + + defp reply_to(socket, %Tablebase{}) do + # Terminal non-mate position (stalemate/insufficient): no reply to play. + {:noreply, socket} + end + + defp solve_attempt(socket) do + {:ok, endgame} = Endgames.record_solve(socket.assigns.endgame) + + socket = + socket + |> assign(:endgame, endgame) + |> record_attempt(:solved) + + {:noreply, + socket + |> assign(:status, :solved) + |> assign(:awaiting_reply, false) + |> assign(:best_move, nil)} + end + + defp fail_attempt(socket) do + socket = record_attempt(socket, :failed) + + {:noreply, + socket + |> assign(:status, :failed) + |> assign(:awaiting_reply, false) + |> assign(:best_move, best_move_text(socket.assigns.tablebase))} + end + + defp record_attempt(socket, outcome) do + case Attempts.record_attempt(socket.assigns.current_scope, socket.assigns.endgame, outcome) do + {:ok, attempt} -> + case Ratings.rate_attempt(attempt) do + {:ok, %{user: user, endgame: endgame, user_delta: delta}} -> + socket + |> assign(:endgame, endgame) + |> assign(:user_rating, user.rating) + |> assign(:last_rating_delta, delta) + + {:skipped, _attempt} -> + socket + |> assign(:last_rating_delta, nil) + |> put_flash( + :info, + "Replay recorded. Your rating is unchanged because you played this recently." + ) + end + + _ -> + assign(socket, :last_rating_delta, nil) + end + end + + defp user_rating(%{user: %{rating: rating}}), do: rating + defp user_rating(_), do: nil + + defp pick_best_move(tablebase), do: tablebase |> best_moves() |> List.first() + + defp best_moves(%Tablebase{moves: moves} = tablebase) when is_list(moves) do + case {outcome_rank(tablebase.category), moves} do + {nil, _} -> + [] + + {_best_rank, []} -> + [] + + {best_rank, [best | _]} -> + Enum.filter(moves, fn move -> + outcome_rank(mover_outcome(move.category)) == best_rank and move.dtz == best.dtz + end) + end + end + + defp best_moves(_tablebase), do: [] + + defp record_opponent_ply(socket, fen, client_san) do + san = + case socket.assigns.pending_reply do + %{san: san} when is_binary(san) -> san + _ -> client_san || "…" + end + + ply = %{ + index: length(socket.assigns.plies), + san: san, + fen_after: fen, + grade: nil + } + + socket + |> assign(:plies, socket.assigns.plies ++ [ply]) + |> assign(:pending_reply, nil) + 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 || ""}" + Enum.find(moves, &(&1.uci == uci)) + end + + defp find_move(_tablebase, _from, _to, _promotion), do: nil + + # Compare only the board and side to move: chess.js may normalise the rest + # (castling/en-passant/halfmove/fullmove) differently from the stored FEN. + defp same_position?(fen_a, fen_b), do: position_key(fen_a) == position_key(fen_b) + + defp position_key(fen) do + case String.split(fen, " ") do + [board, active | _] -> {board, active} + _ -> fen + end + end + + defp grade_move(%Tablebase{moves: []}, _move), do: :unknown + + defp grade_move(%Tablebase{category: position_category, moves: [best | _]}, move) do + best_rank = outcome_rank(position_category) + move_rank = outcome_rank(mover_outcome(move.category)) + + cond do + is_nil(best_rank) or is_nil(move_rank) -> :unknown + move_rank < best_rank -> :losing + move.dtz == best.dtz -> :optimal + true -> :winning + end + end + + # The mover's outcome is the flip of `category`, which is reported from the + # perspective of the side to move *after* the move. + defp mover_outcome(:loss), do: :win + defp mover_outcome(:win), do: :loss + defp mover_outcome(:draw), do: :draw + defp mover_outcome(_), do: :unknown + + defp outcome_rank(:win), do: 2 + defp outcome_rank(:draw), do: 1 + defp outcome_rank(:loss), do: 0 + defp outcome_rank(_), do: nil + + defp positions(start_fen, plies), do: [start_fen | Enum.map(plies, & &1.fen_after)] + + defp push_review_position(socket) do + fen = + socket.assigns.endgame.fen + |> positions(socket.assigns.line) + |> Enum.at(socket.assigns.review_index) + + push_event(socket, "review_position", %{fen: fen}) + end + + defp set_review_index(socket, index) do + socket + |> assign(:review_index, index) + |> update_review_tablebase() + end + + defp update_review_tablebase(socket) do + fen = + socket.assigns.endgame.fen + |> positions(socket.assigns.line) + |> Enum.at(socket.assigns.review_index) + + case snapshot_or_fetch(socket, fen) do + {:ok, tablebase, socket} -> + assign(socket, review_tablebase: tablebase, review_blocked: nil) + + {:unavailable, reason, socket} -> + assign(socket, review_tablebase: nil, review_blocked: reason) + end + end + + defp snapshot_or_fetch(socket, fen) do + case Map.fetch(socket.assigns.snapshots, fen) do + {:ok, tablebase} -> + {:ok, tablebase, socket} + + :error -> + case Tablebase.new(fen) do + {:ok, tablebase} -> {:ok, tablebase, snapshot(socket, fen, tablebase)} + other -> {:unavailable, blocked_reason(other), socket} + end + end + end + + defp snapshot(socket, fen, tablebase) do + assign(socket, :snapshots, Map.put(socket.assigns.snapshots, fen, tablebase)) + end + + defp step_review(socket, delta) do + if socket.assigns.reviewing do + last = length(socket.assigns.line) + index = (socket.assigns.review_index + delta) |> max(0) |> min(last) + + {:noreply, socket |> set_review_index(index) |> push_review_position()} + else + {:noreply, socket} + end + end + + defp parse_index(index) when is_integer(index), do: index + defp parse_index(index) when is_binary(index), do: String.to_integer(index) +end diff --git a/lib/chesstrainer_web/live/endgame_live/train.ex b/lib/chesstrainer_web/live/endgame_live/train.ex new file mode 100644 index 0000000..963494c --- /dev/null +++ b/lib/chesstrainer_web/live/endgame_live/train.ex @@ -0,0 +1,300 @@ +defmodule ChesstrainerWeb.EndgameLive.Train do + @moduledoc """ + A training session: choose a difficulty, then play a run of puzzles in place. + + The session (difficulty, start time, rating baseline, completed count and + timing) lives only in this LiveView. Each puzzle's move grading, opponent + reply and review come from `ChesstrainerWeb.EndgameLive.PlayCore`. + """ + + use ChesstrainerWeb, :live_view + + alias Chesstrainer.Puzzles + alias ChesstrainerWeb.EndgameLive.PlayCore + alias ChesstrainerWeb.PlayComponents + + @impl true + def render(assigns) do + ~H""" + + <.header> + Train + <:subtitle> + <%= if @session do %> + {difficulty_label(@session.difficulty)} · Play a run of endgame puzzles. + <% else %> + Choose a difficulty to start a session. + <% end %> + + <:actions> + <.button :if={@session} phx-click="stop_session"> + <.icon name="hero-x-mark" /> Stop session + + <.button navigate={~p"/endgames"}> + <.icon name="hero-arrow-left" /> Endgames + + + + + <%= if @session do %> +
+ + Difficulty + {difficulty_label(@session.difficulty)} + + + Time + + {format_duration(elapsed_ms(@session))} + + + + Avg/puzzle + {format_duration(avg_ms(@session))} + + + Rating + + {format_delta(net_gain(@session, @user_rating))} + + + + Last + + {format_delta(@last_rating_delta)} + + +
+ + + <% else %> +
+
+

Choose a difficulty

+

+ Your rating: {round(@user_rating)} · bands of ±{Puzzles.band_width()} +

+
+ <%= for {difficulty, label, description} <- difficulty_options(@user_rating) do %> + <.button + id={"difficulty-#{difficulty}"} + phx-click="start_session" + phx-value-difficulty={Atom.to_string(difficulty)} + variant={if difficulty == :medium, do: "primary", else: "secondary"} + class="w-full justify-between" + > + {label} + {description} + + <% end %> +
+
+
+ <% end %> +
+ """ + end + + @impl true + def mount(_params, _session, socket) do + {:ok, + socket + |> assign(:page_title, "Train") + |> assign(:session, nil) + |> assign(:puzzle_started_mono, nil) + |> assign(:puzzle_counted, false) + |> assign(:user_rating, socket.assigns.current_scope.user.rating)} + end + + @impl true + def handle_event("start_session", %{"difficulty" => difficulty}, socket) do + difficulty = parse_difficulty(difficulty) + + case Puzzles.next_endgame(selection_user(socket), difficulty) do + nil -> + {:noreply, put_flash(socket, :error, "No puzzles are available right now.")} + + endgame -> + session = %{ + difficulty: difficulty, + started_at_ms: System.system_time(:millisecond), + baseline: socket.assigns.user_rating, + count: 0, + sum_ms: 0 + } + + socket = + socket + |> assign(:session, session) + |> assign(:puzzle_started_mono, System.monotonic_time(:millisecond)) + |> assign(:puzzle_counted, false) + |> assign(:last_rating_delta, nil) + |> PlayCore.init(endgame, page_title: "Train") + + {:noreply, socket} + end + end + + def handle_event("next_puzzle", _params, socket) do + session = socket.assigns.session + + if session do + case Puzzles.next_endgame(selection_user(socket), session.difficulty, + exclude_ids: [socket.assigns.endgame.id] + ) do + nil -> + {:noreply, put_flash(socket, :info, "No more puzzles at this difficulty.")} + + endgame -> + socket = + socket + |> assign(:puzzle_started_mono, System.monotonic_time(:millisecond)) + |> assign(:puzzle_counted, false) + |> assign(:last_rating_delta, nil) + |> PlayCore.init(endgame, page_title: "Train") + + {:noreply, socket} + end + else + {:noreply, socket} + end + end + + def handle_event("stop_session", _params, socket) do + {:noreply, assign(socket, :session, nil)} + end + + def handle_event("endgame_move_played", params, socket) do + {:noreply, socket} = PlayCore.move_played(socket, params) + {:noreply, account_completion(socket)} + end + + def handle_event("opponent_reply_applied", params, socket) do + {:noreply, socket} = PlayCore.opponent_reply_applied(socket, params) + {:noreply, account_completion(socket)} + end + + def handle_event("chess_fen_invalid", params, socket), + do: PlayCore.fen_invalid(socket, params) + + def handle_event("reset", _params, socket), do: PlayCore.reset(socket) + + def handle_event("review", _params, socket), do: PlayCore.review(socket) + + def handle_event("review_prev", _params, socket), do: PlayCore.review_prev(socket) + + def handle_event("review_next", _params, socket), do: PlayCore.review_next(socket) + + def handle_event("review_step", %{"index" => index}, socket), + do: PlayCore.review_step(socket, index) + + def handle_event("play_best_line", _params, socket), do: PlayCore.play_best_line(socket) + + def handle_event("best_line_move_applied", params, socket), + do: PlayCore.best_line_move_applied(socket, params) + + def handle_event("back_to_game", _params, socket), do: PlayCore.back_to_game(socket) + + # A completed puzzle contributes one first-attempt time to the average. A + # retry happens after this point and is deliberately ignored. + defp account_completion(socket) do + session = socket.assigns.session + status = socket.assigns.status + started = socket.assigns.puzzle_started_mono + + if session && not socket.assigns.puzzle_counted && is_integer(started) && + status in [:solved, :failed] do + duration = max(System.monotonic_time(:millisecond) - started, 0) + count = session.count + 1 + sum_ms = session.sum_ms + duration + + socket + |> assign(:session, %{session | count: count, sum_ms: sum_ms}) + |> assign(:puzzle_counted, true) + else + socket + end + end + + # Selection uses the rating this session has reached, not the stale rating the + # scope carried in at mount. + defp selection_user(socket) do + user = socket.assigns.current_scope.user + %{user | rating: socket.assigns.user_rating || user.rating} + end + + defp parse_difficulty(value) when value in ~w(easy medium hard), + do: String.to_existing_atom(value) + + defp parse_difficulty(_value), do: :medium + + defp difficulty_options(rating) do + width = Puzzles.band_width() + + [ + {:easy, "Easy", "below #{round(rating - width)}"}, + {:medium, "Medium", "#{round(rating - width)}–#{round(rating + width)}"}, + {:hard, "Hard", "above #{round(rating + width)}"} + ] + end + + defp difficulty_label(:easy), do: "Easy" + defp difficulty_label(:medium), do: "Medium" + defp difficulty_label(:hard), do: "Hard" + + defp net_gain(%{baseline: baseline}, rating) when is_number(rating), do: rating - baseline + defp net_gain(_session, _rating), do: nil + + defp avg_ms(%{count: 0}), do: nil + defp avg_ms(%{count: count, sum_ms: sum}), do: div(sum, count) + + defp elapsed_ms(%{started_at_ms: started_at}), + do: max(System.system_time(:millisecond) - started_at, 0) + + defp format_duration(nil), do: "—" + + defp format_duration(ms) when is_integer(ms) do + total = div(max(ms, 0), 1000) + minutes = String.pad_leading(Integer.to_string(div(total, 60)), 2, "0") + seconds = String.pad_leading(Integer.to_string(rem(total, 60)), 2, "0") + "#{minutes}:#{seconds}" + end + + defp format_delta(nil), do: "—" + + defp format_delta(delta) when is_number(delta) do + rounded = round(delta) + + cond do + rounded > 0 -> "+#{rounded}" + true -> Integer.to_string(rounded) + end + end + + defp gain_class(delta) when is_number(delta) and delta > 0, do: "text-success-text" + defp gain_class(delta) when is_number(delta) and delta < 0, do: "text-error" + defp gain_class(_delta), do: "text-muted" +end diff --git a/lib/chesstrainer_web/router.ex b/lib/chesstrainer_web/router.ex index f5956a8..063e2bc 100644 --- a/lib/chesstrainer_web/router.ex +++ b/lib/chesstrainer_web/router.ex @@ -68,6 +68,7 @@ defmodule ChesstrainerWeb.Router do live_session :require_authenticated_user, on_mount: [{ChesstrainerWeb.UserAuth, :require_authenticated}] do + live "/train", EndgameLive.Train, :train live "/users/settings", UserLive.Settings, :edit live "/users/settings/confirm-email/:token", UserLive.Settings, :confirm_email end diff --git a/test/chesstrainer/puzzles_test.exs b/test/chesstrainer/puzzles_test.exs new file mode 100644 index 0000000..b60f174 --- /dev/null +++ b/test/chesstrainer/puzzles_test.exs @@ -0,0 +1,98 @@ +defmodule Chesstrainer.PuzzlesTest do + use Chesstrainer.DataCase, async: true + + import Chesstrainer.AccountsFixtures + import Chesstrainer.EndgamesFixtures + + alias Chesstrainer.Accounts.Scope + alias Chesstrainer.Attempts + alias Chesstrainer.Puzzles + + # The shared `endgame_fixture/1` picks one of six FENs at random-ish, which + # can collide when one test creates several endgames under async load. Pin + # distinct FENs here instead. + @fens [ + "4k3/8/8/8/8/8/8/1K6 w - - 0 1", + "4k3/8/8/8/8/8/8/2K5 w - - 0 1", + "4k3/8/8/8/8/8/8/3K4 w - - 0 1", + "4k3/8/8/8/8/8/8/4K3 w - - 0 1" + ] + + defp endgame_at(rating, index) do + endgame_fixture(fen: Enum.fetch!(@fens, index), rating: rating) + end + + describe "difficulty_range/2" do + test "is centred on the rating and open-ended at the extremes" do + assert Puzzles.difficulty_range(1500, :medium) == {1400, 1600} + assert Puzzles.difficulty_range(1500, :easy) == {nil, 1400} + assert Puzzles.difficulty_range(1500, :hard) == {1600, nil} + end + end + + describe "next_endgame/3" do + test "medium picks an endgame within the band" do + user = user_fixture() + in_band = endgame_at(1550, 0) + _out_of_band = endgame_at(1900, 1) + + assert Puzzles.next_endgame(user, :medium).id == in_band.id + end + + test "easy picks an endgame below the user's rating" do + user = user_fixture() + easy = endgame_at(1300, 0) + _medium = endgame_at(1500, 1) + + assert Puzzles.next_endgame(user, :easy).id == easy.id + end + + test "hard picks an endgame above the user's rating" do + user = user_fixture() + hard = endgame_at(1700, 0) + _medium = endgame_at(1500, 1) + + assert Puzzles.next_endgame(user, :hard).id == hard.id + end + + test "falls back to the nearest endgame when the band is empty" do + user = user_fixture() + only = endgame_at(2200, 0) + + assert Puzzles.next_endgame(user, :medium).id == only.id + end + + test "prefers endgames not attempted in the last 30 days" do + user = user_fixture() + attempted = endgame_at(1500, 0) + fresh = endgame_at(1500, 1) + + {:ok, _} = Attempts.record_attempt(Scope.for_user(user), attempted, :solved) + + assert Puzzles.next_endgame(user, :medium).id == fresh.id + end + + test "falls back to a recent endgame once the fresh pool is empty" do + user = user_fixture() + only = endgame_at(1500, 0) + + {:ok, _} = Attempts.record_attempt(Scope.for_user(user), only, :solved) + + assert Puzzles.next_endgame(user, :medium).id == only.id + end + + test "skips excluded ids" do + user = user_fixture() + excluded = endgame_at(1500, 0) + other = endgame_at(1500, 1) + + assert Puzzles.next_endgame(user, :medium, exclude_ids: [excluded.id]).id == other.id + end + + test "returns nil when no endgames exist" do + user = user_fixture() + + assert Puzzles.next_endgame(user, :medium) == nil + end + end +end diff --git a/test/chesstrainer_web/live/endgame_live/train_test.exs b/test/chesstrainer_web/live/endgame_live/train_test.exs new file mode 100644 index 0000000..ec20abc --- /dev/null +++ b/test/chesstrainer_web/live/endgame_live/train_test.exs @@ -0,0 +1,171 @@ +defmodule ChesstrainerWeb.EndgameLive.TrainTest do + use ChesstrainerWeb.ConnCase + + import Phoenix.LiveViewTest + import Chesstrainer.EndgamesFixtures + + alias Chesstrainer.Attempts.Attempt + alias Chesstrainer.Endgames.Tablebase + alias Chesstrainer.Endgames.Tablebase.Cache, as: TablebaseCache + alias Chesstrainer.FEN + alias Chesstrainer.Repo + + 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, []) + } + + key = FEN.position_key(fen) + TablebaseCache.put(key, tablebase) + on_exit(fn -> TablebaseCache.delete(key) end) + end + + defp grading_moves do + [%Tablebase.Move{uci: "d1d7", san: "Qd7+", category: :loss, dtz: -1}] + end + + # Sets up `count` endgames all inside the medium band, seeds their tablebases, + # and starts a medium session. Returns the view and the endgames. + @session_fens [ + "4k3/8/8/8/8/8/8/1K6 w - - 0 1", + "4k3/8/8/8/8/8/8/2K5 w - - 0 1", + "4k3/8/8/8/8/8/8/3K4 w - - 0 1" + ] + + defp start_medium_session(conn, count) do + endgames = + for index <- 0..(count - 1) do + endgame_fixture(fen: Enum.fetch!(@session_fens, index), rating: 1500) + end + + Enum.each(endgames, fn endgame -> + seed_tablebase(endgame.fen, moves: grading_moves()) + end) + + {:ok, view, _html} = live(conn, ~p"/train") + + view + |> element("#difficulty-medium") + |> render_click() + + {view, endgames} + end + + defp solve_current(view) do + endgame = :sys.get_state(view.pid).socket.assigns.endgame + after_fen = "8/8/8/8/8/8/8/8 b - - 0 1" + + seed_tablebase(after_fen, checkmate: true, moves: []) + + render_hook(view, "endgame_move_played", %{ + "from" => "d1", + "to" => "d7", + "san" => "Qd7+", + "prev_fen" => endgame.fen, + "fen" => after_fen, + "endgame_id" => endgame.id + }) + end + + describe "access" do + test "redirects anonymous visitors to log in", %{conn: conn} do + assert {:error, {:redirect, %{to: "/users/log-in"}}} = live(conn, ~p"/train") + end + end + + describe "starting a session" do + setup :register_and_log_in_user + + test "shows the difficulty picker with all three choices", %{conn: conn} do + {:ok, view, _html} = live(conn, ~p"/train") + + assert has_element?(view, "#difficulty-picker") + assert has_element?(view, "#difficulty-easy") + assert has_element?(view, "#difficulty-medium") + assert has_element?(view, "#difficulty-hard") + assert render(view) =~ "Choose a difficulty" + end + + test "starts a medium session and shows the session chrome", %{conn: conn} do + endgame = endgame_fixture(rating: 1500) + seed_tablebase(endgame.fen) + {:ok, view, _html} = live(conn, ~p"/train") + + view |> element("#difficulty-medium") |> render_click() + + refute has_element?(view, "#difficulty-picker") + assert has_element?(view, "#session-bar") + assert has_element?(view, "#session-clock-" <> Integer.to_string(elapsed_id(view))) + assert has_element?(view, "#endgame-board") + + html = render(view) + assert html =~ "Your move" + assert html =~ "You play White" + + session = :sys.get_state(view.pid).socket.assigns.session + assert session.difficulty == :medium + assert session.count == 0 + end + end + + describe "playing a session" do + setup :register_and_log_in_user + + test "solves a puzzle, records an attempt and shows the rating gain", %{conn: conn} do + {view, [_endgame]} = start_medium_session(conn, 1) + + solve_current(view) + + assert render(view) =~ "Solved!" + assert render(view) =~ "Puzzle rating:" + assert [attempt] = Repo.all(Attempt) + assert attempt.outcome == :solved + + assigns = :sys.get_state(view.pid).socket.assigns + assert assigns.session.count == 1 + assert is_float(assigns.last_rating_delta) + assert assigns.last_rating_delta > 0 + assert assigns.user_rating > 1500.0 + end + + test "loads a different puzzle on next", %{conn: conn} do + {view, endgames} = start_medium_session(conn, 2) + first = :sys.get_state(view.pid).socket.assigns.endgame + + solve_current(view) + view |> element("#next-puzzle-button") |> render_click() + + second = :sys.get_state(view.pid).socket.assigns.endgame + assert second.id != first.id + assert Enum.any?(endgames, &(&1.id == second.id)) + end + + test "a retry does not count toward the average again", %{conn: conn} do + {view, [_endgame]} = start_medium_session(conn, 1) + + solve_current(view) + assert :sys.get_state(view.pid).socket.assigns.session.count == 1 + + view |> element("button", "Try again") |> render_click() + solve_current(view) + + assert :sys.get_state(view.pid).socket.assigns.session.count == 1 + end + + test "stopping a session returns to the picker so a new one can start", %{conn: conn} do + {view, [_endgame]} = start_medium_session(conn, 1) + + view |> element("button", "Stop session") |> render_click() + + assert has_element?(view, "#difficulty-picker") + assert has_element?(view, "#difficulty-medium") + assert :sys.get_state(view.pid).socket.assigns.session == nil + end + end + + defp elapsed_id(view) do + :sys.get_state(view.pid).socket.assigns.session.started_at_ms + end +end