Files
owenrees e0b446bbfb Weight puzzle selection and stop repeats inside a session (#183)
Selection took a hard rating band (medium = user rating ± 100), removed
everything attempted in the last 30 days, and drew uniformly from what was
left. Because the bulk importer gives every endgame in a batch the same
rating, the band held either the whole library or — once a user's rating
drifted past it — only the endgames that user had already played. With
`fresh` empty, the fallback re-drew from the same band ignoring recency, so
recently played puzzles came straight back. An empty band used a
deterministic nearest-match, alternating between the same two puzzles.

Difficulty is now a bias rather than a filter: candidates are weighted by
`exp(-|rating - target| / spread)` and drawn with an exponential race, so
the whole library stays reachable and a thin region around the user's rating
can never empty the pool. `easy` and `hard` keep one-sided guards so the
labels stay honest. When every candidate is excluded, selection serves the
least recently attempted endgame instead of a random recent one.

Sessions now carry the ids they have served, which fixes the observed
in-session repeat (only the current puzzle used to be excluded), and guest
training gets the same treatment. The 30-day window is configurable as the
repeat window and is now named in GLOSSARY.md, distinct from the rating
window and from the tablebase cooldown.

Difficulty copy is qualitative, since the band numbers no longer describe
how selection works.
2026-11-17 14:28:24 +01:00

308 lines
10 KiB
Elixir

defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
@moduledoc """
Public training: play random endgame puzzles without an account.
There is no difficulty selection and no session — each puzzle is drawn from
the whole pool and "Next puzzle" draws another. Anonymous visitors get a
daily budget of puzzles (see `Chesstrainer.GuestLimits`); when it runs out the
page asks them to sign up. Signed-in visitors are sent to `/train`, where they
can pick a difficulty. Move grading, opponent replies and review come from
`ChesstrainerWeb.EndgameLive.PlayCore`.
"""
use ChesstrainerWeb, :live_view
alias Chesstrainer.Endgames
alias Chesstrainer.GuestLimits
alias ChesstrainerWeb.ClientAddress
alias ChesstrainerWeb.EndgameLive.PlayCore
alias ChesstrainerWeb.PlayComponents
@impl true
def render(assigns) do
~H"""
<Layouts.app flash={@flash}>
<.header>
Train
<:subtitle>
<%= if @endgame do %>
A random endgame puzzle — {@endgame.color
|> Atom.to_string()
|> String.capitalize()} to move, rating {round(@endgame.rating)}.
<% else %>
Random endgame puzzles.
<% end %>
<span
:if={@guest_remaining != nil}
id="guest-remaining"
class="mt-1 block text-xs text-muted"
>
{remaining_label(@guest_remaining, @limit)}
</span>
<span class="mt-1 block text-xs text-muted">
<.link navigate={~p"/users/register"}>Create a free account</.link>
to track your rating and train at your level.
</span>
</:subtitle>
</.header>
<section
:if={@limit_reached}
id="guest-limit"
class="rounded-xl border border-hairline bg-canvas-raised p-6"
>
<h2 class="text-lg font-semibold">
You've used your {@limit} free puzzles today
</h2>
<p class="mt-1 text-sm text-muted">
Sign up for a free account to keep training. Your rating is tracked, so
the puzzles match your level.
</p>
<p class="mt-1 text-sm text-muted">
Free guest puzzles reset at 00:00 UTC (in {format_wait(@limit_reached)}).
</p>
<div class="mt-4 flex flex-wrap gap-2">
<.button id="guest-sign-up" navigate={~p"/users/register"} variant="primary">
<.icon name="hero-user-plus" /> Sign up free
</.button>
<.button navigate={~p"/users/log-in"}>Log in</.button>
</div>
</section>
<PlayComponents.play_surface
:if={@endgame && @empty != :exhausted}
session={is_nil(@limit_reached)}
endgame={@endgame}
fen={@fen}
status={@status}
blocked={@blocked}
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}
move_input={@move_input}
move_input_error={@move_input_error}
last_check={@last_check}
last_checkmate={@last_checkmate}
/>
<p :if={@loading} class="text-base-content/70">Picking a random puzzle…</p>
<section
:if={@empty == :exhausted}
id="guest-pool-exhausted"
class="rounded-xl border border-hairline bg-canvas-raised p-6"
>
<h2 class="text-lg font-semibold">No more puzzles are available right now</h2>
<p class="mt-1 text-sm text-muted">
Try again in a moment, or create a free account to train at your level.
</p>
<div class="mt-4 flex flex-wrap gap-2">
<.button id="retry-pool" phx-click="retry_pool" variant="primary">
<.icon name="hero-arrow-path" /> Retry
</.button>
<.button navigate={~p"/users/register"}>Sign up free</.button>
<.button navigate={~p"/users/log-in"}>Log in</.button>
</div>
</section>
<section
:if={not @loading and is_nil(@endgame) and is_nil(@limit_reached)}
id="guest-pool-empty"
class="rounded-xl border border-hairline bg-canvas-raised p-6"
>
<h2 class="text-lg font-semibold">No endgames are available yet</h2>
<p class="mt-1 text-sm text-muted">
Please check back soon, or create a free account to be ready when they land.
</p>
<div class="mt-4 flex flex-wrap gap-2">
<.button id="retry-pool" phx-click="retry_pool" variant="primary">
<.icon name="hero-arrow-path" /> Retry
</.button>
<.button navigate={~p"/users/register"}>Sign up free</.button>
<.button navigate={~p"/users/log-in"}>Log in</.button>
</div>
</section>
</Layouts.app>
"""
end
@impl true
def mount(_params, _session, socket) do
socket =
socket
|> assign(:limit, GuestLimits.limit())
|> assign(:served_ids, [])
cond do
signed_in?(socket) ->
{:ok, redirect(socket, to: ~p"/train")}
connected?(socket) ->
take_puzzle(socket, ClientAddress.from_socket(socket))
true ->
{:ok,
socket
|> assign(:loading, true)
|> assign(:endgame, nil)
|> assign(:empty, nil)
|> assign(:guest_remaining, nil)
|> assign(:limit_reached, nil)
|> assign(:guest_address, nil)}
end
end
@impl true
def handle_event("next_puzzle", _params, socket), do: {:noreply, next_puzzle(socket)}
def handle_event("retry_pool", _params, socket) do
if socket.assigns.empty == :exhausted do
{:noreply, next_puzzle(socket)}
else
{:ok, socket} = take_puzzle(socket, socket.assigns.guest_address)
{:noreply, socket}
end
end
def handle_event("endgame_move_played", params, socket),
do: PlayCore.move_played(socket, params)
def handle_event("submit_move", params, socket), do: PlayCore.submit_move(socket, params)
def handle_event("move_input", params, socket), do: PlayCore.move_input_changed(socket, params)
def handle_event("move_input_error", params, socket),
do: PlayCore.move_input_error(socket, params)
def handle_event("opponent_reply_applied", params, socket),
do: PlayCore.opponent_reply_applied(socket, params)
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("review_start", _params, socket), do: PlayCore.review_start(socket)
def handle_event("review_end", _params, socket), do: PlayCore.review_end(socket)
def handle_event("review_move", params, socket), do: PlayCore.review_move(socket, params)
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)
defp next_puzzle(socket) do
case GuestLimits.remaining(socket.assigns.guest_address) do
{:limit_reached, retry_ms} ->
socket
|> assign(:guest_remaining, nil)
|> assign(:empty, nil)
|> assign(:limit_reached, retry_ms)
{:ok, _remaining} ->
case random_unserved(socket) do
nil -> assign(socket, :empty, :exhausted)
endgame -> start_guest_puzzle(socket, socket.assigns.guest_address, endgame)
end
end
end
defp take_puzzle(socket, address) do
case GuestLimits.remaining(address) do
{:limit_reached, retry_ms} ->
{:ok, limit_wall(socket, address, retry_ms)}
{:ok, _remaining} ->
case random_unserved(socket) do
nil -> {:ok, empty_pool(socket, address)}
endgame -> {:ok, start_guest_puzzle(socket, address, endgame)}
end
end
end
# Prefer an endgame this visitor has not seen in this session. Once the whole
# pool is served — only possible on a very long guest session — start over
# rather than dead-end.
defp random_unserved(socket) do
Endgames.random_endgame(exclude_ids: socket.assigns.served_ids) ||
Endgames.random_endgame()
end
defp start_guest_puzzle(socket, address, endgame) do
case GuestLimits.take(address) do
{:ok, remaining} ->
socket
|> assign(:loading, false)
|> assign(:guest_address, address)
|> assign(:guest_remaining, remaining)
|> assign(:limit_reached, nil)
|> assign(:empty, nil)
|> assign(:served_ids, [endgame.id | socket.assigns.served_ids])
|> PlayCore.init(endgame, page_title: "Train")
{:limit_reached, retry_ms} ->
limit_wall(socket, address, retry_ms)
end
end
defp empty_pool(socket, address) do
socket
|> assign(:loading, false)
|> assign(:guest_address, address)
|> assign(:endgame, nil)
|> assign(:empty, nil)
|> assign(:guest_remaining, nil)
|> assign(:limit_reached, nil)
end
defp limit_wall(socket, address, retry_ms) do
socket
|> assign(:loading, false)
|> assign(:guest_address, address)
|> assign(:guest_remaining, nil)
|> assign(:limit_reached, retry_ms)
|> assign(:endgame, nil)
|> assign(:empty, nil)
end
defp signed_in?(socket) do
case socket.assigns.current_scope do
%{user: %{}} -> true
_ -> false
end
end
defp remaining_label(0, _limit), do: "Last free puzzle today"
defp remaining_label(remaining, limit),
do: "#{remaining} of #{limit} free puzzles left today"
defp format_wait(ms) when is_integer(ms) do
minutes = max(div(ms + 59_999, 60_000), 1)
hours = div(minutes, 60)
mins = rem(minutes, 60)
if hours > 0, do: "#{hours}h #{mins}m", else: "#{mins}m"
end
end