X-Git-Url: https://git.xandkar.net/?a=blobdiff_plain;f=001%2Fsrc%2Ftime.erl;h=d93321582ea6d2269d7edb2b8abdcddf9c6558a4;hb=172421cbe00ddf82a0b92fcb04bd73b4b14e2338;hp=d7109262f8be543632e37a58f61b8eca563c7fe8;hpb=d2a0e2f9319260ac266296451915776f3399fb70;p=cellular-automata.git diff --git a/001/src/time.erl b/001/src/time.erl index d710926..d933215 100644 --- a/001/src/time.erl +++ b/001/src/time.erl @@ -4,7 +4,7 @@ %% API -export([start_link/2 - ,cast/1 + ,tock/2 ]). %% Callbacks @@ -29,6 +29,7 @@ ,num_cells :: integer() ,state_pairs :: list(tuple(integer(), integer())) | [] ,replies_pending :: integer() + ,gen_count = 0 :: integer() }). @@ -43,8 +44,8 @@ start_link(X, Cells) -> gen_server:start_link(ServerName, ?MODULE, Args, Opts). -cast(Msg) -> - gen_server:cast(?MODULE, Msg). +tock(CellID, CellState) -> + gen_server:cast(?MODULE, {tock, {CellID, CellState}}). %% ============================================================================ @@ -58,7 +59,7 @@ init([X, Cells]) -> ,state_pairs=[] ,replies_pending=0 }, - cast(next_tick), + schedule_next_tick(), {ok, State}. @@ -74,14 +75,20 @@ handle_call(_Msg, _From, State) -> {reply, ok, State}. -handle_cast(next_tick, #state{cells=Cells, num_cells=NumCells, state_pairs=[]}=State) -> - ok = send_all(Cells, tick), +handle_cast(next_tick, + #state{cells=Cells + ,num_cells=NumCells + ,state_pairs=[] + }=State) -> + + ok = cast_all(Cells, tick), {noreply, State#state{replies_pending=NumCells}}; handle_cast({tock, {ID, CellState}}, #state{x=X ,state_pairs=StatePairs ,replies_pending=RepliesPending + ,gen_count=GenCount }=State) -> NewStatePairs = [{ID, CellState} | StatePairs], @@ -90,14 +97,17 @@ handle_cast({tock, {ID, CellState}}, case NewRepliesPending of 0 -> + NewGenCount = GenCount + 1, SortedStatePairs = lists:sort(NewStatePairs), StateChars = [state_to_char(S) || {_, S} <- SortedStatePairs], ok = do_print_bar(X), + ok = io:format("GENERATIONS: ~b~n", [NewGenCount]), + ok = do_print_bar(X), ok = do_print_state_chars(X, StateChars), ok = do_print_bar(X), ok = timer:sleep(?INTERVAL), - cast(next_tick), - {noreply, NewState#state{state_pairs=[]}}; + schedule_next_tick(), + {noreply, NewState#state{state_pairs=[], gen_count=NewGenCount}}; _N -> {noreply, NewState#state{state_pairs=NewStatePairs}} @@ -115,10 +125,14 @@ handle_info(_Msg, State) -> %% Internal %% ============================================================================ -send_all([], _) -> ok; -send_all([PID | PIDs], Msg) -> - PID ! Msg, - send_all(PIDs, Msg). +schedule_next_tick() -> + gen_server:cast(?MODULE, next_tick). + + +cast_all([], _) -> ok; +cast_all([Server | Servers], Msg) -> + ok = gen_server:cast(Server, Msg), + cast_all(Servers, Msg). state_to_char(0) -> ?CHAR_DEAD;