2 -behaviour(gen_server).
20 -define(INTERVAL, 0). % In milliseconds
22 -define(CHAR_DEAD, 32). % Space
23 -define(CHAR_ALIVE, 111). % o
24 -define(CHAR_BAR, 61). % =
27 -record(state, {x :: integer()
28 ,cells :: list(atom())
29 ,num_cells :: integer()
30 ,state_pairs :: list(tuple(integer(), integer())) | []
31 ,replies_pending :: integer()
35 %% ============================================================================
37 %% ============================================================================
39 start_link(X, Cells) ->
40 ServerName = {local, ?MODULE},
43 gen_server:start_link(ServerName, ?MODULE, Args, Opts).
47 gen_server:cast(?MODULE, Msg).
50 %% ============================================================================
52 %% ============================================================================
57 ,num_cells=length(Cells)
65 terminate(_Reason, State) ->
69 code_change(_Old, State, _Other) ->
73 handle_call(_Msg, _From, State) ->
77 handle_cast(next_tick, #state{cells=Cells, num_cells=NumCells, state_pairs=[]}=State) ->
78 ok = send_all(Cells, tick),
79 {noreply, State#state{replies_pending=NumCells}};
81 handle_cast({tock, {ID, CellState}},
83 ,state_pairs=StatePairs
84 ,replies_pending=RepliesPending
87 NewStatePairs = [{ID, CellState} | StatePairs],
88 NewRepliesPending = RepliesPending - 1,
89 NewState = State#state{replies_pending=NewRepliesPending},
91 case NewRepliesPending of
93 SortedStatePairs = lists:sort(NewStatePairs),
94 StateChars = [state_to_char(S) || {_, S} <- SortedStatePairs],
96 ok = do_print_state_chars(X, StateChars),
98 ok = timer:sleep(?INTERVAL),
100 {noreply, NewState#state{state_pairs=[]}};
103 {noreply, NewState#state{state_pairs=NewStatePairs}}
106 handle_cast(_Msg, State) ->
110 handle_info(_Msg, State) ->
114 %% ============================================================================
116 %% ============================================================================
118 send_all([], _) -> ok;
119 send_all([PID | PIDs], Msg) ->
124 state_to_char(0) -> ?CHAR_DEAD;
125 state_to_char(1) -> ?CHAR_ALIVE.
128 do_print_state_chars(_, []) -> ok;
129 do_print_state_chars(X, Chars) ->
130 {XChars, RestChars} = lists:split(X, Chars),
131 ok = io:format([XChars, $\n]),
132 do_print_state_chars(X, RestChars).
136 io:format("~s~n", [[?CHAR_BAR || _ <- lists:seq(1, X - 1)]]).