Created
October 1, 2021 10:57
-
-
Save intercaetera/7f736addacec130dc420cdd875382d8f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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