6 -define(CHAR_DEAD, 32). % " "
7 -define(CHAR_ALIVE, 111). % "o"
8 -define(INTERVAL, 100).
11 %% ============================================================================
13 %% ============================================================================
16 [X, Y] = [atom_to_integer(A) || A <- Args],
17 Board = init_board(X, Y),
18 life_loop(X, Y, Board).
21 %% ============================================================================
23 %% ============================================================================
25 life_loop(X, Y, Board) ->
26 ok = do_print_board(Board),
27 timer:sleep(?INTERVAL),
28 life_loop(X, Y, next_generation(X, Y, Board)).
31 do_print_board(Board) ->
32 CharLists = array:to_list(
50 ok = io:format("~s~n", [CharList])
56 state_to_char(0) -> ?CHAR_DEAD;
57 state_to_char(1) -> ?CHAR_ALIVE.
60 next_generation(W, H, Board) ->
65 Neighbors = filter_offsides(H, W, neighbors(X, Y)),
66 States = neighbor_states(Board, Neighbors),
67 LiveNeighbors = lists:sum(States),
68 new_state(State, LiveNeighbors)
77 new_state(1, LiveNeighbors) when LiveNeighbors < 2 -> 0;
78 new_state(1, LiveNeighbors) when LiveNeighbors < 4 -> 1;
79 new_state(1, LiveNeighbors) when LiveNeighbors > 3 -> 0;
80 new_state(0, LiveNeighbors) when LiveNeighbors =:= 3 -> 1;
81 new_state(State, _LiveNeighbors) -> State.
84 neighbor_states(Board, Neighbors) ->
85 [array:get(X, array:get(Y, Board)) || {X, Y} <- Neighbors].
88 filter_offsides(H, W, Coordinates) ->
89 [{X, Y} || {X, Y} <- Coordinates, is_onside(X, Y, H, W)].
92 is_onside(X, Y, H, W) when (X >= 0) and (Y >= 0) and (X < W) and (Y < H) -> true;
93 is_onside(_, _, _, _) -> false.
97 [{X + OffX, Y + OffY} || {OffX, OffY} <- offsets()].
101 [offset(D) || D <- directions()].
104 offset('N') -> { 0, -1};
105 offset('NE') -> { 1, -1};
106 offset('E') -> { 1, 0};
107 offset('SE') -> { 1, 1};
108 offset('S') -> { 0, 1};
109 offset('SW') -> {-1, 1};
110 offset('W') -> {-1, 0};
111 offset('NW') -> {-1, -1}.
115 ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'].
119 array:map(fun(_, _) -> init_row(X) end, array:new(Y)).
123 array:map(fun(_, _) -> init_cell_state() end, array:new(X)).
127 crypto:rand_uniform(0, 2).
130 atom_to_integer(Atom) ->
131 list_to_integer(atom_to_list(Atom)).