Advertisement
Guest User

Untitled

a guest
May 25th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. (* Game Of Life *)
  2.  
  3. (* This program will draw Conway's Game Of Life *)
  4.  
  5. (* **** ARRAY FUNCTION **** *)
  6.  
  7. let init_board (l, c) v =
  8. let rec build_array l e = match l with
  9. | 0 -> []
  10. | _ -> e::build_array (l-1) e
  11. in build_array c (build_array l v)
  12. ;;
  13.  
  14. let set_cell v (x, y) board =
  15. let rec set_line l x = match (l, x) with
  16. | (e::l, 0) -> v::l
  17. | (e::l, x) -> e::set_line l (x-1)
  18. | _ -> l
  19. in let rec get_line arr y = match (arr, y) with
  20. | (l::arr, 0) -> (set_line l x)::arr
  21. | (l::arr, y) -> l::get_line arr (y-1)
  22. | _ -> arr
  23. in get_line board y
  24. ;;
  25.  
  26. let get_cell (x, y) board =
  27. let rec get_element l x = match (l, x) with
  28. | (e::l, 0) -> e
  29. | (e::l, x) -> get_element l (x-1)
  30. | _ -> 0
  31. in let rec get_list arr y = match (arr, y) with
  32. | (l::arr, 0) -> get_element l x
  33. | (l::arr, y) -> get_list arr (y-1)
  34. | _ -> 0
  35. in get_list board y
  36. ;;
  37.  
  38. (* **** DRAWING FUNCTIONS **** *)
  39.  
  40. let draw_cell (x, y) size color =
  41. fill_rect (x + 1, y + 1) (y + size + 1, y + size + 1) color
  42. ;;
  43.  
  44. let draw_board board size =
  45. let cell_color = function
  46. | 0 -> white
  47. | _ -> black
  48. in let rec _d board (x, y) = match (x, y) with
  49. | (0, 0) ->
  50.  
  51.  
  52.  
  53. (* **** GOL FUNCTION **** *)
  54.  
  55. let count_neighbours (x, y) board size =
  56. get_cell ((x - 1), (y - 1)) board +
  57. get_cell ((x - 1), (y)) board +
  58. get_cell ((x - 1), (y + 1)) board +
  59. get_cell ((x), (y - 1)) board +
  60. get_cell ((x), (y + 1)) board +
  61. get_cell ((x + 1), (y - 1)) board +
  62. get_cell ((x + 1), (y)) board +
  63. get_cell ((x + 1), (y + 1)) board
  64. ;;
  65.  
  66. let rule0 cell near = near = 3 || (cell = 1 && (near = 2))
  67. ;;
  68.  
  69. let rec seed_life board size nb_cell =
  70. if nb_cell = 0 then board else
  71. (let pos = (Random.int size, Random.int size) in
  72. if get_cell pos board = 0
  73. then seed_life (set_cell 1 pos board) size (nb_cell - 1)
  74. else seed_life board size nb_cell)
  75. ;;
  76.  
  77. let new_board size nb_cell =
  78. seed_life (init_board (size, size) 0) size nb_cell
  79. ;;
  80.  
  81. let next_generation board size =
  82. let rec _n x y next = match (x, y) with
  83. | (-1, -1) -> next
  84. | (_, -1) -> _n (x - 1) size next
  85. | pos when rule0 (get_cell pos board) (count_neighbours pos board size) -> _n x (y-1) (set_cell 1 pos next)
  86. | _ -> _n x (y-1) next
  87. in _n size size (init_board (size, size) 0)
  88. ;;
  89.  
  90. let rec game board size n = match n with
  91. | 0 -> ()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement