defmodule ExampleWeb.LiveSigil do use ExampleWeb, :live_view def render(assigns) do ~V"""

Sorting Guessing Game

The server has put these letters {shown_word} in some random order which you need to guess. Correct guess earns you 10 points.

{#if status_message}
{status_message}
{/if} {#if error_message}
{error_message}
{/if}

Leaderboard

{#if Object.keys(leaderboard).length > 0} {#each Object.entries(leaderboard).sort((a, b) => b[1] - a[1]) as [name, score]}
{name} {score} pts
{/each} {:else}

No scores yet. Be the first!

{/if}
""" end @doc """ Mounts the LiveView, initializing the server-side state. """ def mount(_params, _session, socket) do # On mount, we shuffle the items and set the initial state. new_secret_word = Enum.shuffle(String.split("ABC","", trim: true)) |> Enum.join socket = assign(socket, secret_word: new_secret_word, shown_word: "ABC", leaderboard: %{} ) {:ok, socket} end @doc """ Handles the `submit_answer` event pushed from the Svelte client. """ def handle_event("submit_answer", %{"name" => name, "attempt" => attempt}, socket) do # All game logic happens securely on the server. if socket.assigns.secret_word == attempt do # Correct Answer new_leaderboard = Map.update(socket.assigns.leaderboard, name, 10, &(&1 + 10)) # Push a feedback event to the client. socket = push_event(socket, "feedback", %{message: "Correct! You earned 10 points."}) # Reset the game for a new round new_secret_word = Enum.shuffle(String.split("ABC","", trim: true)) |> Enum.join new_socket = assign(socket, secret_word: new_secret_word, shown_word: "ABC", leaderboard: new_leaderboard ) {:noreply, new_socket} else # Incorrect Answer socket = push_event(socket, "feedback", %{message: "Not quite, try again!"}) {:noreply, socket} end end end