-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclientEngine.ml
More file actions
79 lines (63 loc) · 2.66 KB
/
clientEngine.ml
File metadata and controls
79 lines (63 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
open Grid
open Client
(** [print_boards game] prints the boards in [game] to the terminal *)
let print_boards game =
let top_board = game |> parse |> snd |> render false in
let bottom_board = game |> parse |> fst |> render true in
ANSITerminal.(print_string [white] top_board); print_endline "";
ANSITerminal.(print_string [white] bottom_board); print_endline ""
let main serv_port player_num =
let client = Client.make_client (serv_port + player_num) in
let c_in, c_out = Client.inchan client, Client.outchan client in
Client.make_connection client serv_port;
let connect_msg = Client.read c_in in
ANSITerminal.(print_string [green] connect_msg); print_endline "";
let init_board = Client.read c_in in
print_boards init_board;
(** [valid_prompt ()] prompts the user for input and waits for a response from
the server. Valid prompts include "shoot (A,1)", "score", and "quit".
Shoot command ends turn and displays game boards on terminal
Score command displays current score and prompts user again
Quit command ends the game for both clients and the server *)
let rec valid_prompt () =
let rec loop () =
ANSITerminal.(print_string [white] (Client.read c_in));
print_endline "";
let msg = read_line () in
Client.write c_out msg;
if msg = "score"
then (ANSITerminal.(print_string [yellow] (Client.read c_in));
print_endline "";
loop ())
else Client.read c_in in
let response = loop () in
if String.index_opt response 'C' <> Some 0
then response
else (ANSITerminal.(print_string [red] response); print_endline "";
valid_prompt ())
in
(** [move ()] is the set of instructions executed when it is this player's
turn*)
let move () =
let response = valid_prompt () in
if response = "QUIT"
then (Client.close client; Stdlib.exit 0)
else print_boards response in
(** [wait ()] is the set of instructions executed when it is the other
player's turn*)
let wait () =
ANSITerminal.(print_string [white] "The other player is moving");
print_endline "";
let response = Client.read c_in in
if response = "QUIT"
then (ANSITerminal.(print_string [white] "the other player has quit");
print_endline ""; Client.close client; Stdlib.exit 0)
else print_boards response in
(** [cycle ()] makes a player move and wait for the other player's moves
until the game is over *)
let rec cycle () =
if player_num = 1
then (move (); wait (); cycle ())
else (wait (); move (); cycle ()) in
cycle ()
let () = main (int_of_string Sys.argv.(1)) (int_of_string Sys.argv.(2))