Skip to content

Commit

Permalink
Game event and event handler
Browse files Browse the repository at this point in the history
  • Loading branch information
bigardone committed Apr 23, 2016
1 parent 48bc5c2 commit 28349c7
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/battleship.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ defmodule Battleship do
supervisor(Battleship.Endpoint, []),
# Here you could define other workers and supervisors as children
# worker(Battleship.Worker, [arg1, arg2, arg3]),
supervisor(Battleship.Game.Supervisor, [])
supervisor(Battleship.Game.Supervisor, []),
worker(Battleship.Game.Event, [])
]

# See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
Expand Down
17 changes: 17 additions & 0 deletions lib/battleship/game/event.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
defmodule Battleship.Game.Event do
def start_link do
{:ok, manager} = GenEvent.start_link(name: __MODULE__)

handlers = [
Battleship.Game.EventHandler
]

Enum.each(handlers, &GenEvent.add_handler(manager, &1, []))

{:ok, manager}
end

def game_created, do: GenEvent.notify(__MODULE__, :game_created)
def player_joined, do: GenEvent.notify(__MODULE__, :player_joined)
def game_over, do: GenEvent.notify(__MODULE__, :game_over)
end
16 changes: 16 additions & 0 deletions lib/battleship/game/event_handler.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
defmodule Battleship.Game.EventHandler do
use GenEvent
alias Battleship.LobbyChannel

def handle_event(:game_created, state), do: broadcast_update(state)
def handle_event(:player_joined, state), do: broadcast_update(state)
def handle_event(:game_over, state), do: broadcast_update(state)

def handle_event(_, state), do: {:ok, state}

defp broadcast_update(state) do
LobbyChannel.broadcast_current_games

{:ok, state}
end
end

0 comments on commit 28349c7

Please sign in to comment.