Commit | Line | Data |
---|---|---|
67f57217 SK |
1 | type direction = |
2 | N | NE | E | SE | S | SW | W | NW | |
3 | ||
4 | ||
5 | let directions = | |
6 | [N; NE; E; SE; S; SW; W; NW] | |
7 | ||
8 | ||
d91a53d5 SK |
9 | let char_dead = ' ' |
10 | let char_alive = 'o' | |
11 | ||
12 | ||
13 | let char_of_state = function | |
14 | | 0 -> char_dead | |
15 | | 1 -> char_alive | |
16 | | _ -> assert false | |
17 | ||
18 | ||
67f57217 SK |
19 | let offset = function |
20 | (* direction -> x, y *) | |
21 | | N -> 0, -1 | |
22 | | NE -> 1, -1 | |
23 | | E -> 1, 0 | |
24 | | SE -> 1, 1 | |
25 | | S -> 0, 1 | |
26 | | SW -> -1, 1 | |
27 | | W -> -1, 0 | |
28 | | NW -> -1, -1 | |
29 | ||
30 | ||
31 | (* Hack to sleep less than 1 sec *) | |
32 | let minisleep subsec = | |
33 | ignore (Unix.select [] [] [] subsec) | |
34 | ||
35 | ||
36 | let init_board x y = | |
3ccae1a8 | 37 | Array.map (Array.map (fun _ -> Random.int 2)) (Array.make_matrix y x 0) |
67f57217 SK |
38 | |
39 | ||
40 | let print_board board = | |
d91a53d5 SK |
41 | Array.iter |
42 | (fun row -> | |
43 | Array.iter | |
44 | (fun state -> print_char (char_of_state state)) | |
45 | row; | |
46 | print_newline () | |
47 | ) | |
48 | board | |
67f57217 SK |
49 | |
50 | ||
51 | let new_state = function | |
52 | | 1, live_neighbors when live_neighbors < 2 -> 0 | |
53 | | 1, live_neighbors when live_neighbors < 4 -> 1 | |
54 | | 1, live_neighbors when live_neighbors > 3 -> 0 | |
55 | | 0, live_neighbors when live_neighbors = 3 -> 1 | |
56 | | state, _ -> state | |
57 | ||
58 | ||
59 | let filter_offsides width height neighbors = | |
60 | List.filter | |
61 | (fun (x, y) -> x >= 0 && y >= 0 && x < width && y < height) | |
62 | neighbors | |
63 | ||
64 | ||
65 | let new_generation board = | |
66 | let height = Array.length board | |
67 | and width = Array.length board.(0) in | |
68 | Array.mapi | |
69 | ( | |
70 | fun i_y row -> | |
71 | Array.mapi | |
72 | (fun i_x state-> | |
73 | let neighbors = | |
74 | List.map | |
75 | (fun d -> | |
76 | let off_x, off_y = offset d in | |
77 | (i_x + off_x), (i_y + off_y) | |
78 | ) | |
79 | directions | |
80 | in | |
81 | let neighbors = filter_offsides width height neighbors in | |
82 | let states = List.map (fun (x, y) -> board.(y).(x)) neighbors in | |
83 | let live_neighbors = List.fold_left (+) 0 states in | |
84 | let state = new_state (state, live_neighbors) in | |
85 | state | |
86 | ) | |
87 | row | |
88 | ) | |
89 | board | |
90 | ||
91 | ||
92 | let rec life_loop board = | |
93 | print_board board; | |
94 | print_newline (); | |
95 | minisleep 0.1; | |
96 | life_loop (new_generation board) | |
97 | ||
98 | ||
3ccae1a8 SK |
99 | let main argv = |
100 | let x = int_of_string argv.(1) | |
101 | and y = int_of_string argv.(2) | |
102 | in | |
103 | ||
67f57217 SK |
104 | Random.init (int_of_float (Unix.time ())); |
105 | ||
106 | life_loop (init_board x y) | |
107 | ||
108 | ||
3ccae1a8 | 109 | let () = main Sys.argv |