Current section
Files
Jump to
Current section
Files
lib/ant_swarm.ex
# AntSwarm.add_ant(AntSwarm)
# AntSwarm.total_food_count(AntSwarm)
defmodule AntSwarm do
use GenServer
# Client API
def start_link(name) do
GenServer.start_link(__MODULE__, :ok, name: name)
end
def add_ant(server) do
GenServer.cast(server, {:add_ant})
end
def total_food_count(server) do
GenServer.call(server, {:total_food_count})
end
# Server API
def init(:ok) do
{:ok, []}
end
# def handle_cast({:find_food, quantity}, state) do
# hunt_duration = 1000 + :rand.uniform(5000)
# Process.send_after(self(), {:update_food, quantity}, hunt_duration)
# {:noreply, state}
# end
def handle_cast({:add_ant}, state) do
{:ok, ant} = Ant.Supervisor.spawn_ant
Task.async(fn -> Ant.find_food(ant) end)
new_state = state ++ [ant]
{:noreply, new_state}
end
def handle_call({:total_food_count}, _from, state) do
total_food_count = Enum.sum(Enum.map(state, fn ant -> Ant.show_food(ant) end))
{:reply, total_food_count, state}
end
# def handle_info({:update_food, quantity}, state) do
# {:noreply, state + quantity}
# end
end