Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (* Game Of Life *)
- (* This program will draw Conway's Game Of Life *)
- (* **** ARRAY FUNCTION **** *)
- let init_board (l, c) v =
- let rec build_array l e = match l with
- | 0 -> []
- | _ -> e::build_array (l-1) e
- in build_array c (build_array l v)
- ;;
- let set_cell v (x, y) board =
- let rec set_line l x = match (l, x) with
- | (e::l, 0) -> v::l
- | (e::l, x) -> e::set_line l (x-1)
- | _ -> l
- in let rec get_line arr y = match (arr, y) with
- | (l::arr, 0) -> (set_line l x)::arr
- | (l::arr, y) -> l::get_line arr (y-1)
- | _ -> arr
- in get_line board y
- ;;
- let get_cell (x, y) board =
- let rec get_element l x = match (l, x) with
- | (e::l, 0) -> e
- | (e::l, x) -> get_element l (x-1)
- | _ -> 0
- in let rec get_list arr y = match (arr, y) with
- | (l::arr, 0) -> get_element l x
- | (l::arr, y) -> get_list arr (y-1)
- | _ -> 0
- in get_list board y
- ;;
- (* **** DRAWING FUNCTIONS **** *)
- let draw_cell (x, y) size color =
- fill_rect (x + 1, y + 1) (y + size + 1, y + size + 1) color
- ;;
- let draw_board board size =
- let cell_color = function
- | 0 -> white
- | _ -> black
- in let rec _d board (x, y) = match (x, y) with
- | (0, 0) ->
- (* **** GOL FUNCTION **** *)
- let count_neighbours (x, y) board size =
- get_cell ((x - 1), (y - 1)) board +
- get_cell ((x - 1), (y)) board +
- get_cell ((x - 1), (y + 1)) board +
- get_cell ((x), (y - 1)) board +
- get_cell ((x), (y + 1)) board +
- get_cell ((x + 1), (y - 1)) board +
- get_cell ((x + 1), (y)) board +
- get_cell ((x + 1), (y + 1)) board
- ;;
- let rule0 cell near = near = 3 || (cell = 1 && (near = 2))
- ;;
- let rec seed_life board size nb_cell =
- if nb_cell = 0 then board else
- (let pos = (Random.int size, Random.int size) in
- if get_cell pos board = 0
- then seed_life (set_cell 1 pos board) size (nb_cell - 1)
- else seed_life board size nb_cell)
- ;;
- let new_board size nb_cell =
- seed_life (init_board (size, size) 0) size nb_cell
- ;;
- let next_generation board size =
- let rec _n x y next = match (x, y) with
- | (-1, -1) -> next
- | (_, -1) -> _n (x - 1) size next
- | pos when rule0 (get_cell pos board) (count_neighbours pos board size) -> _n x (y-1) (set_cell 1 pos next)
- | _ -> _n x (y-1) next
- in _n size size (init_board (size, size) 0)
- ;;
- let rec game board size n = match n with
- | 0 -> ()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement