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.Accounts.Scope alias Chesstrainer.Puzzles alias ChesstrainerWeb.EndgameLive.PlayCore alias ChesstrainerWeb.PlayComponents @impl true def render(assigns) do ~H""" <.header> Train <:subtitle> <%= if @session do %> {difficulty_label(@session.difficulty)} · Play a run of endgame puzzles. <% else %> Choose a difficulty to start a session. <% end %> <:actions> <.button :if={@session} phx-click="stop_session"> <.icon name="hero-x-mark" /> Stop session <.button :if={Scope.premium?(@current_scope)} id="puzzle-search" navigate={~p"/endgames"} > <.icon name="hero-magnifying-glass" /> Puzzle Search <%= if @session do %>
Difficulty {difficulty_label(@session.difficulty)} Time {format_duration(elapsed_ms(@session))} Avg/puzzle {format_duration(avg_ms(@session))} Rating {round(@user_rating)} <.rating_change :if={@session.count > 0} id="session-rating-change" delta={net_gain(@session, @user_rating)} />

You've played every puzzle available right now

There are no more {difficulty_label(@session.difficulty)} puzzles right now. Try again, or pick another difficulty.

<.button id="retry-pool" phx-click="retry_pool" variant="primary"> <.icon name="hero-arrow-path" /> Retry <.button id="change-difficulty" phx-click="stop_session"> Change difficulty
<% else %>

Last session

Difficulty {difficulty_label(@last_session.difficulty)} Time {format_duration(@last_session.duration_ms)} Puzzles {@last_session.count} Avg/puzzle {format_duration(@last_session.avg_ms)} Rating {round(@last_session.rating)} <.rating_change :if={@last_session.count > 0} delta={@last_session.gain} />

Choose a difficulty

Easy draws easier endgames, hard draws harder ones — your rating sets the centre.

<.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" />
<.rating_guide rating={@user_rating} deviation={@user_deviation} />

No puzzles available right now

There are no {difficulty_label(@pool.difficulty)} puzzles yet. Try again, or choose another difficulty.

<.button id="retry-pool" phx-click="retry_pool" class="mt-3"> <.icon name="hero-arrow-path" /> Retry
<%= for {difficulty, label, description} <- difficulty_options() do %> <.button id={"difficulty-#{difficulty}"} phx-click="start_session" phx-value-difficulty={Atom.to_string(difficulty)} variant={if difficulty == :medium, do: "primary", else: "secondary"} class="w-full justify-between" > {label} {description} <% end %>
<.button navigate={~p"/"} variant="ghost" class="mt-2 w-full justify-center"> <.icon name="hero-arrow-left" />Return Home
<% end %>
""" 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(:pool, nil) |> assign(:user_rating, socket.assigns.current_scope.user.rating) |> assign(:user_deviation, socket.assigns.current_scope.user.rating_deviation)} end @impl true def handle_event("start_session", %{"difficulty" => difficulty}, socket) do {:noreply, start_session(socket, parse_difficulty(difficulty))} end def handle_event("next_puzzle", _params, socket), do: {:noreply, next_puzzle(socket)} def handle_event("retry_pool", _params, socket) do socket = case socket.assigns.session do nil -> case socket.assigns.pool do %{difficulty: difficulty} -> start_session(socket, difficulty) _ -> socket end _session -> next_puzzle(socket) end {:noreply, socket} 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, socket |> assign(:session, nil) |> assign(:pool, 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("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 {: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("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 start_session(socket, difficulty) do case Puzzles.next_endgame(selection_user(socket), difficulty) do nil -> assign(socket, :pool, %{difficulty: difficulty}) endgame -> session = %{ difficulty: difficulty, started_at_ms: System.system_time(:millisecond), baseline: socket.assigns.user_rating, count: 0, sum_ms: 0, served_ids: [endgame.id] } socket |> assign(:session, session) |> assign(:pool, nil) |> assign(:puzzle_started_mono, System.monotonic_time(:millisecond)) |> assign(:puzzle_counted, false) |> assign(:last_rating_delta, nil) |> PlayCore.init(endgame, page_title: "Train") end end defp next_puzzle(socket) do session = socket.assigns.session if session do case Puzzles.next_endgame(selection_user(socket), session.difficulty, exclude_ids: session.served_ids ) do nil -> assign(socket, :pool, %{difficulty: session.difficulty}) endgame -> session = %{session | served_ids: [endgame.id | session.served_ids]} socket |> assign(:session, session) |> assign(:pool, nil) |> assign(:puzzle_started_mono, System.monotonic_time(:millisecond)) |> assign(:puzzle_counted, false) |> assign(:last_rating_delta, nil) |> PlayCore.init(endgame, page_title: "Train") end else socket end end # 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 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), rating: 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 do [ {:easy, "Easy", "easier than your rating"}, {:medium, "Medium", "around your rating"}, {:hard, "Hard", "harder than your rating"} ] 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 end