Son aktivite 13 hours ago

Revizyon 408bac1569691541770adb63bfffb25968f72047

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