mirror of
https://github.com/TheRealOwenRees/chess-endgame-trainer.git
synced 2026-11-18 11:42:07 +00:00
Rate users and endgames with Glicko (#40)
This commit is contained in:
@@ -24,6 +24,10 @@ config :chesstrainer,
|
|||||||
ecto_repos: [Chesstrainer.Repo],
|
ecto_repos: [Chesstrainer.Repo],
|
||||||
generators: [timestamp_type: :utc_datetime]
|
generators: [timestamp_type: :utc_datetime]
|
||||||
|
|
||||||
|
# Glicko rating system. `system_constant` is the volatility constraint passed
|
||||||
|
# through to the Glicko package.
|
||||||
|
config :chesstrainer, :ratings, system_constant: 0.8
|
||||||
|
|
||||||
# Configure the endpoint
|
# Configure the endpoint
|
||||||
config :chesstrainer, ChesstrainerWeb.Endpoint,
|
config :chesstrainer, ChesstrainerWeb.Endpoint,
|
||||||
url: [host: "localhost"],
|
url: [host: "localhost"],
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ defmodule Chesstrainer.Accounts.User do
|
|||||||
field :hashed_password, :string, redact: true
|
field :hashed_password, :string, redact: true
|
||||||
field :role, Ecto.Enum, values: [:member, :moderator, :admin, :super_admin], default: :member
|
field :role, Ecto.Enum, values: [:member, :moderator, :admin, :super_admin], default: :member
|
||||||
field :plan, Ecto.Enum, values: [:free, :premium], default: :free
|
field :plan, Ecto.Enum, values: [:free, :premium], default: :free
|
||||||
|
field :rating, :float, default: 1500.0
|
||||||
|
field :rating_deviation, :float, default: 350.0
|
||||||
field :confirmed_at, :utc_datetime
|
field :confirmed_at, :utc_datetime
|
||||||
field :authenticated_at, :utc_datetime, virtual: true
|
field :authenticated_at, :utc_datetime, virtual: true
|
||||||
|
|
||||||
|
|||||||
@@ -17,8 +17,8 @@ defmodule Chesstrainer.Endgames.Endgame do
|
|||||||
field :message, :string
|
field :message, :string
|
||||||
field :notes, :string
|
field :notes, :string
|
||||||
field :result, Ecto.Enum, values: [:win, :loss, :draw]
|
field :result, Ecto.Enum, values: [:win, :loss, :draw]
|
||||||
field :rating, :integer, default: 1500
|
field :rating, :float, default: 1500.0
|
||||||
field :rating_deviation, :integer
|
field :rating_deviation, :float, default: 350.0
|
||||||
field :times_attempted, :integer
|
field :times_attempted, :integer
|
||||||
field :times_solved, :integer
|
field :times_solved, :integer
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
defmodule Chesstrainer.Ratings do
|
||||||
|
@moduledoc """
|
||||||
|
Applies Glicko rating updates to a finished attempt.
|
||||||
|
|
||||||
|
Both sides are rated: the user as the player and the endgame as the
|
||||||
|
opponent, then the reverse so the endgame's difficulty tracks its results.
|
||||||
|
"""
|
||||||
|
|
||||||
|
alias Chesstrainer.Repo
|
||||||
|
alias Chesstrainer.Accounts.User
|
||||||
|
alias Chesstrainer.Endgames.Endgame
|
||||||
|
alias Chesstrainer.Attempts.Attempt
|
||||||
|
|
||||||
|
@default_system_constant 0.8
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
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 the updated user, endgame and attempt.
|
||||||
|
"""
|
||||||
|
def rate_attempt(%Attempt{outcome: outcome} = attempt) do
|
||||||
|
user = Repo.get!(User, attempt.user_id)
|
||||||
|
endgame = Repo.get!(Endgame, attempt.endgame_id)
|
||||||
|
|
||||||
|
score = score_for(outcome)
|
||||||
|
user_player = player(user)
|
||||||
|
endgame_player = player(endgame)
|
||||||
|
|
||||||
|
new_user =
|
||||||
|
Glicko.new_rating(user_player, [Glicko.Result.new(endgame_player, score)], opts())
|
||||||
|
|
||||||
|
new_endgame =
|
||||||
|
Glicko.new_rating(endgame_player, [Glicko.Result.new(user_player, 1.0 - score)], opts())
|
||||||
|
|
||||||
|
Repo.transaction(fn ->
|
||||||
|
user =
|
||||||
|
user
|
||||||
|
|> Ecto.Changeset.change(
|
||||||
|
rating: new_user.rating,
|
||||||
|
rating_deviation: new_user.rating_deviation
|
||||||
|
)
|
||||||
|
|> Repo.update!()
|
||||||
|
|
||||||
|
endgame =
|
||||||
|
endgame
|
||||||
|
|> Ecto.Changeset.change(
|
||||||
|
rating: new_endgame.rating,
|
||||||
|
rating_deviation: new_endgame.rating_deviation
|
||||||
|
)
|
||||||
|
|> Repo.update!()
|
||||||
|
|
||||||
|
attempt =
|
||||||
|
attempt
|
||||||
|
|> Ecto.Changeset.change(rated_at: DateTime.utc_now(:second))
|
||||||
|
|> Repo.update!()
|
||||||
|
|
||||||
|
%{user: user, endgame: endgame, attempt: attempt}
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
|
||||||
|
defp player(%{rating: rating, rating_deviation: rating_deviation}) do
|
||||||
|
Glicko.Player.new_v1(rating: rating, rating_deviation: rating_deviation)
|
||||||
|
end
|
||||||
|
|
||||||
|
defp score_for(:solved), do: 1.0
|
||||||
|
defp score_for(:failed), do: 0.0
|
||||||
|
|
||||||
|
defp opts do
|
||||||
|
ratings = Application.get_env(:chesstrainer, :ratings, [])
|
||||||
|
[system_constant: Keyword.get(ratings, :system_constant, @default_system_constant)]
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -73,7 +73,12 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
|
|||||||
<.form for={@form} id="endgame-form" phx-change="validate" phx-submit="save">
|
<.form for={@form} id="endgame-form" phx-change="validate" phx-submit="save">
|
||||||
<.input field={@form[:fen]} type="text" label="Fen" disabled={@live_action == :edit} />
|
<.input field={@form[:fen]} type="text" label="Fen" disabled={@live_action == :edit} />
|
||||||
<.input field={@form[:color]} type="text" label="Color" disabled />
|
<.input field={@form[:color]} type="text" label="Color" disabled />
|
||||||
<.input field={@form[:rating]} type="number" label="Rating" />
|
<.input
|
||||||
|
field={@form[:rating]}
|
||||||
|
type="number"
|
||||||
|
value={rating_display(@form[:rating])}
|
||||||
|
label="Rating"
|
||||||
|
/>
|
||||||
<.input field={@form[:message]} type="textarea" label="Message" />
|
<.input field={@form[:message]} type="textarea" label="Message" />
|
||||||
<.input field={@form[:notes]} type="textarea" label="Notes" />
|
<.input field={@form[:notes]} type="textarea" label="Notes" />
|
||||||
<.input
|
<.input
|
||||||
@@ -244,6 +249,12 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# Ratings are stored as floats (Glicko); the admin form presents them as whole numbers.
|
||||||
|
defp rating_display(%Phoenix.HTML.FormField{value: value}) when is_float(value),
|
||||||
|
do: round(value)
|
||||||
|
|
||||||
|
defp rating_display(%Phoenix.HTML.FormField{value: value}), do: value
|
||||||
|
|
||||||
defp return_path("index", _endgame), do: ~p"/admin/endgames"
|
defp return_path("index", _endgame), do: ~p"/admin/endgames"
|
||||||
defp return_path("show", endgame), do: ~p"/admin/endgames/#{endgame}"
|
defp return_path("show", endgame), do: ~p"/admin/endgames/#{endgame}"
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ defmodule ChesstrainerWeb.EndgameLive.Index do
|
|||||||
<span :if={endgame.themes == []} class="text-base-content/50">None</span>
|
<span :if={endgame.themes == []} class="text-base-content/50">None</span>
|
||||||
</td>
|
</td>
|
||||||
<td phx-click={JS.navigate(~p"/admin/endgames/#{endgame}")} class="hover:cursor-pointer">
|
<td phx-click={JS.navigate(~p"/admin/endgames/#{endgame}")} class="hover:cursor-pointer">
|
||||||
{endgame.rating}
|
{round(endgame.rating)}
|
||||||
</td>
|
</td>
|
||||||
<td class="w-0 font-semibold">
|
<td class="w-0 font-semibold">
|
||||||
<div class="flex gap-4">
|
<div class="flex gap-4">
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
|
|||||||
alias Chesstrainer.Attempts
|
alias Chesstrainer.Attempts
|
||||||
alias Chesstrainer.Endgames
|
alias Chesstrainer.Endgames
|
||||||
alias Chesstrainer.Endgames.Tablebase
|
alias Chesstrainer.Endgames.Tablebase
|
||||||
|
alias Chesstrainer.Ratings
|
||||||
|
|
||||||
@impl true
|
@impl true
|
||||||
def render(assigns) do
|
def render(assigns) do
|
||||||
@@ -12,8 +13,12 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
|
|||||||
<.header>
|
<.header>
|
||||||
Play endgame {@endgame.key}
|
Play endgame {@endgame.key}
|
||||||
<:subtitle>
|
<:subtitle>
|
||||||
{@endgame.color |> Atom.to_string() |> String.capitalize()} to move · Rating: {@endgame.rating} · Attempts: {@endgame.times_attempted ||
|
{@endgame.color |> Atom.to_string() |> String.capitalize()} to move · Rating: {round(
|
||||||
0} · Solved: {@endgame.times_solved || 0}
|
@endgame.rating
|
||||||
|
)} · Attempts: {@endgame.times_attempted ||
|
||||||
|
0} · Solved: {@endgame.times_solved || 0}<span :if={@user_rating}> · Your rating: {round(
|
||||||
|
@user_rating
|
||||||
|
)}</span>
|
||||||
<p class="text-xs text-gray-500 flex items-center mt-1">
|
<p class="text-xs text-gray-500 flex items-center mt-1">
|
||||||
<span>FEN: {@endgame.fen}</span>
|
<span>FEN: {@endgame.fen}</span>
|
||||||
<button
|
<button
|
||||||
@@ -180,6 +185,7 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
|
|||||||
socket
|
socket
|
||||||
|> assign(:page_title, "Play endgame")
|
|> assign(:page_title, "Play endgame")
|
||||||
|> assign(:endgame, endgame)
|
|> assign(:endgame, endgame)
|
||||||
|
|> assign(:user_rating, user_rating(socket.assigns.current_scope))
|
||||||
|> assign(:fen, endgame.fen)
|
|> assign(:fen, endgame.fen)
|
||||||
|> assign(:tablebase, nil)
|
|> assign(:tablebase, nil)
|
||||||
|> assign(:status, :loading)
|
|> assign(:status, :loading)
|
||||||
@@ -658,18 +664,21 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
|
|||||||
|
|
||||||
defp solve_attempt(socket) do
|
defp solve_attempt(socket) do
|
||||||
{:ok, endgame} = Endgames.record_solve(socket.assigns.endgame)
|
{:ok, endgame} = Endgames.record_solve(socket.assigns.endgame)
|
||||||
record_attempt(socket, :solved)
|
|
||||||
|
socket =
|
||||||
|
socket
|
||||||
|
|> assign(:endgame, endgame)
|
||||||
|
|> record_attempt(:solved)
|
||||||
|
|
||||||
{:noreply,
|
{:noreply,
|
||||||
socket
|
socket
|
||||||
|> assign(:status, :solved)
|
|> assign(:status, :solved)
|
||||||
|> assign(:endgame, endgame)
|
|
||||||
|> assign(:awaiting_reply, false)
|
|> assign(:awaiting_reply, false)
|
||||||
|> assign(:best_move, nil)}
|
|> assign(:best_move, nil)}
|
||||||
end
|
end
|
||||||
|
|
||||||
defp fail_attempt(socket) do
|
defp fail_attempt(socket) do
|
||||||
record_attempt(socket, :failed)
|
socket = record_attempt(socket, :failed)
|
||||||
|
|
||||||
{:noreply,
|
{:noreply,
|
||||||
socket
|
socket
|
||||||
@@ -679,8 +688,21 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
|
|||||||
end
|
end
|
||||||
|
|
||||||
defp record_attempt(socket, outcome) do
|
defp record_attempt(socket, outcome) do
|
||||||
Attempts.record_attempt(socket.assigns.current_scope, socket.assigns.endgame, outcome)
|
case Attempts.record_attempt(socket.assigns.current_scope, socket.assigns.endgame, outcome) do
|
||||||
|
{:ok, attempt} ->
|
||||||
|
{:ok, %{user: user, endgame: endgame}} = Ratings.rate_attempt(attempt)
|
||||||
|
|
||||||
|
socket
|
||||||
|
|> assign(:endgame, endgame)
|
||||||
|
|> assign(:user_rating, user.rating)
|
||||||
|
|
||||||
|
_ ->
|
||||||
|
socket
|
||||||
end
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp user_rating(%{user: %{rating: rating}}), do: rating
|
||||||
|
defp user_rating(_), do: nil
|
||||||
|
|
||||||
defp best_move_text(tablebase) do
|
defp best_move_text(tablebase) do
|
||||||
san =
|
san =
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayerIndex do
|
|||||||
{endgame.result}
|
{endgame.result}
|
||||||
</td>
|
</td>
|
||||||
<td phx-click={JS.navigate(~p"/endgames/#{endgame}/play")} class="hover:cursor-pointer">
|
<td phx-click={JS.navigate(~p"/endgames/#{endgame}/play")} class="hover:cursor-pointer">
|
||||||
{endgame.rating}
|
{round(endgame.rating)}
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<span :for={theme <- endgame.themes} class="badge badge-sm">
|
<span :for={theme <- endgame.themes} class="badge badge-sm">
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ defmodule ChesstrainerWeb.EndgameLive.Show do
|
|||||||
<:item title="Fen">{@endgame.fen}</:item>
|
<:item title="Fen">{@endgame.fen}</:item>
|
||||||
<:item title="Key">{@endgame.key}</:item>
|
<:item title="Key">{@endgame.key}</:item>
|
||||||
<:item title="Color">{@endgame.color}</:item>
|
<:item title="Color">{@endgame.color}</:item>
|
||||||
<:item title="Rating">{@endgame.rating}</:item>
|
<:item title="Rating">{round(@endgame.rating)}</:item>
|
||||||
<:item title="Message">{@endgame.message}</:item>
|
<:item title="Message">{@endgame.message}</:item>
|
||||||
<:item title="Notes">{@endgame.notes}</:item>
|
<:item title="Notes">{@endgame.notes}</:item>
|
||||||
<:item title="Result">{@endgame.result}</:item>
|
<:item title="Result">{@endgame.result}</:item>
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
defmodule Chesstrainer.Repo.Migrations.AddRatingsToUsersAndEndgames do
|
||||||
|
use Ecto.Migration
|
||||||
|
|
||||||
|
def change do
|
||||||
|
alter table(:endgames) do
|
||||||
|
modify :rating, :float, default: 1500.0
|
||||||
|
modify :rating_deviation, :float, default: 350.0
|
||||||
|
end
|
||||||
|
|
||||||
|
alter table(:users) do
|
||||||
|
add :rating, :float, null: false, default: 1500.0
|
||||||
|
add :rating_deviation, :float, null: false, default: 350.0
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
defmodule Chesstrainer.RatingsTest do
|
||||||
|
use Chesstrainer.DataCase, async: true
|
||||||
|
|
||||||
|
import Chesstrainer.AccountsFixtures
|
||||||
|
import Chesstrainer.EndgamesFixtures
|
||||||
|
|
||||||
|
alias Chesstrainer.Accounts.Scope
|
||||||
|
alias Chesstrainer.Accounts.User
|
||||||
|
alias Chesstrainer.Attempts
|
||||||
|
alias Chesstrainer.Attempts.Attempt
|
||||||
|
alias Chesstrainer.Endgames.Endgame
|
||||||
|
alias Chesstrainer.Ratings
|
||||||
|
|
||||||
|
describe "rate_attempt/1" do
|
||||||
|
test "a solve raises the user's rating and lowers the endgame's" do
|
||||||
|
user = user_fixture()
|
||||||
|
endgame = endgame_fixture(rating: 1800)
|
||||||
|
{:ok, attempt} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
|
||||||
|
|
||||||
|
assert {:ok, %{user: rated_user, endgame: rated_endgame, attempt: rated_attempt}} =
|
||||||
|
Ratings.rate_attempt(attempt)
|
||||||
|
|
||||||
|
assert rated_user.rating > 1500.0
|
||||||
|
assert rated_endgame.rating < 1800.0
|
||||||
|
assert is_float(rated_user.rating)
|
||||||
|
assert is_float(rated_user.rating_deviation)
|
||||||
|
assert is_float(rated_endgame.rating)
|
||||||
|
assert is_float(rated_endgame.rating_deviation)
|
||||||
|
refute is_nil(rated_attempt.rated_at)
|
||||||
|
end
|
||||||
|
|
||||||
|
test "a fail lowers the user's rating and raises the endgame's" do
|
||||||
|
user = user_fixture()
|
||||||
|
endgame = endgame_fixture(rating: 1800)
|
||||||
|
{:ok, attempt} = Attempts.record_attempt(Scope.for_user(user), endgame, :failed)
|
||||||
|
|
||||||
|
assert {:ok, %{user: rated_user, endgame: rated_endgame}} = Ratings.rate_attempt(attempt)
|
||||||
|
|
||||||
|
assert rated_user.rating < 1500.0
|
||||||
|
assert rated_endgame.rating > 1800.0
|
||||||
|
end
|
||||||
|
|
||||||
|
test "persists both ratings and stamps the attempt as rated" do
|
||||||
|
user = user_fixture()
|
||||||
|
endgame = endgame_fixture(rating: 1800)
|
||||||
|
{:ok, attempt} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
|
||||||
|
|
||||||
|
{:ok, _} = Ratings.rate_attempt(attempt)
|
||||||
|
|
||||||
|
assert Repo.get!(User, user.id).rating > 1500.0
|
||||||
|
assert Repo.get!(Endgame, endgame.id).rating < 1800.0
|
||||||
|
assert Repo.get!(Attempt, attempt.id).rated_at
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -4,6 +4,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
|
|||||||
import Phoenix.LiveViewTest
|
import Phoenix.LiveViewTest
|
||||||
import Chesstrainer.EndgamesFixtures
|
import Chesstrainer.EndgamesFixtures
|
||||||
|
|
||||||
|
alias Chesstrainer.Accounts.User
|
||||||
alias Chesstrainer.Attempts.Attempt
|
alias Chesstrainer.Attempts.Attempt
|
||||||
alias Chesstrainer.Endgames
|
alias Chesstrainer.Endgames
|
||||||
alias Chesstrainer.Endgames.Tablebase
|
alias Chesstrainer.Endgames.Tablebase
|
||||||
@@ -72,7 +73,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
|
|||||||
color: :black,
|
color: :black,
|
||||||
key: key,
|
key: key,
|
||||||
result: :win,
|
result: :win,
|
||||||
rating: 1500
|
rating: 1500.0
|
||||||
})
|
})
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -460,19 +461,48 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
|
|||||||
assert attempt.user_id == user.id
|
assert attempt.user_id == user.id
|
||||||
assert attempt.outcome == :failed
|
assert attempt.outcome == :failed
|
||||||
end
|
end
|
||||||
|
|
||||||
|
test "rates the user and the endgame on a solve", %{conn: conn, user: user} do
|
||||||
|
endgame = endgame_fixture(rating: 1800)
|
||||||
|
fen_after = "8/8/8/8/8/8/8/8 b - - 0 1"
|
||||||
|
|
||||||
|
seed_tablebase(endgame.fen, moves: grading_moves())
|
||||||
|
seed_tablebase(fen_after, checkmate: true, moves: [])
|
||||||
|
|
||||||
|
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play")
|
||||||
|
|
||||||
|
render_hook(view, "endgame_move_played", %{
|
||||||
|
"from" => "d1",
|
||||||
|
"to" => "d7",
|
||||||
|
"san" => "Qd7+",
|
||||||
|
"prev_fen" => endgame.fen,
|
||||||
|
"fen" => fen_after,
|
||||||
|
"endgame_id" => endgame.id
|
||||||
|
})
|
||||||
|
|
||||||
|
rated_user = Repo.get!(User, user.id)
|
||||||
|
|
||||||
|
assert render(view) =~ "Your rating: #{round(rated_user.rating)}"
|
||||||
|
assert rated_user.rating > 1500.0
|
||||||
|
assert Endgames.get_endgame!(endgame.id).rating < 1800.0
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
describe "per-user attempt records without a signed-in user" do
|
describe "per-user attempt records without a signed-in user" do
|
||||||
test "records nothing for an anonymous visitor", %{conn: conn} do
|
test "records nothing and leaves ratings untouched", %{conn: conn} do
|
||||||
endgame = endgame_fixture()
|
endgame = endgame_fixture(rating: 1800)
|
||||||
seed_tablebase(endgame.fen, moves: grading_moves())
|
seed_tablebase(endgame.fen, moves: grading_moves())
|
||||||
|
|
||||||
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play")
|
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play")
|
||||||
|
|
||||||
play_move(view, endgame, "d1", "d4", "Qd4")
|
play_move(view, endgame, "d1", "d4", "Qd4")
|
||||||
|
|
||||||
assert render(view) =~ "Failed"
|
html = render(view)
|
||||||
|
|
||||||
|
assert html =~ "Failed"
|
||||||
|
refute html =~ "Your rating"
|
||||||
assert Repo.aggregate(Attempt, :count) == 0
|
assert Repo.aggregate(Attempt, :count) == 0
|
||||||
|
assert Endgames.get_endgame!(endgame.id).rating == 1800.0
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user