Last active 10 hours ago

gol.ml Raw Playground
1Random.self_init ()
2
3type cell = Dead | Alive
4let cell_to_string = function
5 | Alive -> "#"
6 | Dead -> "_"
7
8let cell_to_int = function
9 | Alive -> 1
10 | Dead -> 0
11
12let random_cell = fun _ -> if Random.bool () then Dead else Alive ;;
13let random_row = fun _ -> Array.init 10 random_cell ;;
14
15let random_grid () = Array.init 10 random_row ;;
16let empty_grid () = Array.init 10 (fun _ -> Array.make 10 Dead) ;;
17
18let grid = ref (random_grid ()) ;;
19
20let show_row row =
21 for x = 0 to 9 do
22 cell_to_string row.(x) |> print_string
23 done;
24 print_newline () ;;
25
26let show_grid () =
27 for y = 0 to 9 do
28 show_row !grid.(y)
29 done
30
31let read_cell x y =
32 !grid.(y mod 10).(x mod 10) ;;
33
34let neighbors x y =
35 (read_cell (x + 9) (y + 9) |> cell_to_int)
36 + (read_cell x (y + 9) |> cell_to_int)
37 + (read_cell (x + 1) (y + 9) |> cell_to_int)
38 + (read_cell (x + 9) y |> cell_to_int)
39 + (read_cell (x + 1) y |> cell_to_int)
40 + (read_cell (x + 9) (y + 1) |> cell_to_int)
41 + (read_cell x (y + 1) |> cell_to_int)
42 + (read_cell (x + 1) (y + 1) |> cell_to_int)
43
44let next_state x y =
45 match read_cell x y, neighbors x y with
46 | (Dead, 3) -> Alive
47 | (Alive, 2) | (Alive, 3) -> Alive
48 | _ -> Dead
49
50let update_grid () =
51 let next_grid = empty_grid () in
52 for y = 0 to 9 do
53 for x = 0 to 9 do
54 next_grid.(y).(x) <- next_state x y
55 done
56 done;
57 grid := next_grid ;;
58
59while true do
60 show_grid () ;
61 print_newline () ;
62 update_grid () ;
63 let _ = read_line () in () ;
64done
65
66