programming-phoenix-liveview/pento/lib/pento_web/live/wrong_live.ex

89 lines
2.0 KiB
Elixir
Raw Normal View History

2024-08-15 19:47:05 +02:00
defmodule PentoWeb.WrongLive do
use PentoWeb, :live_view
2024-08-16 16:54:19 +02:00
@winning_score 15
2024-08-15 19:47:05 +02:00
def mount(_params, _session, socket) do
2024-08-16 16:54:19 +02:00
socket =
socket
|> assign(score: 0)
|> assign(message: "Make a guess:")
|> assign(number: random_number())
{:ok, socket}
2024-08-15 19:47:05 +02:00
end
def render(assigns) do
~H"""
<h1 class="mb-4 text-4xl font-extrabold">Your score: <%= @score %></h1>
<h2>
<%= @message %>
</h2>
<br />
2024-08-16 16:54:19 +02:00
<h2 class="flex justify-center">
<%= if @score >= winning_score() do %>
2024-08-15 19:47:05 +02:00
<.link
2024-08-16 16:54:19 +02:00
href={~p"/guess"}
class="bg-blue-500 hover:bg-blue-700 text-white text-center font-bold py-2 px-4 border border-blue-700 rounded m-1"
2024-08-15 19:47:05 +02:00
>
2024-08-16 16:54:19 +02:00
Play again!
2024-08-15 19:47:05 +02:00
</.link>
2024-08-16 16:54:19 +02:00
<% else %>
<%= for n <- 1..10 do %>
<.link
class="bg-blue-500 hover:bg-blue-700 text-white text-center font-bold py-2 px-4 border border-blue-700 rounded m-1"
phx-click="guess"
phx-value-number={n}
>
<%= n %>
</.link>
<% end %>
2024-08-15 19:47:05 +02:00
<% end %>
</h2>
"""
end
2024-08-16 16:54:19 +02:00
defp random_number() do
:rand.uniform(10)
2024-08-15 19:47:05 +02:00
end
2024-08-16 16:54:19 +02:00
defp winning_score(), do: @winning_score
2024-08-15 19:47:05 +02:00
def handle_event("guess", %{"number" => guess}, socket) do
2024-08-16 16:54:19 +02:00
number = socket.assigns.number |> to_string()
socket =
if number == guess do
correct_guess(guess, socket)
else
wrong_guess(guess, socket)
end
2024-08-15 19:47:05 +02:00
2024-08-16 16:54:19 +02:00
{:noreply, socket}
end
defp correct_guess(guess, socket) do
score = socket.assigns.score + 8
message = if score >= @winning_score do
"Your guess: #{guess}. Correct. You won!"
else
"Your guess: #{guess}. Correct. Guess the next number."
end
socket
|> assign(message: message)
|> assign(score: score)
|> assign(number: random_number())
end
defp wrong_guess(guess, socket) do
message = "Your guess: #{guess}. Wrong. Guess again."
2024-08-15 19:47:05 +02:00
score = socket.assigns.score - 1
2024-08-16 16:54:19 +02:00
socket
|> assign(message: message)
|> assign(score: score)
2024-08-15 19:47:05 +02:00
end
end