Guest User

Untitled

a guest
Jan 14th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. type player = | Black | White
  2. type cell = | Cell of player | Empty
  3.  
  4. type board = (cell array) array
  5.  
  6. exception Invalid_position_exception of (int * int)
  7.  
  8. let opponent = function | Black -> White | White -> Black
  9.  
  10. let init_board () : board =
  11. let b = Array.init 8 (fun _ -> Array.init 8 (fun _ -> Empty))
  12. in
  13. (b.(3).(3) <- Cell White;
  14. b.(4).(4) <- Cell White;
  15. b.(4).(3) <- Cell Black;
  16. b.(3).(4) <- Cell Black;
  17. b)
  18.  
  19. let print_board (b : board) =
  20. let print_line line =
  21. (Array.iter
  22. (function
  23. | Empty -> print_char '.'
  24. | Cell White -> print_char 'O'
  25. | Cell Black -> print_char '#')
  26. line;
  27. print_newline ())
  28. in Array.iter print_line b
  29.  
  30.  
  31. let check_position (x, y) =
  32. if not ((x >= 0) && ((y < 8) && ((y >= 0) && (y < 8))))
  33. then raise (Invalid_position_exception (x, y))
  34. else ()
  35.  
  36. let find_sequence (b : board) (dx, dy) (x, y) =
  37. match b.(x).(y) with
  38. | Empty -> []
  39. | Cell player ->
  40. let rec find (x, y) accu =
  41. (try
  42. (check_position (x, y);
  43. match b.(x).(y) with
  44. | Cell p ->
  45. if p = player
  46. then accu
  47. else find ((x + dx), (y + dy)) ((x, y) :: accu)
  48. | Empty -> [])
  49. with | Invalid_position_exception e -> [])
  50. in find ((x + dx), (y + dy)) []
  51.  
  52. let find_flipped (b : board) (x, y) =
  53. let directions =
  54. [ (0, 1); (0, (-1)); ((-1), 0); (1, 0); ((-1), (-1)); (1, (-1));
  55. ((-1), 1); (1, 1) ]
  56. in
  57. List.fold_left (fun accu d -> accu @ (find_sequence b d (x, y))) []
  58. directions
  59.  
  60. let play (b : board) player (x, y) =
  61. (b.(x).(y) <- Cell player;
  62. let flipped = find_flipped b (x, y)
  63. in
  64. (List.iter (fun (x, y) -> b.(x).(y) <- Cell player) flipped;
  65. print_board b))
Add Comment
Please, Sign In to add comment