mirror of
https://github.com/TheRealOwenRees/chess-endgame-trainer.git
synced 2026-11-18 11:42:07 +00:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f3f39a21d
|
||
|
|
8d1876b13b
|
||
|
|
0453e97897
|
||
|
|
1b44dae378
|
||
|
|
84eee4057e
|
||
|
|
55d2e2a913
|
+15
-1
@@ -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**:
|
||||
|
||||
+1
-1
@@ -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+/-
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
---
|
||||
|
||||
@@ -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 &);
|
||||
|
||||
@@ -43,14 +43,17 @@
|
||||
--color-accent-content: #ffffff;
|
||||
--color-neutral: #587068;
|
||||
--color-neutral-content: #f4f0e6;
|
||||
--color-info: oklch(62% 0.214 259.815);
|
||||
--color-info-content: oklch(97% 0.014 254.604);
|
||||
/* Toasts use the brand palette rather than the stock blue/red: info is the
|
||||
deep ink green, error is the coral used by primary actions. Both pass AA
|
||||
against their content colour. */
|
||||
--color-info: #17352d;
|
||||
--color-info-content: #fffcf4;
|
||||
--color-success: oklch(70% 0.14 182.503);
|
||||
--color-success-content: oklch(98% 0.014 180.72);
|
||||
--color-warning: oklch(66% 0.179 58.318);
|
||||
--color-warning-content: oklch(98% 0.022 95.277);
|
||||
--color-error: oklch(58% 0.253 17.585);
|
||||
--color-error-content: oklch(96% 0.015 12.422);
|
||||
--color-error: #c74c33;
|
||||
--color-error-content: #ffffff;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] {
|
||||
@@ -87,12 +90,12 @@ html[data-theme="dark"] {
|
||||
--color-accent-content: #0f1714;
|
||||
--color-neutral: #2b3a33;
|
||||
--color-neutral-content: #e9efe9;
|
||||
--color-info: oklch(70% 0.14 240);
|
||||
--color-info-content: oklch(15% 0.02 240);
|
||||
--color-info: #24403a;
|
||||
--color-info-content: #e9efe9;
|
||||
--color-success: oklch(72% 0.13 165);
|
||||
--color-success-content: oklch(15% 0.02 165);
|
||||
--color-warning: oklch(78% 0.15 75);
|
||||
--color-warning-content: oklch(20% 0.03 75);
|
||||
--color-error: oklch(66% 0.19 22);
|
||||
--color-error-content: oklch(15% 0.02 22);
|
||||
--color-error: #c74c33;
|
||||
--color-error-content: #ffffff;
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
@@ -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}`;
|
||||
},
|
||||
};
|
||||
@@ -41,3 +41,47 @@ document.addEventListener("keydown", (event) => {
|
||||
setOpen(false);
|
||||
}
|
||||
});
|
||||
|
||||
// Flash toasts also render on controller pages (the landing page, after logging
|
||||
// out, for example), where there is no LiveView to handle the component's
|
||||
// phx-click. Dismiss them with plain DOM there; LiveView pages keep clearing
|
||||
// the server-side flash through `lv:clear-flash`.
|
||||
document.addEventListener("click", (event) => {
|
||||
const target = event.target instanceof Element ? event.target : null;
|
||||
const flash = target?.closest("[data-flash-dismiss]");
|
||||
if (!flash) return;
|
||||
if (window.liveSocket?.isConnected?.()) return;
|
||||
|
||||
flash.remove();
|
||||
});
|
||||
|
||||
// Auto-dismiss real flash messages after a few seconds. Synthetic clicks reuse
|
||||
// the manual dismiss path, so LiveView pages also clear the server-side flash.
|
||||
// The connectivity notices (`client-error`/`server-error`) start hidden and are
|
||||
// left alone: they should stay until the connection recovers.
|
||||
const FLASH_TIMEOUT_MS = 5000;
|
||||
const scheduledFlashes = new WeakSet();
|
||||
|
||||
const scheduleFlashDismiss = (flash) => {
|
||||
if (scheduledFlashes.has(flash) || flash.hasAttribute("hidden")) return;
|
||||
|
||||
scheduledFlashes.add(flash);
|
||||
setTimeout(() => flash.click(), FLASH_TIMEOUT_MS);
|
||||
};
|
||||
|
||||
const scheduleFlashes = (root) => {
|
||||
if (root.matches?.("[data-flash-dismiss]")) scheduleFlashDismiss(root);
|
||||
root.querySelectorAll?.("[data-flash-dismiss]").forEach(scheduleFlashDismiss);
|
||||
};
|
||||
|
||||
document.querySelectorAll("[data-flash-dismiss]").forEach(scheduleFlashDismiss);
|
||||
|
||||
// Flashes rendered later (LiveView updates, live navigation) arrive after the
|
||||
// initial pass, so watch for them.
|
||||
new MutationObserver((mutations) => {
|
||||
for (const mutation of mutations) {
|
||||
for (const node of mutation.addedNodes) {
|
||||
if (node instanceof Element) scheduleFlashes(node);
|
||||
}
|
||||
}
|
||||
}).observe(document.body, { childList: true, subtree: true });
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
@@ -59,5 +59,32 @@ defmodule Chesstrainer.Attempts do
|
||||
|> Repo.one()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the number of users who have recorded at least one attempt.
|
||||
|
||||
A retry does not count twice: the count is over distinct users.
|
||||
"""
|
||||
def count_users_with_attempts do
|
||||
Attempt
|
||||
|> select([a], count(a.user_id, :distinct))
|
||||
|> 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
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -78,12 +78,13 @@ defmodule ChesstrainerWeb.CoreComponents do
|
||||
:if={msg = render_slot(@inner_block) || Phoenix.Flash.get(@flash, @kind)}
|
||||
id={@id}
|
||||
phx-click={JS.push("lv:clear-flash", value: %{key: @kind}) |> hide("##{@id}")}
|
||||
data-flash-dismiss
|
||||
role="alert"
|
||||
class="fixed right-4 top-4 z-50 flex flex-col gap-2"
|
||||
class="pointer-events-auto"
|
||||
{@rest}
|
||||
>
|
||||
<div class={[
|
||||
"flex w-80 max-w-80 items-start gap-3 rounded-lg border px-4 py-3 text-sm text-wrap shadow-lg sm:w-96 sm:max-w-96",
|
||||
"flex w-full items-start gap-3 rounded-lg border px-4 py-3 text-sm text-wrap shadow-lg",
|
||||
@kind == :info && "border-info bg-info text-info-content",
|
||||
@kind == :error && "border-error bg-error text-error-content"
|
||||
]}>
|
||||
|
||||
@@ -78,6 +78,7 @@ defmodule ChesstrainerWeb.LandingComponents do
|
||||
LiveView, use `board_grid/1` directly.
|
||||
"""
|
||||
attr :endgame, :map, default: nil
|
||||
attr :date, :any, default: nil
|
||||
|
||||
def board_preview(assigns) do
|
||||
endgame = assigns.endgame
|
||||
@@ -88,7 +89,8 @@ defmodule ChesstrainerWeb.LandingComponents do
|
||||
turn: turn_label(endgame),
|
||||
title: title(endgame),
|
||||
themes: theme_names(endgame),
|
||||
orientation: orientation(endgame)
|
||||
orientation: orientation(endgame),
|
||||
date: Calendar.strftime(assigns.date || Date.utc_today(), "%d %b %Y")
|
||||
)
|
||||
|
||||
~H"""
|
||||
@@ -101,6 +103,7 @@ defmodule ChesstrainerWeb.LandingComponents do
|
||||
<strong>{@turn}</strong>
|
||||
</span>
|
||||
</div>
|
||||
<div>{@date}</div>
|
||||
</div>
|
||||
|
||||
<.board_grid fen={@fen} orientation={@orientation} />
|
||||
@@ -186,20 +189,20 @@ defmodule ChesstrainerWeb.LandingComponents do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Formats the puzzle count for the landing-page stat.
|
||||
Formats a landing-page stat count.
|
||||
|
||||
Counts below 100 are shown exactly. Larger counts are floored to the nearest
|
||||
hundred or thousand and suffixed with `+`, so the claim is never overstated.
|
||||
"""
|
||||
def puzzle_count_label(count) when is_integer(count) and count < 100 do
|
||||
def count_label(count) when is_integer(count) and count < 100 do
|
||||
Integer.to_string(count)
|
||||
end
|
||||
|
||||
def puzzle_count_label(count) when is_integer(count) and count < 1000 do
|
||||
def count_label(count) when is_integer(count) and count < 1000 do
|
||||
"#{div(count, 100) * 100}+"
|
||||
end
|
||||
|
||||
def puzzle_count_label(count) when is_integer(count) do
|
||||
def count_label(count) when is_integer(count) do
|
||||
"#{div(count, 1000) * 1000}+"
|
||||
end
|
||||
|
||||
|
||||
@@ -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"""
|
||||
<header>
|
||||
@@ -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 />
|
||||
</.pill_button>
|
||||
</div>
|
||||
@@ -106,9 +109,14 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
end
|
||||
|
||||
defp nav_links(scope) do
|
||||
marketing = [
|
||||
%{label: "Puzzle Search", href: "/#puzzles"}
|
||||
marketing =
|
||||
if premium?(scope) do
|
||||
[
|
||||
%{label: "Puzzle Search", href: "/endgames"}
|
||||
]
|
||||
else
|
||||
[]
|
||||
end
|
||||
|
||||
admin =
|
||||
if admin?(scope) do
|
||||
@@ -121,9 +129,9 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
case scope do
|
||||
%{user: %{username: username}} ->
|
||||
[
|
||||
%{label: username, kind: :text},
|
||||
%{label: "Settings", href: ~p"/users/settings"},
|
||||
%{label: "Log out", href: ~p"/users/log-out", method: "delete"}
|
||||
%{label: "Log out", href: ~p"/users/log-out", method: "delete"},
|
||||
%{label: username, kind: :text}
|
||||
]
|
||||
|
||||
_ ->
|
||||
@@ -139,6 +147,12 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
defp admin?(%{user: %{role: role}}), do: Role.admin?(role)
|
||||
defp admin?(_scope), do: false
|
||||
|
||||
defp premium?(scope), do: match?(%{user: %{plan: :premium}}, scope)
|
||||
|
||||
# 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.
|
||||
|
||||
@@ -160,10 +174,8 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
</div>
|
||||
|
||||
<nav class="footer-links" aria-label="Footer">
|
||||
<a href="/#method">Method</a>
|
||||
<a href="/#puzzles">Puzzles</a>
|
||||
<a href="/#progress">Progress</a>
|
||||
<a href={~p"/endgames"}>Endgames</a>
|
||||
<a href="/#privacy">Privacy Policy</a>
|
||||
<a href="/#terms-conditions">Terms & Conditions</a>
|
||||
</nav>
|
||||
|
||||
<small>© {@year} Lucid Chess</small>
|
||||
@@ -183,7 +195,11 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
|
||||
def flash_group(assigns) do
|
||||
~H"""
|
||||
<div id={@id} aria-live="polite">
|
||||
<div
|
||||
id={@id}
|
||||
aria-live="polite"
|
||||
class="pointer-events-none fixed right-4 top-4 z-50 flex w-80 max-w-80 flex-col gap-2 sm:w-96 sm:max-w-96"
|
||||
>
|
||||
<.flash kind={:info} flash={@flash} />
|
||||
<.flash kind={:error} flash={@flash} />
|
||||
|
||||
|
||||
@@ -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"""
|
||||
<div class="flex gap-2 bg-base-200 p-4 rounded-xl shadow-inner">
|
||||
<div
|
||||
id="endgame-board"
|
||||
phx-hook="ChessBoard"
|
||||
phx-update="ignore"
|
||||
data-endgame-id={@endgame.id}
|
||||
class="w-100 h-100"
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="w-48 h-100 flex flex-col gap-3">
|
||||
<div class="rounded-lg bg-canvas-raised p-3 text-sm">
|
||||
<p class="flex items-center justify-between gap-2 font-semibold">
|
||||
<span>{turn_label(@status, @awaiting_reply)}</span>
|
||||
<span class="text-xs font-normal text-muted">You play {colour_name(@endgame.color)}</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="rounded-lg bg-canvas-raised p-3 text-sm">
|
||||
<%= cond do %>
|
||||
<% @status == :loading -> %>
|
||||
<p class="text-muted">Loading tablebase…</p>
|
||||
<% @status == :blocked -> %>
|
||||
<p class="font-semibold text-error">Tablebase unavailable</p>
|
||||
<p class="text-error">{@blocked_reason}</p>
|
||||
<% @status == :solved -> %>
|
||||
<p class="font-semibold text-success-text">
|
||||
{if @endgame.result == :draw, do: "Draw held!", else: "Solved!"}
|
||||
</p>
|
||||
<% @status == :failed -> %>
|
||||
<p class="font-semibold text-error">Failed</p>
|
||||
<p class="text-error">
|
||||
{if @endgame.result == :draw,
|
||||
do: "That move loses the draw.",
|
||||
else: "That move throws away the win."}
|
||||
</p>
|
||||
<%= if @best_move && @plies != [] do %>
|
||||
<p class="text-muted">
|
||||
You played {List.last(@plies).san}; best was: {@best_move}
|
||||
</p>
|
||||
<% end %>
|
||||
<% @awaiting_reply -> %>
|
||||
<p class="text-muted">Opponent is replying…</p>
|
||||
<% @last_grade == :optimal -> %>
|
||||
<p class="font-semibold text-success-text">Optimal move</p>
|
||||
<% @last_grade == :winning -> %>
|
||||
<p class="font-semibold text-warning">
|
||||
{if @endgame.result == :draw,
|
||||
do: "Keeps the draw — but not the sharpest",
|
||||
else: "Winning — but not the sharpest"}
|
||||
</p>
|
||||
<% @last_grade == :losing -> %>
|
||||
<p class="font-semibold text-error">
|
||||
{if @endgame.result == :draw,
|
||||
do: "Losing move — this loses the draw",
|
||||
else: "Losing move — this throws away the win"}
|
||||
</p>
|
||||
<% @last_grade == :unknown -> %>
|
||||
<p class="font-semibold text-muted">Could not grade that move</p>
|
||||
<% true -> %>
|
||||
<p class="text-muted">Make a move to have it graded.</p>
|
||||
<% end %>
|
||||
<p :if={@status in [:solved, :failed]} class="mt-1 text-xs text-muted">
|
||||
Puzzle rating: {round(@endgame.rating)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div :if={@reviewing} id="best-move-panel" class="rounded-lg bg-canvas-raised p-3 text-sm">
|
||||
<%= cond do %>
|
||||
<% @review_blocked -> %>
|
||||
<p class="text-muted">Best move unavailable here</p>
|
||||
<p class="text-muted">{@review_blocked}</p>
|
||||
<% @review_tablebase -> %>
|
||||
<p class="text-muted font-semibold mb-1">Best move:</p>
|
||||
<p class="text-success-text">{PlayCore.best_move_text(@review_tablebase) || "—"}</p>
|
||||
<%= if played_ply = played_ply_at(@line, @review_index) do %>
|
||||
<p class={["mt-1", grade_class(played_ply.grade)]}>Played: {played_ply.san}</p>
|
||||
<% end %>
|
||||
<% true -> %>
|
||||
<p class="text-muted">No best move.</p>
|
||||
<% end %>
|
||||
</div>
|
||||
|
||||
<div id="move-list" class="flex-1 min-h-0 flex flex-col bg-canvas-raised rounded-lg p-3">
|
||||
<% plies = display_plies(@reviewing, @line, @plies) %>
|
||||
<p class="text-sm text-muted font-semibold mb-2">Moves:</p>
|
||||
<div class="flex-1 overflow-y-auto">
|
||||
<%= if plies == [] do %>
|
||||
<p class="text-sm text-muted">No Moves</p>
|
||||
<% else %>
|
||||
<%= for {[white_ply, black_ply], move_no} <- move_rows(plies, @endgame.color) do %>
|
||||
<div class="font-mono text-sm leading-6">
|
||||
<span class="text-muted mr-2">{move_no}.</span>
|
||||
<%= if white_ply do %>
|
||||
<.ply
|
||||
ply={white_ply}
|
||||
reviewing={@reviewing}
|
||||
review_index={@review_index}
|
||||
result={@endgame.result}
|
||||
/>
|
||||
<% else %>
|
||||
<span class="text-body">...</span>
|
||||
<% end %>
|
||||
<%= if black_ply do %>
|
||||
<.ply
|
||||
ply={black_ply}
|
||||
reviewing={@reviewing}
|
||||
review_index={@review_index}
|
||||
result={@endgame.result}
|
||||
/>
|
||||
<% end %>
|
||||
</div>
|
||||
<% end %>
|
||||
<% end %>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<.button
|
||||
:if={@status in [:solved, :failed] and not @reviewing}
|
||||
phx-click="review"
|
||||
>
|
||||
<.icon name="hero-eye" /> Review
|
||||
</.button>
|
||||
<.button phx-click="reset" variant="primary">
|
||||
<.icon name="hero-arrow-path" />
|
||||
{if @status in [:solved, :failed], do: "Try again", else: "Reset"}
|
||||
</.button>
|
||||
<.button
|
||||
:if={@session and @status in [:solved, :failed] and not @reviewing}
|
||||
id="next-puzzle-button"
|
||||
phx-click="next_puzzle"
|
||||
variant="primary"
|
||||
>
|
||||
Next puzzle
|
||||
</.button>
|
||||
</div>
|
||||
|
||||
<div :if={@reviewing} id="review-controls" class="flex flex-wrap gap-2">
|
||||
<.button phx-click="review_prev" disabled={@review_index <= 0}>←</.button>
|
||||
<.button phx-click="review_next" disabled={@review_index >= length(@line)}>→</.button>
|
||||
<.button
|
||||
:if={@review_tablebase && PlayCore.best_move_text(@review_tablebase)}
|
||||
phx-click="play_best_line"
|
||||
disabled={@awaiting_best_line}
|
||||
>
|
||||
Play best line
|
||||
</.button>
|
||||
<.button :if={@line != @plies} phx-click="back_to_game">Back to game</.button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
"""
|
||||
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 %>
|
||||
<button
|
||||
type="button"
|
||||
phx-click="review_step"
|
||||
phx-value-index={@ply.index + 1}
|
||||
class={[
|
||||
"ml-2",
|
||||
ply_class(@ply),
|
||||
current_ply?(@ply, @review_index) && "underline"
|
||||
]}
|
||||
title={ply_title(@ply, @result)}
|
||||
data-grade={@ply.grade}
|
||||
>
|
||||
{@ply.san}
|
||||
</button>
|
||||
<% else %>
|
||||
<span
|
||||
class={["ml-2", ply_class(@ply)]}
|
||||
title={ply_title(@ply, @result)}
|
||||
data-grade={@ply.grade}
|
||||
>
|
||||
{@ply.san}
|
||||
</span>
|
||||
<% 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
|
||||
@@ -1,6 +1,7 @@
|
||||
defmodule ChesstrainerWeb.PageController do
|
||||
use ChesstrainerWeb, :controller
|
||||
|
||||
alias Chesstrainer.Attempts
|
||||
alias Chesstrainer.DailyPuzzles
|
||||
alias Chesstrainer.Endgames
|
||||
|
||||
@@ -19,7 +20,9 @@ defmodule ChesstrainerWeb.PageController do
|
||||
|> render(:home,
|
||||
endgames: endgames,
|
||||
active_endgame: DailyPuzzles.today(),
|
||||
puzzle_count: Endgames.count_endgames()
|
||||
puzzle_count: Endgames.count_endgames(),
|
||||
user_count: Attempts.count_users_with_attempts(),
|
||||
today: Date.utc_today()
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
<i>♜</i>
|
||||
</span>
|
||||
<span>
|
||||
<strong>12,400+</strong> players training
|
||||
<strong>{count_label(@user_count)}</strong> players training
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -31,7 +31,7 @@
|
||||
<div class="board-stage" id="trainer">
|
||||
<div class="coral-orbit" />
|
||||
<div class="mint-orbit" />
|
||||
<.board_preview endgame={@active_endgame} />
|
||||
<.board_preview endgame={@active_endgame} date={@today} />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
<span>minutes a day</span>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<strong>{puzzle_count_label(@puzzle_count)}</strong>
|
||||
<strong>{count_label(@puzzle_count)}</strong>
|
||||
<span>puzzles</span>
|
||||
</div>
|
||||
<div class="stat">
|
||||
|
||||
@@ -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
|
||||
</:actions>
|
||||
</.header>
|
||||
|
||||
<div class="flex gap-2 bg-base-200 p-4 rounded-xl shadow-inner">
|
||||
<div
|
||||
id="endgame-board"
|
||||
phx-hook="ChessBoard"
|
||||
phx-update="ignore"
|
||||
data-endgame-id={@endgame.id}
|
||||
class="w-100 h-100"
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="w-48 h-100 flex flex-col gap-3">
|
||||
<div class="rounded-lg bg-canvas-raised p-3 text-sm">
|
||||
<%= cond do %>
|
||||
<% @status == :loading -> %>
|
||||
<p class="text-muted">Loading tablebase…</p>
|
||||
<% @status == :blocked -> %>
|
||||
<p class="font-semibold text-error">Tablebase unavailable</p>
|
||||
<p class="text-error">{@blocked_reason}</p>
|
||||
<% @status == :solved -> %>
|
||||
<p class="font-semibold text-success-text">
|
||||
{if @endgame.result == :draw, do: "Draw held!", else: "Solved!"}
|
||||
</p>
|
||||
<% @status == :failed -> %>
|
||||
<p class="font-semibold text-error">Failed</p>
|
||||
<p class="text-error">
|
||||
{if @endgame.result == :draw,
|
||||
do: "That move loses the draw.",
|
||||
else: "That move throws away the win."}
|
||||
</p>
|
||||
<%= if @best_move && @plies != [] do %>
|
||||
<p class="text-muted">
|
||||
You played {List.last(@plies).san}; best was: {@best_move}
|
||||
</p>
|
||||
<% end %>
|
||||
<% @awaiting_reply -> %>
|
||||
<p class="text-muted">Opponent is replying…</p>
|
||||
<% @last_grade == :optimal -> %>
|
||||
<p class="font-semibold text-success-text">Optimal move</p>
|
||||
<% @last_grade == :winning -> %>
|
||||
<p class="font-semibold text-warning">
|
||||
{if @endgame.result == :draw,
|
||||
do: "Keeps the draw — but not the sharpest",
|
||||
else: "Winning — but not the sharpest"}
|
||||
</p>
|
||||
<% @last_grade == :losing -> %>
|
||||
<p class="font-semibold text-error">
|
||||
{if @endgame.result == :draw,
|
||||
do: "Losing move — this loses the draw",
|
||||
else: "Losing move — this throws away the win"}
|
||||
</p>
|
||||
<% @last_grade == :unknown -> %>
|
||||
<p class="font-semibold text-muted">Could not grade that move</p>
|
||||
<% true -> %>
|
||||
<p class="text-muted">Make a move to have it graded.</p>
|
||||
<% end %>
|
||||
</div>
|
||||
|
||||
<div :if={@reviewing} id="best-move-panel" class="rounded-lg bg-canvas-raised p-3 text-sm">
|
||||
<%= cond do %>
|
||||
<% @review_blocked -> %>
|
||||
<p class="text-muted">Best move unavailable here</p>
|
||||
<p class="text-muted">{@review_blocked}</p>
|
||||
<% @review_tablebase -> %>
|
||||
<p class="text-muted font-semibold mb-1">Best move:</p>
|
||||
<p class="text-success-text">{best_move_text(@review_tablebase) || "—"}</p>
|
||||
<%= if played_ply = played_ply_at(@line, @review_index) do %>
|
||||
<p class={["mt-1", grade_class(played_ply.grade)]}>Played: {played_ply.san}</p>
|
||||
<% end %>
|
||||
<% true -> %>
|
||||
<p class="text-muted">No best move.</p>
|
||||
<% end %>
|
||||
</div>
|
||||
|
||||
<div id="move-list" class="flex-1 min-h-0 flex flex-col bg-canvas-raised rounded-lg p-3">
|
||||
<% plies = display_plies(@reviewing, @line, @plies) %>
|
||||
<p class="text-sm text-muted font-semibold mb-2">Moves:</p>
|
||||
<div class="flex-1 overflow-y-auto">
|
||||
<%= if plies == [] do %>
|
||||
<p class="text-sm text-muted">No Moves</p>
|
||||
<% else %>
|
||||
<%= for {[white_ply, black_ply], move_no} <- move_rows(plies, @endgame.color) do %>
|
||||
<div class="font-mono text-sm leading-6">
|
||||
<span class="text-muted mr-2">{move_no}.</span>
|
||||
<%= if white_ply do %>
|
||||
<.ply
|
||||
ply={white_ply}
|
||||
<PlayComponents.play_surface
|
||||
endgame={@endgame}
|
||||
status={@status}
|
||||
blocked_reason={@blocked_reason}
|
||||
best_move={@best_move}
|
||||
plies={@plies}
|
||||
line={@line}
|
||||
reviewing={@reviewing}
|
||||
review_index={@review_index}
|
||||
result={@endgame.result}
|
||||
review_tablebase={@review_tablebase}
|
||||
review_blocked={@review_blocked}
|
||||
awaiting_reply={@awaiting_reply}
|
||||
last_grade={@last_grade}
|
||||
awaiting_best_line={@awaiting_best_line}
|
||||
/>
|
||||
<% else %>
|
||||
<span class="text-body">...</span>
|
||||
<% end %>
|
||||
<%= if black_ply do %>
|
||||
<.ply
|
||||
ply={black_ply}
|
||||
reviewing={@reviewing}
|
||||
review_index={@review_index}
|
||||
result={@endgame.result}
|
||||
/>
|
||||
<% end %>
|
||||
</div>
|
||||
<% end %>
|
||||
<% end %>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<.button
|
||||
:if={@status in [:solved, :failed] and not @reviewing}
|
||||
phx-click="review"
|
||||
>
|
||||
<.icon name="hero-eye" /> Review
|
||||
</.button>
|
||||
<.button phx-click="reset" variant="primary">
|
||||
<.icon name="hero-arrow-path" />
|
||||
{if @status in [:solved, :failed], do: "Try again", else: "Reset"}
|
||||
</.button>
|
||||
</div>
|
||||
|
||||
<div :if={@reviewing} id="review-controls" class="flex flex-wrap gap-2">
|
||||
<.button phx-click="review_prev" disabled={@review_index <= 0}>←</.button>
|
||||
<.button phx-click="review_next" disabled={@review_index >= length(@line)}>→</.button>
|
||||
<.button
|
||||
:if={@review_tablebase && best_move_text(@review_tablebase)}
|
||||
phx-click="play_best_line"
|
||||
disabled={@awaiting_best_line}
|
||||
>
|
||||
Play best line
|
||||
</.button>
|
||||
<.button :if={@line != @plies} phx-click="back_to_game">Back to game</.button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Layouts.app>
|
||||
"""
|
||||
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 %>
|
||||
<button
|
||||
type="button"
|
||||
phx-click="review_step"
|
||||
phx-value-index={@ply.index + 1}
|
||||
class={[
|
||||
"ml-2",
|
||||
ply_class(@ply),
|
||||
current_ply?(@ply, @review_index) && "underline"
|
||||
]}
|
||||
title={ply_title(@ply, @result)}
|
||||
data-grade={@ply.grade}
|
||||
>
|
||||
{@ply.san}
|
||||
</button>
|
||||
<% else %>
|
||||
<span
|
||||
class={["ml-2", ply_class(@ply)]}
|
||||
title={ply_title(@ply, @result)}
|
||||
data-grade={@ply.grade}
|
||||
>
|
||||
{@ply.san}
|
||||
</span>
|
||||
<% 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
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,371 @@
|
||||
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"""
|
||||
<Layouts.app flash={@flash}>
|
||||
<.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 %>
|
||||
</:subtitle>
|
||||
<:actions>
|
||||
<.button :if={@session} phx-click="stop_session">
|
||||
<.icon name="hero-x-mark" /> Stop session
|
||||
</.button>
|
||||
<.button
|
||||
:if={premium?(@current_scope)}
|
||||
id="puzzle-search"
|
||||
navigate={~p"/endgames"}
|
||||
>
|
||||
<.icon name="hero-magnifying-glass" /> Puzzle Search
|
||||
</.button>
|
||||
</:actions>
|
||||
</.header>
|
||||
|
||||
<%= if @session do %>
|
||||
<div
|
||||
id="session-bar"
|
||||
class="mb-4 flex flex-wrap items-center gap-x-6 gap-y-2 rounded-lg bg-canvas-raised p-3 text-sm"
|
||||
>
|
||||
<span>
|
||||
<span class="text-muted">Difficulty</span>
|
||||
<span class="font-semibold">{difficulty_label(@session.difficulty)}</span>
|
||||
</span>
|
||||
<span>
|
||||
<span class="text-muted">Time</span>
|
||||
<span
|
||||
id={"session-clock-#{@session.started_at_ms}"}
|
||||
phx-hook="SessionClock"
|
||||
data-started-at={@session.started_at_ms}
|
||||
class="font-mono"
|
||||
>
|
||||
{format_duration(elapsed_ms(@session))}
|
||||
</span>
|
||||
</span>
|
||||
<span>
|
||||
<span class="text-muted">Avg/puzzle</span>
|
||||
<span class="font-mono">{format_duration(avg_ms(@session))}</span>
|
||||
</span>
|
||||
<span>
|
||||
<span class="text-muted">Rating</span>
|
||||
<span class={["font-mono", gain_class(net_gain(@session, @user_rating))]}>
|
||||
{format_delta(net_gain(@session, @user_rating))}
|
||||
</span>
|
||||
</span>
|
||||
<span :if={@last_rating_delta}>
|
||||
<span class="text-muted">Last</span>
|
||||
<span class={["font-mono", gain_class(@last_rating_delta)]}>
|
||||
{format_delta(@last_rating_delta)}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<PlayComponents.play_surface
|
||||
session={true}
|
||||
endgame={@endgame}
|
||||
status={@status}
|
||||
blocked_reason={@blocked_reason}
|
||||
best_move={@best_move}
|
||||
plies={@plies}
|
||||
line={@line}
|
||||
reviewing={@reviewing}
|
||||
review_index={@review_index}
|
||||
review_tablebase={@review_tablebase}
|
||||
review_blocked={@review_blocked}
|
||||
awaiting_reply={@awaiting_reply}
|
||||
last_grade={@last_grade}
|
||||
awaiting_best_line={@awaiting_best_line}
|
||||
/>
|
||||
<% else %>
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
|
||||
<div id="difficulty-picker" class="w-full max-w-md rounded-xl bg-base-100 p-6 shadow-xl">
|
||||
<div
|
||||
:if={@last_session}
|
||||
id="last-session"
|
||||
class="mb-4 rounded-lg bg-canvas-raised p-3 text-sm"
|
||||
>
|
||||
<p class="mb-1 font-semibold">Last session</p>
|
||||
<div class="flex flex-wrap gap-x-4 gap-y-1 text-xs">
|
||||
<span>
|
||||
<span class="text-muted">Difficulty</span>
|
||||
<span class="font-semibold">{difficulty_label(@last_session.difficulty)}</span>
|
||||
</span>
|
||||
<span>
|
||||
<span class="text-muted">Time</span>
|
||||
<span class="font-mono">{format_duration(@last_session.duration_ms)}</span>
|
||||
</span>
|
||||
<span>
|
||||
<span class="text-muted">Puzzles</span>
|
||||
<span class="font-mono">{@last_session.count}</span>
|
||||
</span>
|
||||
<span>
|
||||
<span class="text-muted">Avg/puzzle</span>
|
||||
<span class="font-mono">{format_duration(@last_session.avg_ms)}</span>
|
||||
</span>
|
||||
<span>
|
||||
<span class="text-muted">Rating</span>
|
||||
<span class={["font-mono", gain_class(@last_session.gain)]}>
|
||||
{format_delta(@last_session.gain)}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h2 class="text-lg font-semibold">Choose a difficulty</h2>
|
||||
<p class="mt-1 text-sm text-muted">
|
||||
Your rating: {round(@user_rating)} · bands of ±{Puzzles.band_width()}
|
||||
</p>
|
||||
</div>
|
||||
<.link
|
||||
id="close-difficulty"
|
||||
navigate={~p"/"}
|
||||
aria-label="Close and return home"
|
||||
class="rounded-md p-1 text-muted hover:bg-base-200 hover:text-base-content focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
|
||||
>
|
||||
<.icon name="hero-x-mark" class="size-5" />
|
||||
</.link>
|
||||
</div>
|
||||
<div class="mt-4 grid gap-2">
|
||||
<%= 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"
|
||||
>
|
||||
<span>{label}</span>
|
||||
<span class="text-xs font-normal opacity-80">{description}</span>
|
||||
</.button>
|
||||
<% end %>
|
||||
</div>
|
||||
<.button navigate={~p"/"} variant="ghost" class="mt-2 w-full justify-center">
|
||||
Cancel
|
||||
</.button>
|
||||
</div>
|
||||
</div>
|
||||
<% end %>
|
||||
</Layouts.app>
|
||||
"""
|
||||
end
|
||||
|
||||
@impl true
|
||||
def mount(_params, _session, socket) do
|
||||
{:ok,
|
||||
socket
|
||||
|> assign(:page_title, "Train")
|
||||
|> assign(:session, nil)
|
||||
|> assign(:last_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
|
||||
socket =
|
||||
case socket.assigns.session do
|
||||
nil -> socket
|
||||
session -> assign(socket, :last_session, summarise(session, socket.assigns.user_rating))
|
||||
end
|
||||
|
||||
{: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 premium?(%{user: %{plan: :premium}}), do: true
|
||||
defp premium?(_scope), do: false
|
||||
|
||||
defp summarise(session, rating) do
|
||||
%{
|
||||
difficulty: session.difficulty,
|
||||
duration_ms: elapsed_ms(session),
|
||||
count: session.count,
|
||||
avg_ms: avg_ms(session),
|
||||
gain: net_gain(session, 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
|
||||
@@ -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
|
||||
|
||||
@@ -39,6 +39,26 @@ defmodule Chesstrainer.AttemptsTest do
|
||||
end
|
||||
end
|
||||
|
||||
describe "count_users_with_attempts/0" do
|
||||
test "counts distinct users who have recorded an attempt" do
|
||||
first = user_fixture()
|
||||
second = user_fixture()
|
||||
endgame = endgame_fixture()
|
||||
|
||||
{:ok, _} = Attempts.record_attempt(Scope.for_user(first), endgame, :solved)
|
||||
{:ok, _} = Attempts.record_attempt(Scope.for_user(first), endgame, :failed)
|
||||
{:ok, _} = Attempts.record_attempt(Scope.for_user(second), endgame, :solved)
|
||||
|
||||
assert Attempts.count_users_with_attempts() == 2
|
||||
end
|
||||
|
||||
test "ignores users without attempts" do
|
||||
user_fixture()
|
||||
|
||||
assert Attempts.count_users_with_attempts() == 0
|
||||
end
|
||||
end
|
||||
|
||||
describe "cascade" do
|
||||
test "deleting a user removes their attempts" do
|
||||
user = user_fixture()
|
||||
|
||||
@@ -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
|
||||
@@ -54,23 +54,23 @@ defmodule ChesstrainerWeb.LandingComponentsTest do
|
||||
assert html =~ "currentColor"
|
||||
end
|
||||
|
||||
describe "puzzle_count_label/1" do
|
||||
describe "count_label/1" do
|
||||
test "shows counts below 100 exactly" do
|
||||
assert LandingComponents.puzzle_count_label(0) == "0"
|
||||
assert LandingComponents.puzzle_count_label(47) == "47"
|
||||
assert LandingComponents.puzzle_count_label(99) == "99"
|
||||
assert LandingComponents.count_label(0) == "0"
|
||||
assert LandingComponents.count_label(47) == "47"
|
||||
assert LandingComponents.count_label(99) == "99"
|
||||
end
|
||||
|
||||
test "floors counts of 100 or more to hundreds" do
|
||||
assert LandingComponents.puzzle_count_label(100) == "100+"
|
||||
assert LandingComponents.puzzle_count_label(199) == "100+"
|
||||
assert LandingComponents.puzzle_count_label(999) == "900+"
|
||||
assert LandingComponents.count_label(100) == "100+"
|
||||
assert LandingComponents.count_label(199) == "100+"
|
||||
assert LandingComponents.count_label(999) == "900+"
|
||||
end
|
||||
|
||||
test "floors counts of 1000 or more to thousands" do
|
||||
assert LandingComponents.puzzle_count_label(1000) == "1000+"
|
||||
assert LandingComponents.puzzle_count_label(1999) == "1000+"
|
||||
assert LandingComponents.puzzle_count_label(2400) == "2000+"
|
||||
assert LandingComponents.count_label(1000) == "1000+"
|
||||
assert LandingComponents.count_label(1999) == "1000+"
|
||||
assert LandingComponents.count_label(2400) == "2000+"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -2,7 +2,10 @@ defmodule ChesstrainerWeb.PageControllerTest do
|
||||
use ChesstrainerWeb.ConnCase
|
||||
|
||||
import Chesstrainer.AccountsFixtures
|
||||
import Chesstrainer.EndgamesFixtures
|
||||
|
||||
alias Chesstrainer.Accounts.Scope
|
||||
alias Chesstrainer.Attempts
|
||||
alias Chesstrainer.DailyPuzzles
|
||||
alias Chesstrainer.Endgames
|
||||
alias Chesstrainer.Themes
|
||||
@@ -49,8 +52,8 @@ defmodule ChesstrainerWeb.PageControllerTest do
|
||||
|
||||
assert html =~ "Learn to see the"
|
||||
assert html =~ "LUCID"
|
||||
assert html =~ "Method"
|
||||
assert html =~ "Puzzles"
|
||||
assert html =~ "Privacy Policy"
|
||||
assert html =~ "/#terms-conditions"
|
||||
assert html =~ "Start training"
|
||||
assert html =~ ~s(id="nav-links")
|
||||
assert html =~ "menu-button"
|
||||
@@ -89,6 +92,17 @@ defmodule ChesstrainerWeb.PageControllerTest do
|
||||
end
|
||||
end
|
||||
|
||||
test "hero shows the number of players with at least one attempt", %{conn: conn} do
|
||||
user = user_fixture()
|
||||
endgame = endgame_fixture()
|
||||
{:ok, _} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
|
||||
|
||||
html = conn |> get(~p"/") |> html_response(200)
|
||||
document = LazyHTML.from_document(html)
|
||||
|
||||
assert LazyHTML.text(LazyHTML.query(document, ".rating-note strong")) == "1"
|
||||
end
|
||||
|
||||
test "guest navbar links to log in and register", %{conn: conn} do
|
||||
html = conn |> get(~p"/") |> html_response(200)
|
||||
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
defmodule ChesstrainerWeb.EndgameLive.TrainTest do
|
||||
use ChesstrainerWeb.ConnCase
|
||||
|
||||
import Phoenix.LiveViewTest
|
||||
import Chesstrainer.AccountsFixtures
|
||||
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 has_element?(view, "#close-difficulty[href='/']")
|
||||
assert has_element?(view, "a", "Cancel")
|
||||
refute has_element?(view, "#puzzle-search")
|
||||
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 "premium access" do
|
||||
test "shows the puzzle search link for premium users", %{conn: conn} do
|
||||
{:ok, user} =
|
||||
user_fixture()
|
||||
|> Ecto.Changeset.change(plan: :premium)
|
||||
|> Repo.update()
|
||||
|
||||
conn = log_in_user(conn, user)
|
||||
{:ok, view, _html} = live(conn, ~p"/train")
|
||||
|
||||
assert has_element?(view, "#puzzle-search[href='/endgames']")
|
||||
assert render(view) =~ "Puzzle Search"
|
||||
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 shows the finished session in the picker", %{conn: conn} do
|
||||
{view, [_endgame]} = start_medium_session(conn, 1)
|
||||
solve_current(view)
|
||||
|
||||
view |> element("button", "Stop session") |> render_click()
|
||||
|
||||
assert has_element?(view, "#last-session")
|
||||
assert render(view) =~ "Last session"
|
||||
|
||||
last = :sys.get_state(view.pid).socket.assigns.last_session
|
||||
assert last.difficulty == :medium
|
||||
assert last.count == 1
|
||||
assert is_float(last.gain)
|
||||
assert last.gain > 0
|
||||
assert last.duration_ms >= 0
|
||||
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
|
||||
Reference in New Issue
Block a user