Run all game processes in a game supervisor

This commit is contained in:
Kodi Craft 2024-08-25 21:03:09 +02:00
parent dc9a2f2b5f
commit fb2a21a546
Signed by: kodi
GPG Key ID: 69D9EED60B242822
3 changed files with 24 additions and 5 deletions

View File

@ -40,10 +40,25 @@ defmodule Amethyst.API.Game do
end
end
@spec start(Amethyst.API.Game, term()) :: no_return()
def child_spec(mod, refs) do
%{
id: __MODULE__,
start: {__MODULE__, :start_link, [mod, refs]}
}
end
@spec start(Amethyst.API.Game, term()) :: {:ok, pid}
def start(mod, refs) do
true = refs |> Enum.all?(fn {_key, pid } -> Process.link(pid) end)
loop(mod, refs)
pid = spawn(fn ->
true = refs |> Enum.all?(fn {_key, pid } -> Process.link(pid) end)
loop(mod, refs)
end)
{:ok, pid}
end
def start_link(mod, refs) do
{:ok, pid} = start(mod, refs)
Process.link(pid)
{:ok, pid}
end
defp loop(mod, refs) do
receive do

View File

@ -66,7 +66,10 @@ defmodule Amethyst.GameCoordinator do
# We should gracefully handle situations where we cannot create a game.
{:ok, refs} = type.instantiate(game_supervisor_pid)
refs = refs |> Map.put(:game_supervisor, game_supervisor_pid) |> Map.put(:task_supervisor, task_supervisor_pid)
pid = spawn(Amethyst.API.Game, :start, [type, refs])
{:ok, pid} = DynamicSupervisor.start_child(
game_supervisor_pid,
Amethyst.API.Game.child_spec(type, refs)
)
games = [{type, pid, []} | games]
{pid, games}
end

View File

@ -9,8 +9,9 @@ defmodule Example.Game do
end
@impl true
def login(from, cfg, _state) do
def login(from, cfg, refs) do
Logger.info("Player logged in from #{inspect(from)}: #{inspect(cfg)}")
Logger.info("The refs for this game are #{inspect(refs)}")
:ok
end
end