2023-04-16 21:32:56 +02:00
|
|
|
defmodule ChickenEggWeb.IndexLive do
|
|
|
|
use ChickenEggWeb, :live_view
|
|
|
|
|
|
|
|
alias ChickenEggWeb.ChickenComponents
|
|
|
|
|
|
|
|
def render(assigns) do
|
|
|
|
~H"""
|
2023-04-19 15:17:33 +02:00
|
|
|
<div
|
|
|
|
class="board relative bg-green-700 w-screen h-screen select-none"
|
|
|
|
id="chicken-egg"
|
|
|
|
phx-window-keyup="boak"
|
|
|
|
phx-key=" "
|
|
|
|
phx-hook="ChickenEgg"
|
|
|
|
>
|
|
|
|
<div class="score absolute right-0 z-50 text-fuchsia-50 text-4xl font-semibold p-4 text-outline">
|
|
|
|
<%= @score %>
|
|
|
|
</div>
|
|
|
|
|
2023-04-16 21:32:56 +02:00
|
|
|
<ChickenComponents.chicken x={@chicken.x} y={@chicken.y} />
|
|
|
|
|
|
|
|
<div id="chicken-eggs" phx-update="stream">
|
|
|
|
<div :for={{dom_id, egg} <- @streams.eggs} class="egg" id={dom_id}>
|
|
|
|
<ChickenComponents.egg x={egg.x} y={egg.y} />
|
|
|
|
</div>
|
|
|
|
</div>
|
|
|
|
</div>
|
|
|
|
"""
|
|
|
|
end
|
|
|
|
|
|
|
|
def mount(_params, _session, socket) do
|
|
|
|
{:ok,
|
|
|
|
socket
|
2023-04-19 13:47:14 +02:00
|
|
|
|> assign(:chicken, %{x: 42, y: 47})
|
2023-04-19 15:17:33 +02:00
|
|
|
|> assign(:score, 0)
|
|
|
|
|> stream(:eggs, [])}
|
2023-04-16 21:32:56 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def handle_event("boak", _params, socket) do
|
2023-04-19 15:17:33 +02:00
|
|
|
score = socket.assigns.score
|
2023-04-16 21:32:56 +02:00
|
|
|
%{x: cx, y: cy} = socket.assigns.chicken
|
|
|
|
|
2023-04-19 15:17:33 +02:00
|
|
|
new_egg = %{id: "egg#{cx}#{cy}", x: cx, y: cy}
|
|
|
|
new_chicken = %{x: Enum.random(1..99), y: Enum.random(1..99)}
|
2023-04-16 21:32:56 +02:00
|
|
|
|
|
|
|
{:noreply,
|
|
|
|
socket
|
|
|
|
|> assign(:chicken, new_chicken)
|
2023-04-19 15:17:33 +02:00
|
|
|
|> assign(:score, score + 1)
|
2023-04-16 21:32:56 +02:00
|
|
|
|> stream_insert(:eggs, new_egg)}
|
|
|
|
end
|
|
|
|
end
|