-
Notifications
You must be signed in to change notification settings - Fork 14
/
Referee.java
1324 lines (1121 loc) · 46 KB
/
Referee.java
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
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Referee extends MultiReferee {
private static final int LEAGUE_LEVEL = 3;
private static final int MAP_WIDTH = 23;
private static final int MAP_HEIGHT = 21;
private static final int COOLDOWN_CANNON = 2;
private static final int COOLDOWN_MINE = 5;
private static final int INITIAL_SHIP_HEALTH = 100;
private static final int MAX_SHIP_HEALTH = 100;
private static final int MAX_SHIP_SPEED;
private static final int MIN_SHIPS = 1;
private static final int MAX_SHIPS;
private static final int MIN_MINES;
private static final int MAX_MINES;
private static final int MIN_RUM_BARRELS = 10;
private static final int MAX_RUM_BARRELS = 26;
private static final int MIN_RUM_BARREL_VALUE = 10;
private static final int MAX_RUM_BARREL_VALUE = 20;
private static final int REWARD_RUM_BARREL_VALUE = 30;
private static final int MINE_VISIBILITY_RANGE = 5;
private static final int FIRE_DISTANCE_MAX = 10;
private static final int LOW_DAMAGE = 25;
private static final int HIGH_DAMAGE = 50;
private static final int MINE_DAMAGE = 25;
private static final int NEAR_MINE_DAMAGE = 10;
private static final boolean CANNONS_ENABLED;
private static final boolean MINES_ENABLED;
static {
switch (LEAGUE_LEVEL) {
case 0: // 1 ship / no mines / speed 1
MAX_SHIPS = 1;
CANNONS_ENABLED = false;
MINES_ENABLED = false;
MIN_MINES = 0;
MAX_MINES = 0;
MAX_SHIP_SPEED = 1;
break;
case 1: // add mines
MAX_SHIPS = 1;
CANNONS_ENABLED = true;
MINES_ENABLED = true;
MIN_MINES = 5;
MAX_MINES = 10;
MAX_SHIP_SPEED = 1;
break;
case 2: // 3 ships max
MAX_SHIPS = 3;
CANNONS_ENABLED = true;
MINES_ENABLED = true;
MIN_MINES = 5;
MAX_MINES = 10;
MAX_SHIP_SPEED = 1;
break;
default: // increase max speed
MAX_SHIPS = 3;
CANNONS_ENABLED = true;
MINES_ENABLED = true;
MIN_MINES = 5;
MAX_MINES = 10;
MAX_SHIP_SPEED = 2;
break;
}
}
private static final Pattern PLAYER_INPUT_MOVE_PATTERN = Pattern.compile("MOVE (?<x>-?[0-9]{1,8})\\s+(?<y>-?[0-9]{1,8})(?:\\s+(?<message>.+))?",
Pattern.CASE_INSENSITIVE);
private static final Pattern PLAYER_INPUT_SLOWER_PATTERN = Pattern.compile("SLOWER(?:\\s+(?<message>.+))?", Pattern.CASE_INSENSITIVE);
private static final Pattern PLAYER_INPUT_FASTER_PATTERN = Pattern.compile("FASTER(?:\\s+(?<message>.+))?", Pattern.CASE_INSENSITIVE);
private static final Pattern PLAYER_INPUT_WAIT_PATTERN = Pattern.compile("WAIT(?:\\s+(?<message>.+))?", Pattern.CASE_INSENSITIVE);
private static final Pattern PLAYER_INPUT_PORT_PATTERN = Pattern.compile("PORT(?:\\s+(?<message>.+))?", Pattern.CASE_INSENSITIVE);
private static final Pattern PLAYER_INPUT_STARBOARD_PATTERN = Pattern.compile("STARBOARD(?:\\s+(?<message>.+))?", Pattern.CASE_INSENSITIVE);
private static final Pattern PLAYER_INPUT_FIRE_PATTERN = Pattern.compile("FIRE (?<x>-?[0-9]{1,8})\\s+(?<y>-?[0-9]{1,8})(?:\\s+(?<message>.+))?",
Pattern.CASE_INSENSITIVE);
private static final Pattern PLAYER_INPUT_MINE_PATTERN = Pattern.compile("MINE(?:\\s+(?<message>.+))?", Pattern.CASE_INSENSITIVE);
public static int clamp(int val, int min, int max) {
return Math.max(min, Math.min(max, val));
}
public static long parseProperty(Properties prop, String key, long defaultValue) {
try {
return Long.valueOf(prop.getProperty(key));
} catch (NumberFormatException e) {
// Ignore invalid data
}
return defaultValue;
}
@SafeVarargs
static final <T> String join(T... v) {
return Stream.of(v).map(String::valueOf).collect(Collectors.joining(" "));
}
public static class Coord {
private final static int[][] DIRECTIONS_EVEN = new int[][] { { 1, 0 }, { 0, -1 }, { -1, -1 }, { -1, 0 }, { -1, 1 }, { 0, 1 } };
private final static int[][] DIRECTIONS_ODD = new int[][] { { 1, 0 }, { 1, -1 }, { 0, -1 }, { -1, 0 }, { 0, 1 }, { 1, 1 } };
private final int x;
private final int y;
public Coord(int x, int y) {
this.x = x;
this.y = y;
}
public Coord(Coord other) {
this.x = other.x;
this.y = other.y;
}
public double angle(Coord targetPosition) {
double dy = (targetPosition.y - this.y) * Math.sqrt(3) / 2;
double dx = targetPosition.x - this.x + ((this.y - targetPosition.y) & 1) * 0.5;
double angle = -Math.atan2(dy, dx) * 3 / Math.PI;
if (angle < 0) {
angle += 6;
} else if (angle >= 6) {
angle -= 6;
}
return angle;
}
CubeCoordinate toCubeCoordinate() {
int xp = x - (y - (y & 1)) / 2;
int zp = y;
int yp = -(xp + zp);
return new CubeCoordinate(xp, yp, zp);
}
Coord neighbor(int orientation) {
int newY, newX;
if (this.y % 2 == 1) {
newY = this.y + DIRECTIONS_ODD[orientation][1];
newX = this.x + DIRECTIONS_ODD[orientation][0];
} else {
newY = this.y + DIRECTIONS_EVEN[orientation][1];
newX = this.x + DIRECTIONS_EVEN[orientation][0];
}
return new Coord(newX, newY);
}
boolean isInsideMap() {
return x >= 0 && x < MAP_WIDTH && y >= 0 && y < MAP_HEIGHT;
}
int distanceTo(Coord dst) {
return this.toCubeCoordinate().distanceTo(dst.toCubeCoordinate());
}
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Coord other = (Coord) obj;
return y == other.y && x == other.x;
}
@Override
public String toString() {
return join(x, y);
}
}
public static class CubeCoordinate {
static int[][] directions = new int[][] { { 1, -1, 0 }, { +1, 0, -1 }, { 0, +1, -1 }, { -1, +1, 0 }, { -1, 0, +1 }, { 0, -1, +1 } };
int x, y, z;
public CubeCoordinate(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
Coord toOffsetCoordinate() {
int newX = x + (z - (z & 1)) / 2;
int newY = z;
return new Coord(newX, newY);
}
CubeCoordinate neighbor(int orientation) {
int nx = this.x + directions[orientation][0];
int ny = this.y + directions[orientation][1];
int nz = this.z + directions[orientation][2];
return new CubeCoordinate(nx, ny, nz);
}
int distanceTo(CubeCoordinate dst) {
return (Math.abs(x - dst.x) + Math.abs(y - dst.y) + Math.abs(z - dst.z)) / 2;
}
@Override
public String toString() {
return join(x, y, z);
}
}
private static enum EntityType {
SHIP, BARREL, MINE, CANNONBALL
}
public static abstract class Entity {
private static int UNIQUE_ENTITY_ID = 0;
protected final int id;
protected final EntityType type;
protected Coord position;
public Entity(EntityType type, int x, int y) {
this.id = UNIQUE_ENTITY_ID++;
this.type = type;
this.position = new Coord(x, y);
}
public String toViewString() {
return join(id, position.y, position.x);
}
protected String toPlayerString(int arg1, int arg2, int arg3, int arg4) {
return join(id, type.name(), position.x, position.y, arg1, arg2, arg3, arg4);
}
}
public static class Mine extends Entity {
public Mine(int x, int y) {
super(EntityType.MINE, x, y);
}
public String toPlayerString(int playerIdx) {
return toPlayerString(0, 0, 0, 0);
}
public List<Damage> explode(List<Ship> ships, boolean force) {
List<Damage> damage = new ArrayList<>();
Ship victim = null;
for (Ship ship : ships) {
if (position.equals(ship.bow()) || position.equals(ship.stern()) || position.equals(ship.position)) {
damage.add(new Damage(this.position, MINE_DAMAGE, true));
ship.damage(MINE_DAMAGE);
victim = ship;
}
}
if (force || victim != null) {
if (victim == null) {
damage.add(new Damage(this.position, MINE_DAMAGE, true));
}
for (Ship ship : ships) {
if (ship != victim) {
Coord impactPosition = null;
if (ship.stern().distanceTo(position) <= 1) {
impactPosition = ship.stern();
}
if (ship.bow().distanceTo(position) <= 1) {
impactPosition = ship.bow();
}
if (ship.position.distanceTo(position) <= 1) {
impactPosition = ship.position;
}
if (impactPosition != null) {
ship.damage(NEAR_MINE_DAMAGE);
damage.add(new Damage(impactPosition, NEAR_MINE_DAMAGE, true));
}
}
}
}
return damage;
}
}
public static class Cannonball extends Entity {
final int ownerEntityId;
final int srcX;
final int srcY;
final int initialRemainingTurns;
int remainingTurns;
public Cannonball(int row, int col, int ownerEntityId, int srcX, int srcY, int remainingTurns) {
super(EntityType.CANNONBALL, row, col);
this.ownerEntityId = ownerEntityId;
this.srcX = srcX;
this.srcY = srcY;
this.initialRemainingTurns = this.remainingTurns = remainingTurns;
}
public String toViewString() {
return join(id, position.y, position.x, srcY, srcX, initialRemainingTurns, remainingTurns, ownerEntityId);
}
public String toPlayerString(int playerIdx) {
return toPlayerString(ownerEntityId, remainingTurns, 0, 0);
}
}
public static class RumBarrel extends Entity {
private int health;
public RumBarrel(int x, int y, int health) {
super(EntityType.BARREL, x, y);
this.health = health;
}
public String toViewString() {
return join(id, position.y, position.x, health);
}
public String toPlayerString(int playerIdx) {
return toPlayerString(health, 0, 0, 0);
}
}
public static class Damage {
private final Coord position;
private final int health;
private final boolean hit;
public Damage(Coord position, int health, boolean hit) {
this.position = position;
this.health = health;
this.hit = hit;
}
public String toViewString() {
return join(position.y, position.x, health, (hit ? 1 : 0));
}
}
public static enum Action {
FASTER, SLOWER, PORT, STARBOARD, FIRE, MINE
}
public static class Ship extends Entity {
int orientation;
int speed;
int health;
int initialHealth;
int owner;
String message;
Action action;
int mineCooldown;
int cannonCooldown;
Coord target;
public int newOrientation;
public Coord newPosition;
public Coord newBowCoordinate;
public Coord newSternCoordinate;
public Ship(int x, int y, int orientation, int owner) {
super(EntityType.SHIP, x, y);
this.orientation = orientation;
this.speed = 0;
this.health = INITIAL_SHIP_HEALTH;
this.owner = owner;
}
public String toViewString() {
return join(id, position.y, position.x, orientation, health, speed, (action != null ? action : "WAIT"), bow().y, bow().x, stern().y,
stern().x, " ;" + (message != null ? message : ""));
}
public String toPlayerString(int playerIdx) {
return toPlayerString(orientation, speed, health, owner == playerIdx ? 1 : 0);
}
public void setMessage(String message) {
if (message != null && message.length() > 50) {
message = message.substring(0, 50) + "...";
}
this.message = message;
}
public void moveTo(int x, int y) {
Coord currentPosition = this.position;
Coord targetPosition = new Coord(x, y);
if (currentPosition.equals(targetPosition)) {
this.action = Action.SLOWER;
return;
}
double targetAngle, angleStraight, anglePort, angleStarboard, centerAngle, anglePortCenter, angleStarboardCenter;
switch (speed) {
case 2:
this.action = Action.SLOWER;
break;
case 1:
// Suppose we've moved first
currentPosition = currentPosition.neighbor(orientation);
if (!currentPosition.isInsideMap()) {
this.action = Action.SLOWER;
break;
}
// Target reached at next turn
if (currentPosition.equals(targetPosition)) {
this.action = null;
break;
}
// For each neighbor cell, find the closest to target
targetAngle = currentPosition.angle(targetPosition);
angleStraight = Math.min(Math.abs(orientation - targetAngle), 6 - Math.abs(orientation - targetAngle));
anglePort = Math.min(Math.abs((orientation + 1) - targetAngle), Math.abs((orientation - 5) - targetAngle));
angleStarboard = Math.min(Math.abs((orientation + 5) - targetAngle), Math.abs((orientation - 1) - targetAngle));
centerAngle = currentPosition.angle(new Coord(MAP_WIDTH / 2, MAP_HEIGHT / 2));
anglePortCenter = Math.min(Math.abs((orientation + 1) - centerAngle), Math.abs((orientation - 5) - centerAngle));
angleStarboardCenter = Math.min(Math.abs((orientation + 5) - centerAngle), Math.abs((orientation - 1) - centerAngle));
// Next to target with bad angle, slow down then rotate (avoid to turn around the target!)
if (currentPosition.distanceTo(targetPosition) == 1 && angleStraight > 1.5) {
this.action = Action.SLOWER;
break;
}
Integer distanceMin = null;
// Test forward
Coord nextPosition = currentPosition.neighbor(orientation);
if (nextPosition.isInsideMap()) {
distanceMin = nextPosition.distanceTo(targetPosition);
this.action = null;
}
// Test port
nextPosition = currentPosition.neighbor((orientation + 1) % 6);
if (nextPosition.isInsideMap()) {
int distance = nextPosition.distanceTo(targetPosition);
if (distanceMin == null || distance < distanceMin || distance == distanceMin && anglePort < angleStraight - 0.5) {
distanceMin = distance;
this.action = Action.PORT;
}
}
// Test starboard
nextPosition = currentPosition.neighbor((orientation + 5) % 6);
if (nextPosition.isInsideMap()) {
int distance = nextPosition.distanceTo(targetPosition);
if (distanceMin == null || distance < distanceMin
|| (distance == distanceMin && angleStarboard < anglePort - 0.5 && this.action == Action.PORT)
|| (distance == distanceMin && angleStarboard < angleStraight - 0.5 && this.action == null)
|| (distance == distanceMin && this.action == Action.PORT && angleStarboard == anglePort
&& angleStarboardCenter < anglePortCenter)
|| (distance == distanceMin && this.action == Action.PORT && angleStarboard == anglePort
&& angleStarboardCenter == anglePortCenter && (orientation == 1 || orientation == 4))) {
distanceMin = distance;
this.action = Action.STARBOARD;
}
}
break;
case 0:
// Rotate ship towards target
targetAngle = currentPosition.angle(targetPosition);
angleStraight = Math.min(Math.abs(orientation - targetAngle), 6 - Math.abs(orientation - targetAngle));
anglePort = Math.min(Math.abs((orientation + 1) - targetAngle), Math.abs((orientation - 5) - targetAngle));
angleStarboard = Math.min(Math.abs((orientation + 5) - targetAngle), Math.abs((orientation - 1) - targetAngle));
centerAngle = currentPosition.angle(new Coord(MAP_WIDTH / 2, MAP_HEIGHT / 2));
anglePortCenter = Math.min(Math.abs((orientation + 1) - centerAngle), Math.abs((orientation - 5) - centerAngle));
angleStarboardCenter = Math.min(Math.abs((orientation + 5) - centerAngle), Math.abs((orientation - 1) - centerAngle));
Coord forwardPosition = currentPosition.neighbor(orientation);
this.action = null;
if (anglePort <= angleStarboard) {
this.action = Action.PORT;
}
if (angleStarboard < anglePort || angleStarboard == anglePort && angleStarboardCenter < anglePortCenter
|| angleStarboard == anglePort && angleStarboardCenter == anglePortCenter && (orientation == 1 || orientation == 4)) {
this.action = Action.STARBOARD;
}
if (forwardPosition.isInsideMap() && angleStraight <= anglePort && angleStraight <= angleStarboard) {
this.action = Action.FASTER;
}
break;
}
}
public void faster() {
this.action = Action.FASTER;
}
public void slower() {
this.action = Action.SLOWER;
}
public void port() {
this.action = Action.PORT;
}
public void starboard() {
this.action = Action.STARBOARD;
}
public void placeMine() {
if (MINES_ENABLED) {
this.action = Action.MINE;
}
}
public Coord stern() {
return position.neighbor((orientation + 3) % 6);
}
public Coord bow() {
return position.neighbor(orientation);
}
public Coord newStern() {
return position.neighbor((newOrientation + 3) % 6);
}
public Coord newBow() {
return position.neighbor(newOrientation);
}
public boolean at(Coord coord) {
Coord stern = stern();
Coord bow = bow();
return stern != null && stern.equals(coord) || bow != null && bow.equals(coord) || position.equals(coord);
}
public boolean newBowIntersect(Ship other) {
return newBowCoordinate != null && (newBowCoordinate.equals(other.newBowCoordinate) || newBowCoordinate.equals(other.newPosition)
|| newBowCoordinate.equals(other.newSternCoordinate));
}
public boolean newBowIntersect(List<Ship> ships) {
for (Ship other : ships) {
if (this != other && newBowIntersect(other)) {
return true;
}
}
return false;
}
public boolean newPositionsIntersect(Ship other) {
boolean sternCollision = newSternCoordinate != null && (newSternCoordinate.equals(other.newBowCoordinate)
|| newSternCoordinate.equals(other.newPosition) || newSternCoordinate.equals(other.newSternCoordinate));
boolean centerCollision = newPosition != null && (newPosition.equals(other.newBowCoordinate) || newPosition.equals(other.newPosition)
|| newPosition.equals(other.newSternCoordinate));
return newBowIntersect(other) || sternCollision || centerCollision;
}
public boolean newPositionsIntersect(List<Ship> ships) {
for (Ship other : ships) {
if (this != other && newPositionsIntersect(other)) {
return true;
}
}
return false;
}
public void damage(int health) {
this.health -= health;
if (this.health <= 0) {
this.health = 0;
}
}
public void heal(int health) {
this.health += health;
if (this.health > MAX_SHIP_HEALTH) {
this.health = MAX_SHIP_HEALTH;
}
}
public void fire(int x, int y) {
if (CANNONS_ENABLED) {
Coord target = new Coord(x, y);
this.target = target;
this.action = Action.FIRE;
}
}
}
private static class Player {
private int id;
private List<Ship> ships;
private List<Ship> shipsAlive;
public Player(int id) {
this.id = id;
this.ships = new ArrayList<>();
this.shipsAlive = new ArrayList<>();
}
public void setDead() {
for (Ship ship : ships) {
ship.health = 0;
}
}
public int getScore() {
int score = 0;
for (Ship ship : ships) {
score += ship.health;
}
return score;
}
public List<String> toViewString() {
List<String> data = new ArrayList<>();
data.add(String.valueOf(this.id));
for (Ship ship : ships) {
data.add(ship.toViewString());
}
return data;
}
}
private long seed;
private List<Cannonball> cannonballs;
private List<Mine> mines;
private List<RumBarrel> barrels;
private List<Player> players;
private List<Ship> ships;
private List<Damage> damage;
private List<Coord> cannonBallExplosions;
private int shipsPerPlayer;
private int mineCount;
private int barrelCount;
private Random random;
public Referee(InputStream is, PrintStream out, PrintStream err) throws IOException {
super(is, out, err);
}
public static void main(String... args) throws IOException {
new Referee(System.in, System.out, System.err);
}
@Override
protected void initReferee(int playerCount, Properties prop) throws InvalidFormatException {
seed = parseProperty(prop, "seed", new Random(System.currentTimeMillis()).nextLong());
random = new Random(this.seed);
shipsPerPlayer = clamp((int) parseProperty(prop, "shipsPerPlayer", random.nextInt(1 + MAX_SHIPS - MIN_SHIPS) + MIN_SHIPS), MIN_SHIPS,
MAX_SHIPS);
if (MAX_MINES > MIN_MINES) {
mineCount = clamp((int) parseProperty(prop, "mineCount", random.nextInt(MAX_MINES - MIN_MINES) + MIN_MINES), MIN_MINES, MAX_MINES);
} else {
mineCount = MIN_MINES;
}
barrelCount = clamp((int) parseProperty(prop, "barrelCount", random.nextInt(MAX_RUM_BARRELS - MIN_RUM_BARRELS) + MIN_RUM_BARRELS),
MIN_RUM_BARRELS, MAX_RUM_BARRELS);
cannonballs = new ArrayList<>();
cannonBallExplosions = new ArrayList<>();
damage = new ArrayList<>();
// Generate Players
this.players = new ArrayList<Player>(playerCount);
for (int i = 0; i < playerCount; i++) {
this.players.add(new Player(i));
}
// Generate Ships
for (int j = 0; j < shipsPerPlayer; j++) {
int xMin = 1 + j * MAP_WIDTH / shipsPerPlayer;
int xMax = (j + 1) * MAP_WIDTH / shipsPerPlayer - 2;
int y = 1 + random.nextInt(MAP_HEIGHT / 2 - 2);
int x = xMin + random.nextInt(1 + xMax - xMin);
int orientation = random.nextInt(6);
Ship ship0 = new Ship(x, y, orientation, 0);
Ship ship1 = new Ship(x, MAP_HEIGHT - 1 - y, (6 - orientation) % 6, 1);
this.players.get(0).ships.add(ship0);
this.players.get(1).ships.add(ship1);
this.players.get(0).shipsAlive.add(ship0);
this.players.get(1).shipsAlive.add(ship1);
}
this.ships = players.stream().map(p -> p.ships).flatMap(List::stream).collect(Collectors.toList());
// Generate mines
mines = new ArrayList<>();
while (mines.size() < mineCount) {
int x = 1 + random.nextInt(MAP_WIDTH - 2);
int y = 1 + random.nextInt(MAP_HEIGHT / 2);
Mine m = new Mine(x, y);
boolean cellIsFreeOfMines = mines.stream().noneMatch(mine -> mine.position.equals(m.position));
boolean cellIsFreeOfShips = ships.stream().noneMatch(ship -> ship.at(m.position));
if (cellIsFreeOfShips && cellIsFreeOfMines) {
if (y != MAP_HEIGHT - 1 - y) {
mines.add(new Mine(x, MAP_HEIGHT - 1 - y));
}
mines.add(m);
}
}
mineCount = mines.size();
// Generate supplies
barrels = new ArrayList<>();
while (barrels.size() < barrelCount) {
int x = 1 + random.nextInt(MAP_WIDTH - 2);
int y = 1 + random.nextInt(MAP_HEIGHT / 2);
int h = MIN_RUM_BARREL_VALUE + random.nextInt(1 + MAX_RUM_BARREL_VALUE - MIN_RUM_BARREL_VALUE);
RumBarrel m = new RumBarrel(x, y, h);
boolean cellIsFreeOfBarrels = barrels.stream().noneMatch(barrel -> barrel.position.equals(m.position));
boolean cellIsFreeOfMines = mines.stream().noneMatch(mine -> mine.position.equals(m.position));
boolean cellIsFreeOfShips = ships.stream().noneMatch(ship -> ship.at(m.position));
if (cellIsFreeOfShips && cellIsFreeOfMines && cellIsFreeOfBarrels) {
if (y != MAP_HEIGHT - 1 - y) {
barrels.add(new RumBarrel(x, MAP_HEIGHT - 1 - y, h));
}
barrels.add(m);
}
}
barrelCount = barrels.size();
}
@Override
protected Properties getConfiguration() {
Properties prop = new Properties();
prop.setProperty("seed", String.valueOf(seed));
prop.setProperty("shipsPerPlayer", String.valueOf(shipsPerPlayer));
prop.setProperty("barrelCount", String.valueOf(barrelCount));
prop.setProperty("mineCount", String.valueOf(mineCount));
return prop;
}
@Override
protected void prepare(int round) {
for (Player player : players) {
for (Ship ship : player.ships) {
ship.action = null;
ship.message = null;
}
}
cannonBallExplosions.clear();
damage.clear();
}
@Override
protected int getExpectedOutputLineCountForPlayer(int playerIdx) {
return this.players.get(playerIdx).shipsAlive.size();
}
@Override
protected void handlePlayerOutput(int frame, int round, int playerIdx, String[] outputs)
throws WinException, LostException, InvalidInputException {
Player player = this.players.get(playerIdx);
try {
int i = 0;
for (String line : outputs) {
Matcher matchWait = PLAYER_INPUT_WAIT_PATTERN.matcher(line);
Matcher matchMove = PLAYER_INPUT_MOVE_PATTERN.matcher(line);
Matcher matchFaster = PLAYER_INPUT_FASTER_PATTERN.matcher(line);
Matcher matchSlower = PLAYER_INPUT_SLOWER_PATTERN.matcher(line);
Matcher matchPort = PLAYER_INPUT_PORT_PATTERN.matcher(line);
Matcher matchStarboard = PLAYER_INPUT_STARBOARD_PATTERN.matcher(line);
Matcher matchFire = PLAYER_INPUT_FIRE_PATTERN.matcher(line);
Matcher matchMine = PLAYER_INPUT_MINE_PATTERN.matcher(line);
Ship ship = player.shipsAlive.get(i++);
if (matchMove.matches()) {
int x = Integer.parseInt(matchMove.group("x"));
int y = Integer.parseInt(matchMove.group("y"));
ship.setMessage(matchMove.group("message"));
ship.moveTo(x, y);
} else if (matchFaster.matches()) {
ship.setMessage(matchFaster.group("message"));
ship.faster();
} else if (matchSlower.matches()) {
ship.setMessage(matchSlower.group("message"));
ship.slower();
} else if (matchPort.matches()) {
ship.setMessage(matchPort.group("message"));
ship.port();
} else if (matchStarboard.matches()) {
ship.setMessage(matchStarboard.group("message"));
ship.starboard();
} else if (matchWait.matches()) {
ship.setMessage(matchWait.group("message"));
} else if (matchMine.matches()) {
ship.setMessage(matchMine.group("message"));
ship.placeMine();
} else if (matchFire.matches()) {
int x = Integer.parseInt(matchFire.group("x"));
int y = Integer.parseInt(matchFire.group("y"));
ship.setMessage(matchFire.group("message"));
ship.fire(x, y);
} else {
throw new InvalidInputException("A valid action", line);
}
}
} catch (InvalidInputException e) {
player.setDead();
throw e;
}
}
private void decrementRum() {
for (Ship ship : ships) {
ship.damage(1);
}
}
private void updateInitialRum() {
for (Ship ship : ships) {
ship.initialHealth = ship.health;
}
}
private void moveCannonballs() {
for (Iterator<Cannonball> it = cannonballs.iterator(); it.hasNext();) {
Cannonball ball = it.next();
if (ball.remainingTurns == 0) {
it.remove();
continue;
} else if (ball.remainingTurns > 0) {
ball.remainingTurns--;
}
if (ball.remainingTurns == 0) {
cannonBallExplosions.add(ball.position);
}
}
}
private void applyActions() {
for (Player player : players) {
for (Ship ship : player.shipsAlive) {
if (ship.mineCooldown > 0) {
ship.mineCooldown--;
}
if (ship.cannonCooldown > 0) {
ship.cannonCooldown--;
}
ship.newOrientation = ship.orientation;
if (ship.action != null) {
switch (ship.action) {
case FASTER:
if (ship.speed < MAX_SHIP_SPEED) {
ship.speed++;
}
break;
case SLOWER:
if (ship.speed > 0) {
ship.speed--;
}
break;
case PORT:
ship.newOrientation = (ship.orientation + 1) % 6;
break;
case STARBOARD:
ship.newOrientation = (ship.orientation + 5) % 6;
break;
case MINE:
if (ship.mineCooldown == 0) {
Coord target = ship.stern().neighbor((ship.orientation + 3) % 6);
if (target.isInsideMap()) {
boolean cellIsFreeOfBarrels = barrels.stream().noneMatch(barrel -> barrel.position.equals(target));
boolean cellIsFreeOfMines = mines.stream().noneMatch(mine -> mine.position.equals(target));
boolean cellIsFreeOfShips = ships.stream().filter(b -> b != ship).noneMatch(b -> b.at(target));
if (cellIsFreeOfBarrels && cellIsFreeOfShips && cellIsFreeOfMines) {
ship.mineCooldown = COOLDOWN_MINE;
Mine mine = new Mine(target.x, target.y);
mines.add(mine);
}
}
}
break;
case FIRE:
int distance = ship.bow().distanceTo(ship.target);
if (ship.target.isInsideMap() && distance <= FIRE_DISTANCE_MAX && ship.cannonCooldown == 0) {
int travelTime = (int) (1 + Math.round(ship.bow().distanceTo(ship.target) / 3.0));
cannonballs.add(new Cannonball(ship.target.x, ship.target.y, ship.id, ship.bow().x, ship.bow().y, travelTime));
ship.cannonCooldown = COOLDOWN_CANNON;
}
break;
default:
break;
}
}
}
}
}
private void checkBarrelCollisions(Ship ship) {
Coord bow = ship.bow();
Coord stern = ship.stern();
Coord center = ship.position;
for (Iterator<RumBarrel> it = barrels.iterator(); it.hasNext();) {
RumBarrel barrel = it.next();
if (barrel.position.equals(bow) || barrel.position.equals(stern) || barrel.position.equals(center)) {
ship.heal(barrel.health);
it.remove();
}
}
}
private void checkMineCollisions() {
for (Iterator<Mine> it = mines.iterator(); it.hasNext();) {
Mine mine = it.next();
List<Damage> mineDamage = mine.explode(ships, false);
if (!mineDamage.isEmpty()) {
damage.addAll(mineDamage);
it.remove();
}
}
}
private void checkCollisions() {
// Check collisions with Barrels
for (Ship ship : this.ships) {
checkBarrelCollisions(ship);
}
// Check collisions with Mines
checkMineCollisions();
}
private void moveShips() {
// ---
// Go forward
// ---
for (int i = 1; i <= MAX_SHIP_SPEED; i++) {
for (Player player : players) {
for (Ship ship : player.shipsAlive) {
ship.newPosition = ship.position;
ship.newBowCoordinate = ship.bow();
ship.newSternCoordinate = ship.stern();
if (i > ship.speed) {
continue;
}
Coord newCoordinate = ship.position.neighbor(ship.orientation);
if (newCoordinate.isInsideMap()) {
// Set new coordinate.
ship.newPosition = newCoordinate;
ship.newBowCoordinate = newCoordinate.neighbor(ship.orientation);
ship.newSternCoordinate = newCoordinate.neighbor((ship.orientation + 3) % 6);
} else {
// Stop ship!
ship.speed = 0;
}
}
}
// Check ship and obstacles collisions
List<Ship> collisions = new ArrayList<>();
boolean collisionDetected = true;