Skip to content

Instantly share code, notes, and snippets.

@intercaetera
Created October 1, 2021 10:57
Show Gist options
  • Save intercaetera/7f736addacec130dc420cdd875382d8f to your computer and use it in GitHub Desktop.
Save intercaetera/7f736addacec130dc420cdd875382d8f to your computer and use it in GitHub Desktop.
defmodule DogsvscatsWeb.Fight do
use Phoenix.LiveView
alias Dogsvscats.FightMetrics
def mount(_params, _session, socket) do
if connected?(socket), do: :timer.send_interval(1000, :update)
{:ok, assign(socket, %{team: nil, state: FightMetrics.get_state()})}
end
def handle_info(:update, socket) do
{:noreply, assign(socket, state: FightMetrics.get_state())}
end
def handle_event("choose_dogs", _, socket) do
{:noreply, assign(socket, :team, :dogs)}
end
def handle_event("choose_cats", _, socket) do
{:noreply, assign(socket, :team, :cats)}
end
def handle_event("hit", _, socket) do
case socket.assigns.team do
:dogs -> FightMetrics.dog_hit()
:cats -> FightMetrics.cat_hit()
end
{:noreply, assign(socket, :state, FightMetrics.get_state())}
end
def render(%{ team: nil } = assigns) do
~L"""
<div>
<h1>Choose your team!</h1>
<button phx-click="choose_dogs" class="team-select">๐Ÿถ</button> vs <button phx-click="choose_cats" class="team-select">๐Ÿฑ</button>
</div>
"""
end
def render(assigns) do
~L"""
<div>
<div>
<h2>Your chosen team is:</h2>
<%= @team %>
</div>
<div>
<h2>The score is now:</h2>
<h1><%= state_format(@state) %></h1>
</div>
<div>
<button phx-click="hit">HIT EM!!!!</button>
</div>
</div>
"""
end
defp state_format(state) when state > 0, do: "๐Ÿถ #{state} ๐Ÿถ"
defp state_format(state) when state < 0, do: "๐Ÿฑ #{abs(state)} ๐Ÿฑ"
defp state_format(state), do: state
end
defmodule Dogsvscats.FightMetrics do
use GenServer
def start_link(_) do
GenServer.start_link(__MODULE__, nil, [name: __MODULE__])
end
def init(_) do
# positive: dogs win, negative: cats win
{:ok, 0}
end
def dog_hit(), do: GenServer.cast(__MODULE__, :dog)
def cat_hit(), do: GenServer.cast(__MODULE__, :cat)
def get_state(), do: GenServer.call(__MODULE__, :state)
def handle_call(:state, _from, state) do
{:reply, state, state}
end
def handle_cast(:dog, state) do
{:noreply, state + 1}
end
def handle_cast(:cat, state) do
{:noreply, state - 1}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment