-
Notifications
You must be signed in to change notification settings - Fork 1
/
lp.ml
2233 lines (1952 loc) · 75.9 KB
/
lp.ml
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(*** lambda punter ***)
(* ignore SIGPIPE signals *)
module Signal = struct
let sigpipe_handler = Lwt_unix.on_signal Sys.sigpipe (fun _sig -> prerr_endline @@ "SIGPIPE")
end
module Default = struct
(* Default map:
*
* Build this base map
0--1--2
| / \ |
|/ \|
7 3
|\ /|
| \ / |
6--5--4
and discrete shadows of it for each punter (no rivers)
...........
. .
. 0 1 2 .
. .
. .
. 7 3 .
. .
. .
. 6 5 4 .
. .
...........
*)
let map =
"{\"sites\":[{\"id\":0, \"x\": -1.0, \"y\": 1.0}, {\"id\":1, \"x\": 0.0, \"y\": 1.0}, \
{\"id\":2, \"x\": 1.0, \"y\": 1.0}, {\"id\":3, \"x\": 1.0, \"y\": 0.0}, \
{\"id\":4, \"x\": 1.0, \"y\": -1.0}, {\"id\":5, \"x\": 0.0, \"y\": -1.0}, \
{\"id\":6, \"x\": -1.0, \"y\": -1.0}, {\"id\":7, \"x\":-1.0, \"y\": 0.0}],\
\"rivers\":[{\"source\": 0, \"target\": 1}, {\"source\": 1, \"target\": 2}, \
{\"source\": 2, \"target\": 3}, {\"source\": 3, \"target\": 4}, \
{\"source\": 4, \"target\": 5}, {\"source\": 5, \"target\": 6}, \
{\"source\": 6, \"target\": 7}, {\"source\": 7, \"target\": 0}, \
{\"source\": 1, \"target\": 3}, {\"source\": 3, \"target\": 5}, \
{\"source\": 5, \"target\": 7}, {\"source\": 7, \"target\": 1}],\
\"mines\":[1,5]}"
end
module Settings = struct
let map = ref Default.map
let map_path = ref None
let num_punters = ref 2
let setup_timeout = ref 10.0
let handshake_timeout = ref 10.0
let move_timeout = ref 1.0
let max_timeouts = ref 10
let address = ref "127.0.0.1"
let port = ref 9999
let log_file = ref ""
let logging_level = ref 1
let coordinates = ref false
let eager = ref false
let offline = ref false
let punter_file = ref None
let progs = ref ["eager-futures-splurges-options"; "eager-futures-splurges-options"]
(* extensions *)
let splurges = ref false
let options = ref false
let futures = ref false
(* round of the contest *)
let round = ref None
end
module Loader : sig
end = struct
open Arg
open Printf
let arg_specs = align [
("--map", String (fun s -> Settings.map_path := Some s), " Read in the graph from a JSON graph file");
("--punters", Set_int Settings.num_punters, " Number of punters (default 2)");
("--setup-timeout", Set_float Settings.setup_timeout, " Setup timeout (default 10.0)");
("--handshake-timeout", Set_float Settings.handshake_timeout, " Handshake timeout (default 10.0)");
("--move-timeout", Set_float Settings.move_timeout, " Move timeout (default 1.0)");
("--max-timeouts", Set_int Settings.max_timeouts, " Maximum number of timeouts (default 10)");
("--address", Set_string Settings.address, " IP address");
("--port", Set_int Settings.port, " Port");
("--offline", Set Settings.offline, " Run an offline game");
("--punter-file", String (fun s -> Settings.punter_file := Some s), " A file containing a list of punters to run in offline mode");
("--coordinates", Set Settings.coordinates, " Graphs have coordinate data");
("--splurges", Set Settings.splurges, " Enable splurges");
("--options", Set Settings.options, " Enable options");
("--futures", Set Settings.futures, " Enable futures");
("--eager", Set Settings.eager, " Run as an eager client");
("--log-level", Set_int Settings.logging_level, " Logging level (values: 0 to 2) (default: 1)");
("--log", Set_string Settings.log_file, " Log file");
("--round", String (fun s -> Settings.round := Some s), " Contest round");
]
let _ = Arg.parse arg_specs ignore "Options:"
let read_file_lines path : string list =
let ic =
begin
try open_in path
with Sys_error(err) ->
printf "Error reading file (%s)\n" err;
exit (-1)
end in
let rec read_file_inner ic lines =
begin
try
let line = input_line ic in
read_file_inner ic (line :: lines)
with End_of_file ->
close_in_noerr ic;
List.rev lines
end in
(* Obtain input context, read each line *)
read_file_inner ic []
let read_file path = read_file_lines path |> String.concat "\n"
let _ =
match !Settings.map_path with
| Some p ->
printf "Reading map from file %s\n" p;
Settings.map := read_file p
| None -> ()
let _ =
if not !Settings.eager && !Settings.offline then
match !Settings.punter_file with
| None -> ()
| Some filename ->
printf "Reading punter list from file %s\n" filename;
Settings.progs := read_file_lines filename;
Settings.num_punters := List.length (!Settings.progs)
end
module Log = struct
let logger = ref !Lwt_log.default
let init () =
let set_level level =
ignore(if level > 0 then Lwt_log.add_rule "*" Lwt_log.Info);
ignore(if level > 1 then Lwt_log.add_rule "*" Lwt_log.Debug) in
set_level !Settings.logging_level;
let open Lwt in
if !Settings.log_file <> "" then
Lwt_log.file !Settings.log_file () >>= fun l ->
logger := l;
return ()
else
return ()
(* always displays: log level 0 *)
let info msg = Lwt_log.notice ~logger:!logger msg
(* log level 1 *)
let json msg = Lwt_log.info ~logger:!logger ("JSON:"^(Yojson.Safe.to_string msg))
(* log level 2 *)
let debug msg = Lwt_log.debug ~logger:!logger (Lazy.force msg)
let warning msg = Lwt_log.warning ~logger:!logger msg
let error msg = Lwt_log.error ~logger:!logger msg
end
module Util = struct
(* choose one entry from a hash table *)
let hash_table_choose (type a) (type b) (table : (a, b) Hashtbl.t) =
let exception Pair of (a * b) in
try
Hashtbl.iter (fun k v -> raise @@ Pair (k, v)) table;
raise Not_found
with
Pair (k, v) -> (k, v)
end
open Util
open Graph
(* undirected graphs with integer vertices *)
module Vertex = struct
type t = int
let compare = Pervasives.compare
let equal = (=)
let hash = Hashtbl.hash
end
module G = Imperative.Graph.Concrete (Vertex)
(* shortest paths *)
module Weight = struct
type edge = G.edge
type t = int
let weight edge = 1
let compare = Pervasives.compare
let add = (+)
let sub = (-)
let zero = 0
end
module Dijkstra = Path.Dijkstra (G) (Weight)
module Game = struct
type punter = int
type site = int
type river = int * int
type punter_resources = {credit:int; options:int}
(* Active credit - a punter that can claim up to credit rivers
Zombie - a punter that has been disconnected and can no longer move *)
type punter_status = Active of punter_resources | Zombie
type move = Claim of (punter * river) (* Claim (p, r) p claims river r *)
| Pass of punter (* Pass p p passes *)
| Splurge of (punter * site list) (* Splurge (p, sites) p splurges rivers connecting sites *)
| Option of (punter * river) (* Option (p, r) p buys option in river r *)
(* first punter is the owner; second punter has bought an option *)
type river_state = (punter * punter option) option
type futures = (site, site option) Hashtbl.t
exception IllegalMove of string
exception IllegalFuture of string
let string_of_river (i, j) = "(" ^ string_of_int i ^ ", " ^ string_of_int j^ ")"
let punter_of_move =
function
| Claim (p, _)
| Pass p
| Option (p, _)
| Splurge (p, _) -> p
let punter_prefix p =
if !Settings.offline then
"Punter " ^ string_of_int p ^ " ("^List.nth !Settings.progs p^")"
else
"Punter "^string_of_int p
let string_of_claim ?short:(short=false) (p, river) =
if short then
"Claim("^string_of_int p^", "^string_of_river river^")"
else
punter_prefix p^" claims "^string_of_river river
let string_of_pass ?short:(short=false) p =
if short then
"Pass("^string_of_int p^")"
else
punter_prefix p^" passes"
let string_of_splurge ?short:(short=false) (p, sites) =
if short then
"Splurge("^string_of_int p^", [" ^ String.concat ", " (List.map string_of_int sites) ^ "])"
else
punter_prefix p^" splurges "^"[" ^ String.concat ", " (List.map string_of_int sites) ^ "]"
let string_of_option ?short:(short=false) (p, river) =
if short then
"Option("^string_of_int p^", "^string_of_river river^")"
else
punter_prefix p^" buys option for "^string_of_river river
let string_of_move ?short:(short=false) =
function
| Claim c -> string_of_claim ~short:short c
| Pass p -> string_of_pass ~short:short p
| Option o -> string_of_option ~short:short o
| Splurge s -> string_of_splurge ~short:short s
type game_settings = {splurges:bool; options:bool; futures:bool}
let string_of_settings =
fun {futures; splurges; options} ->
let opt b s =
if b then [s]
else [] in
"{" ^ (String.concat
", "
(List.concat [opt futures "futures"; opt splurges "splurges"; opt options "options"])) ^ "}"
(* for use by clients *)
let apply_settings {splurges=splurges; options=options; futures=futures} =
(* each setting is only enabled if both the server and the client
is willing to handle it *)
begin
Settings.splurges := !Settings.splurges && splurges;
Settings.options := !Settings.options && options;
Settings.futures := !Settings.futures && futures
end
let read_settings () =
{splurges = !Settings.splurges; options = !Settings.options; futures = !Settings.futures}
(* game state *)
type t = {num_punters: int;
(* static base graph *)
base: G.t;
mines: int list;
coordinates: (site, (float * float)) Hashtbl.t;
(* dynamic graphs *)
punter_graphs: G.t array;
network: (river, river_state) Hashtbl.t;
free_rivers: (river, unit) Hashtbl.t;
(* other dynamic game state *)
status: punter_status array;
num_moves: int ref;
(* game settings *)
settings: game_settings;
(* futures *)
futures: futures array}
let extract_resource p game =
match game.status.(p) with
| Active res -> res
| Zombie -> {credit = 0; options = 0}
let update_resource p game res =
match game.status.(p) with
| Active _res -> game.status.(p) <- Active res
| Zombie -> ()
let extract_resources game =
Array.to_list
(Array.init game.num_punters (fun p -> extract_resource p game))
let update_resources game resources =
List.iteri
(fun p res -> update_resource p game res)
resources
let norm_river (source, target) =
if source < target then
(source, target)
else
(target, source)
let find_network_river game river =
Hashtbl.find game.network (norm_river river)
let add_network_river game river =
Hashtbl.add game.network (norm_river river)
let replace_network_river game river =
Hashtbl.replace game.network (norm_river river)
let find_free_river game river =
Hashtbl.find game.free_rivers (norm_river river)
(* assumes river exists *)
let is_free_river game river =
match find_network_river game river with
| None -> true
| Some _ -> false
let add_free_river game river =
Hashtbl.add game.free_rivers (norm_river river)
let replace_free_river game river =
Hashtbl.replace game.free_rivers (norm_river river)
let size game = G.nb_edges game.base
let finished game = !(game.num_moves) = size game
let first_round game = !(game.num_moves) < game.num_punters
let valid_punter game p = 0 <= p && p < game.num_punters
let empty_futures mines =
let futures = Hashtbl.create (List.length mines) in
List.iter (fun mine -> Hashtbl.add futures mine None) mines;
futures
let check_future game source target =
if not (List.mem source game.mines) then
raise @@ IllegalFuture ("Source "^ string_of_int source ^ " is not a mine");
if List.mem target game.mines then
raise @@ IllegalFuture ("Target "^ string_of_int source ^ " is a mine");
if not (G.mem_vertex game.base target) then
raise @@ IllegalFuture ("Target "^ string_of_int source ^ " is not a site")
let check_river_available game river =
match find_network_river game river with
| None -> ()
| Some (p, _) -> raise @@ IllegalMove ("Illegal claim: punter " ^ string_of_int p ^
" already owns " ^ string_of_river river)
| exception Not_found -> raise @@ IllegalMove ("Illegal claim: no river " ^ string_of_river river)
let check_river_owner p game river =
match find_network_river game river with
| None -> raise @@ IllegalMove ("Illegal option: nobody owns river " ^ string_of_river river)
| Some (q, None) when p = q -> raise @@ IllegalMove ("Illegal option: punter " ^ string_of_int p ^
" already owns " ^ string_of_river river);
| Some (q, None) -> q
| Some (_, Some p) -> raise @@ IllegalMove ("Illegal option: punter " ^ string_of_int p ^
" already has an option on " ^ string_of_river river)
| exception Not_found -> raise @@ IllegalMove ("Illegal option: no river " ^ string_of_river river)
let check_splurge p game sites options : move list =
let grabbed = Hashtbl.create ((List.length sites)-1) in
let rec splurge s sites options =
match sites with
| [] -> []
| t :: sites ->
let river = norm_river (s, t) in
if Hashtbl.mem grabbed river then
raise @@ IllegalMove (punter_prefix p^
" attempting to splurge the same river twice: " ^
string_of_river river);
Hashtbl.add grabbed river ();
begin
try
check_river_available game river;
Claim (p, (s, t)) :: splurge t sites options
with
| IllegalMove msg ->
begin
if options > 0 then
let _q = check_river_owner p game river in
Option (p, (s, t)) :: splurge t sites (options-1)
else
raise (IllegalMove msg)
end
end in
match sites with
| [] -> raise @@ IllegalMove (punter_prefix p^
" attempting an malformed splurge: " ^
"[]")
| [s] -> raise @@ IllegalMove (punter_prefix p^
" attempting an malformed splurge: " ^
"[" ^ string_of_int s ^ "]")
| s :: sites ->
begin
try
splurge s sites options
with
| IllegalMove msg ->
raise @@ IllegalMove (punter_prefix p^
" attempting an illegal splurge\n" ^ msg)
end
let apply_claim game (p, river) =
let res = extract_resource p game in
let (i, j) as river = norm_river river in
(* prerr_endline ("Applying claim: ("^string_of_int p^", "^string_of_river river^")"); *)
Hashtbl.replace game.network river (Some (p, None));
Hashtbl.remove game.free_rivers river;
G.add_edge game.punter_graphs.(p) i j;
update_resource p game {res with credit = res.credit - 1}
let apply_option game p q river =
let res = extract_resource p game in
let (i, j) as river = norm_river river in
(* prerr_endline ("Applying option: ("^string_of_int p^", "^string_of_river river^")"); *)
Hashtbl.replace game.network river (Some (q, Some p));
G.add_edge game.punter_graphs.(p) i j;
update_resource p game {credit = res.credit - 1; options = res.options - 1}
(* add one credit *)
let incr_credit p game =
let res = extract_resource p game in
update_resource p game {res with credit = res.credit + 1}
(* pass punter p *)
let pass game p = ()
(* claim river (i, j) for punter p *)
let claim game (p, (i, j)) =
match game.status.(p) with
| Zombie -> ()
| Active res ->
if not (valid_punter game p) then
raise @@ IllegalMove (punter_prefix p ^ " is invalid");
let river = if i <= j then (i, j) else (j, i) in
check_river_available game river;
apply_claim game (p, river)
(* option on river (i, j) for punter p *)
let option game (p, (i, j)) =
match game.status.(p) with
| Zombie -> ()
| Active res ->
if not game.settings.options then
raise @@ IllegalMove ("Options not enabled");
if not (valid_punter game p) then
raise @@ IllegalMove (punter_prefix p^" is invalid");
let options = res.options in
if options <= 0 then
raise @@ IllegalMove (punter_prefix p^" has bought all available options");
let river = if i <= j then (i, j) else (j, i) in
let q = check_river_owner p game river in
apply_option game p q river
(* splurge the list of rivers given by sites for p *)
let splurge game p sites =
match game.status.(p) with
| Zombie -> ()
| Active res ->
let max = res.credit in
if not game.settings.splurges then
raise @@ IllegalMove ("Splurges not enabled");
if not (valid_punter game p) then
raise @@ IllegalMove (punter_prefix p^" is invalid");
let n = (List.length sites) - 1 in
if n > max then
raise @@ IllegalMove (punter_prefix p ^
" attempted to claim " ^ string_of_int n ^
" rivers (max: "^ string_of_int max ^ ")")
else
let moves = check_splurge p game sites (res.options) in
List.iter
(function
| Claim c ->
apply_claim game c
| Option (p, river) ->
let q = check_river_owner p game river in
apply_option game p q river
| Pass _
| Splurge _ -> assert false)
moves
let make_move game move =
incr_credit (punter_of_move move) game;
match move with
| Claim c -> claim game c
| Pass p -> pass game p
| Splurge (p, sites) -> splurge game p sites
| Option c -> option game c
end
open Game
module Json = struct
type json = Yojson.Safe.json
open Yojson.Safe.Util
exception MalformedMap of string * string
exception MalformedMode of string * string
exception MalformedMove of string * string
exception MalformedState of string * string
exception MalformedServerMessage of json
let json_to_string json = Yojson.Safe.to_string json
let from_string s = Yojson.Safe.from_string s
let num_to_float =
function
| `Int i -> float_of_int i
| `Float f -> f
| _ -> failwith "Not a number"
(* join two association lists *)
let join xs ys =
match xs, ys with
| `Assoc xs, `Assoc ys -> `Assoc (xs @ ys)
| _ -> assert false
(* Maps *)
(* input a map as an initial game state *)
let input_map game_settings num_punters map =
let base = G.create () in
let coordinates = Hashtbl.create 8192 in
let punter_graphs = Array.init num_punters (fun _p -> G.create ()) in
let network = Hashtbl.create 8192 in
let free_rivers = Hashtbl.create 8192 in
let add_edge i j =
let i, j = if i < j then i, j else j, i in
G.add_edge base i j;
Hashtbl.replace network (i, j) None;
Hashtbl.replace free_rivers (i, j) () in
try
let sites = map |> member "sites" |> to_list in
List.iter
(fun site ->
let i = site |> member "id" |> to_int in
G.add_vertex base (G.V.create i);
for j = 0 to num_punters-1 do
G.add_vertex punter_graphs.(j) (G.V.create i)
done;
(* coordinates *)
if !(Settings.coordinates) then
let x = num_to_float (site |> member "x") in
let y = num_to_float (site |> member "y") in
Hashtbl.add coordinates i (x, y))
sites;
let rivers = map |> member "rivers" |> to_list in
List.iter
(fun edge ->
let i = edge |> member "source" |> to_int in
let j = edge |> member "target" |> to_int in
add_edge i j)
rivers;
(* if there are mines then read them in *)
let mines =
match map |> member "mines" with
| `Null -> raise @@ MalformedMap(json_to_string map, "Map has no mines")
| json_mines ->
List.map
(fun mine -> mine |> to_int)
(json_mines |> to_list) in
let options =
if !Settings.options then
List.length mines
else
0 in
let status =
Array.init
num_punters
(fun _p -> Active {credit = 0; options = options}) in
let futures =
Array.init
num_punters
(fun _ -> Game.empty_futures mines) in
{ num_punters = num_punters;
base = base;
mines = mines;
coordinates = coordinates;
punter_graphs = punter_graphs;
network = network;
free_rivers = free_rivers;
status = status;
num_moves = ref 0;
settings = game_settings;
futures = futures }
with
| Yojson.Json_error(msg) -> raise @@ MalformedMap(json_to_string map, msg)
| _ -> raise @@ MalformedMap(json_to_string map, "")
let output_map game =
let g = game.base in
let sites =
if !(Settings.coordinates) then
G.fold_vertex
(fun i sites ->
let (x, y) = Hashtbl.find game.coordinates i in
`Assoc [("id", `Int i); ("x", `Float x); ("y", `Float y)] :: sites)
g []
else
G.fold_vertex (fun i sites -> `Assoc [("id", `Int i)] :: sites) game.base [] in
let rivers = G.fold_edges (fun j i rivers -> `Assoc [("source", `Int i); ("target", `Int j)] :: rivers) g [] in
`Assoc [("sites", `List sites);
("rivers", `List rivers);
("mines", `List (List.map (fun i -> `Int i) game.mines))]
(* Settings *)
let input_settings s =
let get_bool_setting s name =
match s |> member name with
| `Bool b -> b
| _ -> false in
match s |> member "settings" with
| `Null -> {splurges=false; options=false; futures=false}
| s ->
let splurges = get_bool_setting s "splurges" in
let options = get_bool_setting s "options" in
let futures = get_bool_setting s "futures" in
{splurges=splurges; options=options; futures=futures}
let output_settings settings =
let add_setting b name settings =
if b then
(name, `Bool true) :: settings
else
settings in
let settings =
add_setting settings.splurges "splurges"
(add_setting settings.options "options"
(add_setting settings.futures "futures" [])) in
`Assoc [("settings", `Assoc settings)]
(* Game state *)
let input_game_state s =
let p = s |> member "punter" |> to_int in
let n = s |> member "punters" |> to_int in
let map = s |> member "map" in
let settings = input_settings s in
(p, n, map, settings)
let output_game_state p n map (settings : Game.game_settings) =
if not settings.futures && not settings.splurges && not settings.options then
(* if there are no extensions then omit the settings field*)
(`Assoc [("punter", `Int p);
("punters", `Int n);
("map", map)])
else
join
(`Assoc [("punter", `Int p);
("punters", `Int n);
("map", map)])
(output_settings settings)
(* Splurging goals *)
let input_goal goal =
match goal |> member "goal" |> to_string with
| "splurging" -> `Splurging
| "saving" -> `Saving
| _ -> assert false
let output_goal =
function
| `Splurging -> `Assoc [("goal", `String "splurging")]
| `Saving -> `Assoc [("goal", `String "saving")]
(* State *)
let input_state m =
try
m |> member "state"
with
| Yojson.Json_error(msg) -> raise @@ MalformedState(json_to_string m, msg)
| _ -> raise @@ MalformedState(json_to_string m, "")
let output_state state = `Assoc [("state", state)]
let with_state json state =
match json with
| `Assoc xs ->
`Assoc (("state", state) :: xs)
| _ -> assert false
let without_state json =
match json with
| `Assoc xs ->
`Assoc (List.filter (fun (label, value) -> label <> "state") xs)
| _ -> json
(* Claim *)
let rec input_claim claim =
let claim = claim |> member "claim" in
let p = claim |> member "punter" |> to_int in
let i = claim |> member "source" |> to_int in
let j = claim |> member "target" |> to_int in
(p, (i, j))
let output_claim (p, (i, j)) =
`Assoc [("punter", `Int p);
("source", `Int i);
("target", `Int j)]
(* Move *)
let input_move m =
try
match m |> member "claim" with
| `Null ->
begin
match m |> member "pass" with
| `Null ->
begin
match m |> member "splurge" with
| `Null ->
begin
match m |> member "option" with
| `Null ->
raise @@ MalformedMove (json_to_string m, "Unknown kind of move")
| m ->
(* if running as a client then be prepared to
accept any kind of move *)
if !Settings.eager || !Settings.options then
let p = m |> member "punter" |> to_int in
let i = m |> member "source" |> to_int in
let j = m |> member "target" |> to_int in
Option (p, (i, j))
else
raise @@ MalformedMove (json_to_string m, "Splurges disabled")
end
| m ->
(* if running as a client then be prepared to
accept any kind of move *)
if !Settings.eager || !Settings.splurges then
let p = m |> member "punter" |> to_int in
let claims = m |> member "route" |> to_list in
Splurge (p, List.map to_int claims)
else
raise @@ MalformedMove (json_to_string m, "Splurges disabled")
end
| m ->
let p = m |> member "punter" |> to_int in
Pass p
end
| m ->
let p = m |> member "punter" |> to_int in
let i = m |> member "source" |> to_int in
let j = m |> member "target" |> to_int in
Claim (p, (i, j))
with
| Yojson.Json_error(msg) -> raise @@ MalformedMove(json_to_string m, msg)
| MalformedMove(_, _) as e -> raise e
| _ -> raise @@ MalformedMove(json_to_string m, "")
let output_move move =
match move with
| Claim claim ->
`Assoc [("claim", output_claim claim)]
| Pass p ->
(`Assoc [("pass",
`Assoc [("punter", `Int p)])])
| Splurge (p, sites) ->
`Assoc [("splurge",
`Assoc [("punter", `Int p);
("route",
`List (List.map (fun s -> `Int s) sites))])]
| Option claim ->
`Assoc [("option", output_claim claim)]
(* Moves *)
let input_moves ms =
let moves = ms |> member "moves" |> to_list in
List.map input_move moves
let output_moves moves =
`Assoc [("moves", `List (List.map output_move moves))]
(* Timeout *)
(* as specified in the protocol *)
let output_timeout t =
`Assoc [("timeout", `Float t)]
(* for logging *)
let output_punter_timeout p =
`Assoc [("timeout", `Assoc [("punter", `Int p)])]
(* Move request *)
let input_move_request r =
input_moves (r |> member "move")
let output_move_request moves =
`Assoc [("move", output_moves moves)]
(* Score *)
let input_score s =
let p = s |> member "punter" |> to_int in
let score = s |> member "score" |> to_int in
(p, score)
let output_score p score =
if !Settings.offline then
`Assoc [("punter", `Int p); ("score", `Int score); ("team", `String (List.nth !Settings.progs p))]
else
`Assoc [("punter", `Int p); ("score", `Int score)]
(* Scores *)
let input_scores s =
let ss = s |> member "scores" |> to_list in
List.map input_score ss
let output_scores scores =
let scores = Array.to_list scores in
`Assoc [("scores", `List (List.mapi output_score scores))]
(* Future scores *)
let output_future_scores future_scores =
let future_scores = Array.to_list future_scores in
`Assoc [("futures",
`List (List.mapi
(fun p xs ->
`Assoc [("punter", `Int p);
("scores", `List (List.map (fun (m, s) -> `Assoc [("mine", `Int m); ("score", `Int s)]) xs))])
future_scores))]
(* Stop *)
let input_stop s =
let s = s |> member "stop" in
let moves = input_moves s in
let scores = input_scores s in
(moves, scores)
let output_stop moves scores =
`Assoc [("stop", join (output_moves (Array.to_list moves)) (output_scores scores))]
(* Move request or stop *)
let input_move_request_or_stop x =
match x |> member "move" with
| `Null -> `Stop (input_stop x)
| _ -> `Move (input_move_request x)
(* Server message *)
let input_server_message_type msg =
match msg |> member "punter" with
| `Null ->
begin
match msg |> member "move" with
| `Null ->
begin
match msg |> member "stop" with
| `Null ->
raise @@ MalformedServerMessage((msg : json))
| _ -> `Stop
end
| _ -> `Move
end
| _ -> `Setup
(* Create a game from a map *)
let create_game game_settings num_punters map =
try
input_map game_settings num_punters map
with
MalformedMap(json, msg) ->
prerr_endline ("Fatal error: malformed map (" ^ msg ^ ")");
prerr_endline ("json: "^json);
exit (-1)
(* Me *)
let input_me me =
me |> member "me" |> to_string
let output_me name =
`Assoc [("me", `String name)]
(* You *)
let input_you you =
you |> member "you" |> to_string
let output_you name =
`Assoc [("you", `String name)]
(* Ready *)
let input_ready ready =
ready |> member "ready" |> to_int
let output_ready p =
`Assoc [("ready", `Int p)]
(* Future *)
let input_future future =
let source = future |> member "source" |> to_int in
let target = future |> member "target" |> to_int in
(source, target)
let output_future (source, target) =
`Assoc [("source", `Int source); ("target", `Int target)]
(* Futures *)
let input_futures futures =
let futures =
match futures |> member "futures" with
| `Null -> []
| futures -> futures |> to_list in
List.map input_future futures
let output_futures futures =
`Assoc [("futures", `List (List.map output_future futures))]
(* Punter status *)
let output_punter_status p =
function
| Active {credit; options} ->
let credit = if !Settings.splurges then [("credit", `Int credit)] else [] in
let options = if !Settings.options then [("options", `Int options)] else [] in
`Assoc ([("punter", `Int p); ("active", `Bool true)] @ credit @ options)
| Zombie ->
`Assoc [("punter", `Int p); ("active", `Bool false)]
let output_punter_statuses status =
`Assoc [("statuses", `List (List.mapi output_punter_status (Array.to_list status)))]
(* Zombie *)
let output_zombie p =
`Assoc [("zombie", `Assoc [("punter", `Int p)])]
(* Gameplay *)
let output_gameplay =
function
| `Start ->
`Assoc [("gameplay", `String "start")]
| `Stop ->
`Assoc [("gameplay", `String "stop")]
end
type json = Json.json
module Score : sig
type data = (int * int Dijkstra.H.t) list
val calc_total : data -> Game.futures -> G.t -> int
val calc_scores : data -> Game.futures array -> G.t array -> (int * (int * int) list) array
val report_scores : (int * (int * int) list) array -> unit Lwt.t
end = struct
type data = (int * int Dijkstra.H.t) list
(* Scoring:
1) Compute all pairs of connected sites in the punter graph.
(Currently we do this at the end by computing the strongly connected
components. We could instead compute the connected pairs
incrementally, but it isn't clear whether doing so would be more
efficient.)
2) To score a punter: take the sum of all the scores for all mines