Skip to content

Instantly share code, notes, and snippets.

@Sephi-Chan
Created March 2, 2019 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sephi-Chan/bc7ba1bd1038f72fd215217531842e1f to your computer and use it in GitHub Desktop.
Save Sephi-Chan/bc7ba1bd1038f72fd215217531842e1f to your computer and use it in GitHub Desktop.
defmodule Tanks.Games do
use GenServer
def start_link([]) do
GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
end
def create(map, player_1, player_2) do
GenServer.call(__MODULE__, {:create, UUID.uuid4(), map, player_1, player_2})
end
def game_for_player(player_id) do
Enum.find(all(), fn (game) ->
game.player_1 == player_id or game.player_2 == player_id
end)
end
def all do
children = Supervisor.which_children(Tanks.GamesSupervisor)
Enum.map(children, fn ({_, pid, _, _}) ->
Tanks.Game.basic_info(pid)
end)
end
def seed() do
IO.inspect("Seed game...")
mac = "d698ce9c-7e44-45c3-c57c-8390b602fa30"
win = "cba90965-713c-494a-c9f6-cb69ab87f1ef"
{:ok, lobby_id} = Tanks.Lobbies.open(win, Tanks.Board.get(1))
{:ok, game_id} = Tanks.Lobbies.add_player(lobby_id, mac)
Tanks.Game.player_buys_unit(game_id, win, "artillery", [5,5])
Tanks.Game.player_buys_unit(game_id, win, "tank", [5,1])
Tanks.Game.player_buys_unit(game_id, win, "medium_tank", [5,2])
Tanks.Game.player_ends_turn(game_id, win)
Tanks.Game.player_buys_unit(game_id, mac, "artillery", [5,3])
Tanks.Game.player_buys_unit(game_id, mac, "medium_tank", [5,4])
Tanks.Game.player_ends_turn(game_id, mac)
end
def init(state) do
{:ok, state}
end
def handle_call({:create, game_id, map, player_1_id, player_2_id}, _from, state) do
game = %{
id: game_id,
player_1: player_1_id,
player_2: player_2_id,
map: map
}
{:ok, pid} = DynamicSupervisor.start_child(Tanks.GamesSupervisor, {Tanks.Game, game})
Process.monitor(pid)
{:reply, {:ok, game.id}, state}
end
def handle_info({:DOWN, _, _, _, _}, state) do
games = Tanks.Games.all()
IO.inspect(games)
if games == [] do
Tanks.Games.seed()
end
{:noreply, state}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment