2 -behaviour(gen_server).
20 -define(INTERVAL, 100). % In milliseconds
22 -define(CHAR_DEAD, 32). % Space
23 -define(CHAR_ALIVE, 111). % o
24 -define(CHAR_BAR, 45). % -
27 -record(state, {x :: integer()
29 ,cells :: list(atom())
30 ,num_cells :: integer()
31 ,state_pairs :: list(tuple(integer(), integer())) | []
32 ,replies_pending :: integer()
33 ,generation = 0 :: integer()
37 %% ============================================================================
39 %% ============================================================================
41 start_link(X, Y, Cells) ->
42 ServerName = {local, ?MODULE},
45 gen_server:start_link(ServerName, ?MODULE, Args, Opts).
48 tock(CellID, CellState) ->
49 gen_server:cast(?MODULE, {tock, {CellID, CellState}}).
52 %% ============================================================================
54 %% ============================================================================
56 init([X, Y, Cells]) ->
60 ,num_cells=length(Cells)
68 terminate(_Reason, State) ->
72 code_change(_Old, State, _Other) ->
76 handle_call(_Msg, _From, State) ->
80 handle_cast(next_tick,
84 ,generation=Generation
87 NewGeneration = Generation + 1,
88 ok = cast_all(Cells, {tick, NewGeneration}),
89 {noreply, State#state{replies_pending=NumCells, generation=NewGeneration}};
91 handle_cast({tock, {ID, CellState}},
94 ,state_pairs=StatePairs
95 ,replies_pending=RepliesPending
96 ,generation=Generation
100 NewStatePairs = [{ID, CellState} | StatePairs],
101 NewRepliesPending = RepliesPending - 1,
102 NewState = State#state{replies_pending=NewRepliesPending},
104 case NewRepliesPending of
106 SortedStatePairs = lists:sort(
107 fun({A, _}, {B, _}) -> A < B end,
110 StateChars = [state_to_char(S) || {_, S} <- SortedStatePairs],
113 "X: ~b Y: ~b CELLS: ~b GENERATION: ~b~n",
114 [X, Y, NumCells, Generation]
116 ok = do_print_bar(X),
118 ok = do_print_state_chars(X, StateChars),
120 ok = timer:sleep(?INTERVAL),
121 schedule_next_tick(),
122 {noreply, NewState#state{state_pairs=[]}};
125 {noreply, NewState#state{state_pairs=NewStatePairs}}
128 handle_cast(_Msg, State) ->
132 handle_info(_Msg, State) ->
136 %% ============================================================================
138 %% ============================================================================
140 schedule_next_tick() ->
141 gen_server:cast(?MODULE, next_tick).
144 cast_all([], _) -> ok;
145 cast_all([Server | Servers], Msg) ->
146 ok = gen_server:cast(Server, Msg),
147 cast_all(Servers, Msg).
150 state_to_char(0) -> ?CHAR_DEAD;
151 state_to_char(1) -> ?CHAR_ALIVE.
154 do_print_state_chars(_, []) -> ok;
155 do_print_state_chars(X, Chars) ->
156 {XChars, RestChars} = lists:split(X, Chars),
157 ok = io:format([XChars, $\n]),
158 do_print_state_chars(X, RestChars).
162 io:format("~s~n", [[?CHAR_BAR || _ <- lists:seq(1, X - 1)]]).