All pastes #1224360 Raw Edit

ant_sim.erl

public text v1 · immutable
#1224360 ·published 2008-10-10 06:32 UTC
rendered paste body
-module(ant_sim).

ant_loop(P, WithFood, W_pid) ->
	Candidates = [ahead(P), ahead_left(P), ahead_right(P)],
	ant_retry_loop(Candidates, WithFood, W_pid),
	receive after 40 -> ok end,
	ant_loop(P1, WithFood1, W_pid).

ant_retry_loop(Candidates, WithFood, W_pid) ->
	W_pid ! {self(), info, Candidates},
	% receive FPA {Food, Pheromone, Ant} info of all candidates

	% pick target cell P1 based on score
	% correspondingly, we should have FPA1 and WithFood1

	W_pid ! {self(), move, P, P1, FPA1},
	receive
		ok -> {P1, WithFood1};
		_  -> ant_retry_loop(Candidates, WithFood, W_pid)
	end.

ahead({X0, Y0, Dir}) ->
	X1 = list:nth(Dir, [X, X+1, X+1, X+1, X, X-1, X-1, X-1]),
	Y1 = list:nth(Dir, [Y-1, Y-1, Y, Y+1, Y+1, Y+1, Y, Y-1]),
	{X1 rem 80, Y1 rem 80, Dir}.

ahead_left({X, Y, Dir}) ->
	ahead({X, Y, Dir-1 rem 8}).

ahead_right({X, Y, Dir}) ->
	ahead({X, Y, Dir+1 rem 8}).

world_loop(State) ->
	receive
		{Pid, info, Ps} ->
			Pid ! [current(State, P) || P <- Ps],
			world_loop(State);
		{Pid, move, P0, P1, FPA1} ->
			case current(State, P1) of
			FPA1 ->
				% make the move by constructing State1
				Pid ! ok,
				world_loop(State1);
			_ ->
				Pid ! no,
				world_loop(State)
			end
	end.