Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- type player = | Black | White
- type cell = | Cell of player | Empty
- type board = (cell array) array
- exception Invalid_position_exception of (int * int)
- let opponent = function | Black -> White | White -> Black
- let init_board () : board =
- let b = Array.init 8 (fun _ -> Array.init 8 (fun _ -> Empty))
- in
- (b.(3).(3) <- Cell White;
- b.(4).(4) <- Cell White;
- b.(4).(3) <- Cell Black;
- b.(3).(4) <- Cell Black;
- b)
- let print_board (b : board) =
- let print_line line =
- (Array.iter
- (function
- | Empty -> print_char '.'
- | Cell White -> print_char 'O'
- | Cell Black -> print_char '#')
- line;
- print_newline ())
- in Array.iter print_line b
- let check_position (x, y) =
- if not ((x >= 0) && ((y < 8) && ((y >= 0) && (y < 8))))
- then raise (Invalid_position_exception (x, y))
- else ()
- let find_sequence (b : board) (dx, dy) (x, y) =
- match b.(x).(y) with
- | Empty -> []
- | Cell player ->
- let rec find (x, y) accu =
- (try
- (check_position (x, y);
- match b.(x).(y) with
- | Cell p ->
- if p = player
- then accu
- else find ((x + dx), (y + dy)) ((x, y) :: accu)
- | Empty -> [])
- with | Invalid_position_exception e -> [])
- in find ((x + dx), (y + dy)) []
- let find_flipped (b : board) (x, y) =
- let directions =
- [ (0, 1); (0, (-1)); ((-1), 0); (1, 0); ((-1), (-1)); (1, (-1));
- ((-1), 1); (1, 1) ]
- in
- List.fold_left (fun accu d -> accu @ (find_sequence b d (x, y))) []
- directions
- let play (b : board) player (x, y) =
- (b.(x).(y) <- Cell player;
- let flipped = find_flipped b (x, y)
- in
- (List.iter (fun (x, y) -> b.(x).(y) <- Cell player) flipped;
- print_board b))
Add Comment
Please, Sign In to add comment