-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRobotPlayer.java
1601 lines (1401 loc) · 60.6 KB
/
RobotPlayer.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
package yggdrasil;
import battlecode.common.*;
/*
* Todo list
*
* Units that move out of sensor range could be followed
* Archons need to avoid edges and corners when moving
* Could broadcast good locations for gardeners
*/
public strictfp class RobotPlayer {
static final int debugLevel = 0; // 0 = off, 1 = function calls, 2 = logic, 3/4 = detailed info
static final boolean indicatorsOn = false;
static RobotController rc;
static MapLocation mapCentre;
static RobotInfo[] robots; //Cached result from senseNearbyRobots
static TreeInfo[] trees; //Cached result from senseNearbyTree
static BulletInfo[] bullets; //Cached result from senseNearbyBullets
static boolean overrideDanger = false;
static MapLocation rallyPoint = null;
/**
* run() is the method that is called when a robot is instantiated in the Battlecode world.
* If this method returns, the robot dies!
**/
@SuppressWarnings("unused")
public static void run(RobotController rc) throws GameActionException {
// This is the RobotController object. You use it to perform actions from this robot,
// and to get information on its current status.
RobotPlayer.rc = rc;
float x = 0;
float y = 0;
int count = 0;
for (MapLocation m:rc.getInitialArchonLocations(rc.getTeam())) {
x += m.x;
y += m.y;
count++;
}
for (MapLocation m:rc.getInitialArchonLocations(rc.getTeam().opponent())) {
x += m.x;
y += m.y;
count++;
}
if (count == 0)
mapCentre = new MapLocation(400,400);
else
mapCentre = new MapLocation(x/count, y/count);
// Here, we've separated the controls into a different method for each RobotType.
// You can add the missing ones or rewrite this into your own control structure.
switch (rc.getType()) {
case ARCHON:
runArchon();
break;
case GARDENER:
runGardener();
break;
case SOLDIER:
runCombat();
break;
case LUMBERJACK:
runLumberjack();
break;
case SCOUT:
runScout();
break;
case TANK:
runCombat();
break;
}
}
/*
static void setIndicator(MapLocation from, MapLocation to, int red, int green, int blue) throws GameActionException {
if (indicatorsOn)
rc.setIndicatorLine(from, to, red, green, blue);
}
static void setIndicator(MapLocation centre, int red, int green, int blue) throws GameActionException {
if (indicatorsOn)
rc.setIndicatorDot(centre, red, green, blue);
}
static void debug(int level, String str) {
if (level <= debugLevel)
System.out.println(str);
}
*/
static float unitStrength(RobotType type) {
if (type.bulletSpeed > 0)
return type.attackPower;
if (type == RobotType.LUMBERJACK)
return 1;
return 0;
}
static void sense() throws GameActionException {
robots = rc.senseNearbyRobots();
trees = rc.senseNearbyTrees();
bullets = rc.senseNearbyBullets();
overrideDanger = false;
float enemyStrength = 0;
float allyStrength = 0;
RobotInfo enemy = null;
for (RobotInfo r: robots) {
if (r.getTeam() == rc.getTeam()) {
allyStrength += unitStrength(r.getType());
} else {
if (enemy == null)
enemy = r;
enemyStrength += unitStrength(r.getType());
}
}
if (enemy != null && (allyStrength < 2 || allyStrength < enemyStrength)) {
help(enemy.getLocation());
} else {
checkHelp();
}
}
static void checkWin() throws GameActionException {
// Go for the win if we have enough bullets
int vps = rc.getTeamVictoryPoints();
float bullets = rc.getTeamBullets();
float exchangeRate = rc.getVictoryPointCost();
if (rc.getRoundNum() >= rc.getRoundLimit() -1 || (int)(bullets/exchangeRate) + vps >= GameConstants.VICTORY_POINTS_TO_WIN) {
rc.donate(bullets);
} else if (bullets > 1000 && rc.getRoundNum() > 200) { //Only donate vps later on - if we get a windfall from a tree then we want to spend the bullets early on
int newVps = (int)((bullets - 1000)/exchangeRate);
rc.donate(newVps*exchangeRate);
}
}
/*
* Broadcast data
* 0 - set to round num that we broadcast for help (or cancel help)
* 1 - 1 = goto location (at 2, 3), 0 = cancelled
* 2 = x location (int part)
* 3 = y location (int part)
*/
static void help(MapLocation here) throws GameActionException {
int round = rc.readBroadcast(0);
int rally = rc.readBroadcast(1);
if (round == rc.getRoundNum() && rally > 0) //Someone else called for help this turn
return;
rc.broadcast(0, rc.getRoundNum());
rc.broadcast(1, 1);
rc.broadcastFloat(2, here.x);
rc.broadcastFloat(3, here.y);
rallyPoint = here;
//debug(4, "Calling for help " + here);
//setIndicator(here, 0, 0, 255);
}
static void cancelHelp() throws GameActionException {
rc.broadcast(0, rc.getRoundNum());
rc.broadcast(1, 0);
rallyPoint = null;
//debug(4, "Cancelling help");
}
static void checkHelp() throws GameActionException {
int round = rc.readBroadcast(0);
int rally = rc.readBroadcast(1);
if (rally > 0) {
if (rc.getRoundNum() - round < 50) { //Current help
rallyPoint = new MapLocation(rc.readBroadcastFloat(2), rc.readBroadcastFloat(3));
if (rc.canSenseLocation(rallyPoint)) {
RobotInfo enemy = findNearestRobot(null, rc.getTeam().opponent());
if (enemy == null)
cancelHelp();
}
} else {
cancelHelp();
}
} else if (rc.getRoundNum() - round > 1) {
//See if someone has broadcast as it wasn't us!
MapLocation[] broadcast = rc.senseBroadcastingRobotLocations();
if (broadcast.length > 0)
help(broadcast[0]);
else
rallyPoint = null;
}
}
static void checkShake() throws GameActionException {
if (!rc.canShake())
return;
//Check to see if there is a tree in range that we can shake
//Head to the one with the most resources if we are a scout
TreeInfo bestTree = null;
for (TreeInfo t:trees) {
if (t.getContainedBullets() > 0) {
if (rc.canShake(t.getID()))
rc.shake(t.getID());
else if (rc.getType() == RobotType.SCOUT && (bestTree == null || t.getContainedBullets() > bestTree.getContainedBullets()))
bestTree = t;
}
}
if (bestTree != null)
tryMove(bestTree.getLocation());
}
static RobotInfo findNearestRobot(RobotType type, Team team) {
//List is ordered by distance already so return first entry in list of the correct type
for (RobotInfo r:robots) {
if ((type == null || r.getType() == type) && (team == null || r.getTeam() == team))
return r;
}
return null;
}
static boolean closeToMapEdge() throws GameActionException {
if (rc.onTheMap(rc.getLocation(), RobotType.GARDENER.sensorRadius))
return false;
return true;
}
//Check for edges of the map - too close and we don't want to build
static boolean isGoodGardenLocation() throws GameActionException {
return (!closeToMapEdge() && findNearestRobot(RobotType.GARDENER, rc.getTeam()) == null);
}
/*
* Check to see if a bullet fired from here will hit an enemy first (rather than a tree or an ally)
* If it does return the distance to the enemy or the negative distance for an ally
* or -100 for a miss or -50 for a hit on a neutral tree
*/
static float hitDistance(MapLocation loc, Direction dir) {
TreeInfo nearestTree = null;
float nearestHitTreeDist = -1;
RobotInfo nearestUnit = null;
float nearestHitUnitDist = -1;
//Check each tree to see if it will hit it
for (TreeInfo t:trees) {
nearestHitTreeDist = calcHitDist(loc, loc.add(dir, rc.getType().sensorRadius*2), t.getLocation(), t.getRadius());
if (nearestHitTreeDist >= 0) {
nearestTree = t;
break;
}
}
for (RobotInfo r:robots) {
nearestHitUnitDist = calcHitDist(loc, loc.add(dir, rc.getType().sensorRadius*2), r.getLocation(), r.getRadius());
if (nearestHitUnitDist >= 0) {
nearestUnit = r;
break;
}
}
//debug(2, "Shot from " + loc + " dir = " + dir + " will hit unit " + nearestUnit + " at distance " + nearestHitUnitDist + " and tree " + nearestTree + " at distance " + nearestHitTreeDist);
if (nearestUnit != null && (nearestTree == null || nearestHitUnitDist <= nearestHitTreeDist)) { //We hit a robot
if (nearestUnit.getTeam() != rc.getTeam())
return nearestHitUnitDist;
else
return -nearestHitUnitDist;
}
if (nearestTree != null) {
if (nearestTree.getTeam() == rc.getTeam().opponent())
return nearestHitTreeDist;
else if (nearestTree.getTeam() == rc.getTeam())
return -nearestHitTreeDist;
else
return -50;
}
return -100;
}
/*
* There is one archon that is the prime one - it gets to spend all of the initial bullets
* The prime is the archon nearest the enemy and is assigned on turn 1
*/
static boolean amIPrime() {
MapLocation[] me = rc.getInitialArchonLocations(rc.getTeam());
MapLocation[] them = rc.getInitialArchonLocations(rc.getTeam().opponent());
float nearest = 1000;
MapLocation prime = null;
for (MapLocation m: me) {
for (MapLocation t:them) {
if (m.distanceTo(t) < nearest) {
nearest = m.distanceTo(t);
prime = m;
}
}
}
return (prime == rc.getLocation());
}
/*
* The Archon creates new gardeners and acts as the arbiter for what we build
* It should avoid bullets and can shake trees
* If it is the last (or only) archon it tries really hard to stay alive
*/
static void runArchon() throws GameActionException {
// Try/catch blocks stop unhandled exceptions, which cause your robot to explode
try {
boolean prime = amIPrime();
/*
if (prime) {
debug(1, "I'm the prime archon!");
} else {
debug(1, "I'm an archon!");
}
*/
// The code you want your robot to perform every round should be in this loop
while (true) {
checkWin();
sense();
checkShake();
if (rc.getRoundNum() == 2 && rc.getTeamBullets() >= GameConstants.BULLETS_INITIAL_AMOUNT) //Check to see if the prime failed to build and take over
prime = true;
RobotInfo nearestGardener = findNearestRobot(RobotType.GARDENER, rc.getTeam());
RobotInfo nearestEnemy = null;
for (RobotInfo r:robots) {
if (r.getTeam() != rc.getTeam() && r.getType().canAttack()) {
nearestEnemy = r;
break;
}
}
float resourcesNeeded = RobotType.GARDENER.bulletCost;
if (nearestEnemy != null)
resourcesNeeded += RobotType.SOLDIER.bulletCost;
else
resourcesNeeded += GameConstants.BULLET_TREE_COST;
if (((prime && rc.getRoundNum() <= 2) || rc.getRoundNum() > 25) && rc.getTeamBullets() >= resourcesNeeded && nearestGardener == null) {
Direction dir = rc.getLocation().directionTo(mapCentre);
if (dir == null)
dir = randomDirection();
int directionsToTry = 60; //We have plenty of time to try building and in a confined place - options are good
for (int i=0; i<directionsToTry; i++) {
if (rc.canHireGardener(dir)) {
rc.hireGardener(dir);
break;
}
dir = dir.rotateLeftRads((float)Math.PI*2/directionsToTry);
}
}
wander();
// Clock.yield() makes the robot wait until the next turn, then it will perform this loop again
Clock.yield();
}
} catch (Exception e) {
//debug(1, "Archon Exception");
e.printStackTrace();
}
}
static final int buildDirections = 20;
static int countBuildOptions(Direction dir) {
int result = 0;
if (dir == null)
dir = rc.getLocation().directionTo(mapCentre);
if (dir == null)
dir = randomDirection();
for (int i=0; i<buildDirections; i++) {
if (rc.canBuildRobot(RobotType.LUMBERJACK, dir)) //A neutral tree means we need a lumberjack
result++;
dir = dir.rotateLeftRads((float)Math.PI*2/buildDirections);
}
return result;
}
static boolean buildIt(RobotType type, Direction dir) throws GameActionException {
//debug(1, "buildIt: type = " + type + " dir = " + dir);
if (dir == null)
dir = rc.getLocation().directionTo(mapCentre);
if (dir == null)
dir = randomDirection();
for (int i=0; i<buildDirections; i++) {
if (rc.canBuildRobot(type, dir)) {
rc.buildRobot(type, dir);
return true;
}
dir = dir.rotateLeftRads((float)Math.PI*2/buildDirections);
}
return false;
}
/*
* Gardeners create trees and keep them watered
* If there are no other gardeners in sight then build a garden here otherwise move away from nearest gardener
*
* Once a garden centre is picked we create a circle of trees within watering distance
*/
static void runGardener() throws GameActionException {
//debug(1, "I'm a gardener!");
Team me = rc.getTeam();
final int sides = 9;
final float buildDist = (float) (1 / Math.sin(Math.PI/sides)) - RobotType.GARDENER.bodyRadius - GameConstants.BULLET_TREE_RADIUS;
boolean scoutBuilt = false;
boolean lumberjackBuilt = false;
boolean movedAway = false;
MapLocation centre = null;
Direction spokes[] = new Direction[sides-2];
MapLocation plantFrom[] = new MapLocation[sides-2];
MapLocation treeCentre[] = new MapLocation[sides-2];
Direction buildDir = null;
MapLocation buildLoc = null;
// The code you want your robot to perform every round should be in this loop
while (true) {
// Try/catch blocks stop unhandled exceptions, which cause your robot to explode
try {
checkWin();
sense();
checkShake();
if (centre == null && isGoodGardenLocation()) {
//We centre ourselves here and build a circle of trees around us on the points of a 9 sided shape with 2 trees missing to leave space to move
//This shape allows us to water any tree from the centre without moving
centre = rc.getLocation();
buildDir = centre.directionTo(mapCentre).opposite();
buildLoc = centre.add(buildDir, RobotType.GARDENER.strideRadius);
spokes[0] = buildDir.rotateLeftRads((float)(Math.PI*3/sides));
for (int i=1; i<spokes.length; i++ ) {
spokes[i] = spokes[i-1].rotateLeftRads((float)(Math.PI*2/sides));
}
for (int i=0; i<spokes.length; i++ ) {
plantFrom[i] = centre.add(spokes[i], buildDist);
if (rc.onTheMap(plantFrom[i], RobotType.GARDENER.bodyRadius)) {
treeCentre[i] = plantFrom[i].add(spokes[i], RobotType.GARDENER.bodyRadius + GameConstants.BULLET_TREE_RADIUS + GameConstants.GENERAL_SPAWN_OFFSET);
if (!rc.onTheMap(treeCentre[i], GameConstants.BULLET_TREE_RADIUS)) {
plantFrom[i] = null; //Cannot build in this direction
}
} else {
plantFrom[i] = null; //Cannot build in this direction
}
}
}
if (centre == null) { //Move away from nearestGardener and randomly thereafter
if (!movedAway) {
RobotInfo nearestGardener = findNearestRobot(RobotType.GARDENER, rc.getTeam());
if (nearestGardener != null) {
wanderDir = nearestGardener.getLocation().directionTo(rc.getLocation());
movedAway = true;
}
}
wander();
}
int defenders = 0;
int lumberjacks = 0;
int scouts = 0; // Number of enemy scouts
int enemies = 0; //Number of combat enemies
int chopTrees = 0;
int containerTrees = 0;
float shakeResources = 0;
int myTrees = 0;
for (TreeInfo t:trees) {
if (t.getTeam() == me)
myTrees++;
else
chopTrees++;
if (t.containedRobot != null)
containerTrees++;
if (t.getContainedBullets() > 0)
shakeResources += t.getContainedBullets();
}
RobotInfo nearestEnemy = null;
for (RobotInfo r: robots) {
if (r.getTeam() != me) {
if (nearestEnemy == null)
nearestEnemy = r;
if (r.getType() == RobotType.SCOUT)
scouts++;
if (r.getType().canAttack())
enemies++;
} else {
if (r.getType() == RobotType.LUMBERJACK)
lumberjacks++;
else if (r.getType() == RobotType.SOLDIER || r.getType() == RobotType.TANK)
defenders++;
}
}
//Check to see if we want to build anything
if (rc.isBuildReady()) {
//Sometimes we only have room for 1 unit so we need it to be a lumberjack to clear space
//Other times there are free units in nearby trees
if (!lumberjackBuilt && chopTrees > 0) {
int buildLocations = countBuildOptions(buildDir);
if (buildLocations <= 1 || containerTrees > 0) { //We need a lumberjack as a priority
if (rc.hasRobotBuildRequirements(RobotType.LUMBERJACK)) {
tryMove(buildLoc);
lumberjackBuilt = buildIt(RobotType.LUMBERJACK, buildDir);
}
}
}
if (shakeResources > RobotType.SCOUT.bulletCost && rc.hasRobotBuildRequirements(RobotType.SCOUT) && !scoutBuilt) {
tryMove(buildLoc);
scoutBuilt = buildIt(RobotType.SCOUT, buildDir);
}
if (defenders == 0 || (enemies > 0 && enemies >= defenders)) {
if (rc.isBuildReady() && rc.hasRobotBuildRequirements(RobotType.TANK)) {
tryMove(buildLoc);
buildIt(RobotType.TANK, buildDir);
}
if (rc.isBuildReady() && rc.hasRobotBuildRequirements(RobotType.SOLDIER)) {
tryMove(buildLoc);
buildIt(RobotType.SOLDIER, buildDir);
}
}
if (rc.hasRobotBuildRequirements(RobotType.SCOUT) && !scoutBuilt) {
tryMove(buildLoc);
scoutBuilt = buildIt(RobotType.SCOUT, buildDir);
}
if (rc.isBuildReady() && rc.hasRobotBuildRequirements(RobotType.LUMBERJACK) && (chopTrees > lumberjacks || scouts > lumberjacks)) {
tryMove(buildLoc);
lumberjackBuilt = buildIt(RobotType.LUMBERJACK, buildDir);
}
}
//See if we can plant a tree this turn
if (centre != null && (myTrees == 0 || defenders > 0) && rc.hasTreeBuildRequirements() && !rc.hasMoved()) {
for (int currentSpoke=0; currentSpoke<spokes.length; currentSpoke++) {
if (plantFrom[currentSpoke] != null && canMove(plantFrom[currentSpoke]) && !rc.isCircleOccupiedExceptByThisRobot(treeCentre[currentSpoke], GameConstants.BULLET_TREE_RADIUS)) {
rc.move(plantFrom[currentSpoke]);
if (rc.getLocation() == plantFrom[currentSpoke] && rc.canPlantTree(spokes[currentSpoke])) {
rc.plantTree(spokes[currentSpoke]);
}
break;
}
}
}
if (!rc.hasMoved() && centre != null)
tryMove(centre);
if (rc.canWater()) {
TreeInfo waterMe = null;
for (TreeInfo t:trees) { //Find tree most in need of water
if (t.getTeam() == rc.getTeam() && rc.canWater(t.getID()) && (waterMe == null || (t.getHealth() < waterMe.getHealth())))
waterMe = t;
}
if (waterMe != null)
rc.water(waterMe.getID());
}
// Clock.yield() makes the robot wait until the next turn, then it will perform this loop again
Clock.yield();
} catch (Exception e) {
//debug(1, "Gardener Exception");
e.printStackTrace();
}
}
}
/*
* Track a bullet
* Return 0 if is misses, 1 if it hits an enemy, -1 if it hits an ally, -2 if it can be dodged, -3 if it hits a neutral
*/
static int processShot(Direction dir, RobotInfo target) {
float hitDist = hitDistance(rc.getLocation().add(dir, rc.getType().bodyRadius + GameConstants.BULLET_SPAWN_OFFSET), dir);
if (hitDist == -100) //Miss
return 0;
if (hitDist == -50) //Neutral
return -3;
if (hitDist < 0) //Ally
return -1;
int turnsBeforeHit = (int) Math.ceil(hitDist/ rc.getType().bulletSpeed);
if (hitDist % rc.getType().bulletSpeed == 0)
turnsBeforeHit--;
if (turnsBeforeHit * target.getType().strideRadius <= target.getType().bodyRadius)
return 1;
return -2; //Bullet will probably miss (can be dodged)
}
static boolean canShoot(RobotInfo target) {
float ammo = rc.getTeamBullets();
if (rc.getAttackCount() > 0)
return false;
if (target.getType() == RobotType.ARCHON && ammo < 500)
return false;
return (ammo >= 1);
}
/*
* shoot works out the optimum fire pattern based on the size of the target and its distance from us then shoots
* avoiding friendly fire
*
* If the enemy is really close we may have a guaranteed hit of one or more bullets depending on its stride
* If it is further away we may need to fire multiple shots to guarantee hitting it with one bullet
*/
static void shoot(RobotInfo target) throws GameActionException {
//debug(1, "Shooting at " + target);
if (target == null || !canShoot(target))
return;
MapLocation targetLoc = target.getLocation();
MapLocation myLocation = rc.getLocation();
Direction dir = myLocation.directionTo(targetLoc);
float dist = myLocation.distanceTo(targetLoc);
int shot = processShot(dir, target);
if (shot == 0) //Miss
return;
if (shot == -1) //Hit an ally
return;
if (shot == -3) //Neutral
return;
//Look at the distance to target and its size to determine if it can dodge
//Pentad fires 5 bullets with 15 degrees between each one (spread originating from the centre of the robot firing)
//Triad fires 3 bullets with 20 degrees between each one
//We can work out the angle either side of the centre of the target at which we hit
float spreadAngle = (float) Math.asin(target.getType().bodyRadius/dist);
int shotsToFire = 0;
Direction shotDir = dir;
//debug(3, "shoot: target " + target + " dist=" + dist + " spreadAngle = " + spreadAngle + " (" + Math.toDegrees((double)spreadAngle) + ")");
if (shot == -2) { //can be dodged
if (rc.canFireTriadShot() && dist <= target.getType().bodyRadius / Math.sin(Math.toRadians(GameConstants.TRIAD_SPREAD_DEGREES/2))) {
shotsToFire = 3;
//debug (3, "Firing 3 - 1 should hit");
} else if (rc.canFirePentadShot() && dist <= target.getType().bodyRadius / Math.sin(Math.toRadians(GameConstants.PENTAD_SPREAD_DEGREES/2))) {
shotsToFire = 5;
//debug (3, "Firing 5 - 1 should hit");
}
} else if (rc.canFirePentadShot() && 2*spreadAngle >= Math.toRadians(GameConstants.PENTAD_SPREAD_DEGREES*4)) { //All 5 shots will hit
shotsToFire = 5;
//debug (3, "Firing 5 - all should hit");
} else if (rc.canFirePentadShot() && 2*spreadAngle > Math.toRadians(GameConstants.PENTAD_SPREAD_DEGREES*3)) { //4 shots will hit
shotsToFire = 5;
shotDir.rotateRightDegrees(GameConstants.PENTAD_SPREAD_DEGREES/2);
//debug (3, "Firing 5 - 4 should hit");
} else if (rc.canFireTriadShot() && 2*spreadAngle > Math.toRadians(GameConstants.TRIAD_SPREAD_DEGREES*2)) { //All 3 triad shots will hit
shotsToFire = 3;
//debug (3, "Firing 3 - all should hit");
} else if (rc.canFirePentadShot() && 2*spreadAngle > Math.toRadians(GameConstants.PENTAD_SPREAD_DEGREES*2)) { //3 of 5 shots will hit)
shotsToFire = 5;
//debug (3, "Firing 5 - 3 should hit");
} else if (rc.canFireTriadShot() && 2*spreadAngle > Math.toRadians(GameConstants.TRIAD_SPREAD_DEGREES*2)) { //2 of a triad shots will hit
shotsToFire = 3;
shotDir.rotateLeftDegrees(GameConstants.TRIAD_SPREAD_DEGREES/2);
//debug (3, "Firing 3 - 2 should hit");
} else if (rc.canFirePentadShot() && 2*spreadAngle > Math.toRadians(GameConstants.PENTAD_SPREAD_DEGREES)) { //2 of 5 shots will hit
shotsToFire = 5;
shotDir.rotateRightDegrees(GameConstants.PENTAD_SPREAD_DEGREES/2);
//debug (3, "Firing 5 - 2 should hit");
} else if (rc.canFireSingleShot() && shot == 1) {
shotsToFire = 1;
//debug (3, "Firing 1 shot");
}
if (shotsToFire == 5) {
rc.firePentadShot(shotDir);
//debug(2, "Shooting 5 shots at " + target);
} else if (shotsToFire == 3) {
rc.fireTriadShot(shotDir);
//debug(2, "Shooting 3 shots at " + target);
} else if (shotsToFire == 1) {
rc.fireSingleShot(shotDir);
//debug(2, "Firing 1 shot at " + target);
}
if (shotsToFire > 0) { //We shot so update bullet info
bullets = rc.senseNearbyBullets();
}
}
static void runCombat() throws GameActionException {
//debug(1, "I'm a combatant!");
// The code you want your robot to perform every round should be in this loop
while (true) {
// Try/catch blocks stop unhandled exceptions, which cause your robot to explode
try {
checkWin();
sense();
checkShake();
boolean stay = manageCombat();
if (!stay) {
if (rallyPoint != null) {
moveTo(rallyPoint);
}
wander();
}
// Clock.yield() makes the robot wait until the next turn, then it will perform this loop again
Clock.yield();
} catch (Exception e) {
//debug(1, "Combatant Exception");
e.printStackTrace();
}
}
}
static float lumberjackRange() {
return rc.getType().bodyRadius + RobotType.LUMBERJACK.strideRadius + GameConstants.LUMBERJACK_STRIKE_RADIUS;
}
static int lumberjacksInRange(MapLocation loc) {
int enemyLumberjacks = 0;
int allyLumberjacks = 0;
int enemies = 0;
for (RobotInfo r:robots) {
if (r.getTeam() != rc.getTeam())
enemies++;
if (r.getType() == RobotType.LUMBERJACK && loc.distanceTo(r.getLocation()) <= lumberjackRange()) {
if (r.getTeam() != rc.getTeam())
enemyLumberjacks++;
else
allyLumberjacks++;
}
}
if (overrideDanger)
enemyLumberjacks = 0;
if (enemies > 0) //Our own lumberjacks will be attacking
enemyLumberjacks += allyLumberjacks;
return enemyLumberjacks;
}
/*
* A tree is safe if we can hide in it
* That means there has to be room and there is no attacking robot within its stride distance since a shot fired adjacent to a tree could hit us in the tree
*/
static boolean isTreeSafe(TreeInfo t) throws GameActionException {
if (Clock.getBytecodesLeft() < 1000) //This routine can take time so return false if we are short on time
return false;
if (t.getHealth() <= GameConstants.LUMBERJACK_CHOP_DAMAGE || (t.containedRobot != null && t.getHealth() < 20))
return false;
if (t.getRadius() < RobotType.SCOUT.bodyRadius) //Too small to hide in
return false;
//For trees the same size as us they are safe if no lumberjack is in range and no unit with bullets is within a stride of the tree edge
for (RobotInfo r: robots) {
float distanceToTree = r.getLocation().distanceTo(t.getLocation());
float gapBetween = distanceToTree - t.getRadius() - r.getType().bodyRadius;
if (gapBetween < 0) { //Occupied
//setIndicator(t.getLocation(),255,128,128);
return false;
}
if (r.getTeam() != rc.getTeam() && r.getType().canAttack()) { //Enemy
float dangerDist = r.getType().strideRadius;
if (r.getType() == RobotType.LUMBERJACK)
dangerDist += GameConstants.LUMBERJACK_STRIKE_RADIUS;
else
dangerDist += GameConstants.BULLET_SPAWN_OFFSET;
if (gapBetween <= dangerDist) {
//setIndicator(t.getLocation(), 255,0,0);
return false;
}
}
}
//setIndicator(t.getLocation(),0,255,0);
return true;
}
/*
* ManageCombat
*
* Find the best target and the best position to shoot from
* Returns true if we are in the right place and shouldn't move
*
* We track the position of the nearest threat and the position of the best target
*/
static boolean manageCombat() throws GameActionException {
Team enemy = rc.getTeam().opponent();
MapLocation myLocation = rc.getLocation();
RobotInfo nearestGardener = null;
RobotInfo nearestArchon = null;
RobotInfo nearestDanger = null;
RobotInfo nearestEnemy = null;
RobotInfo nearestLumberjack = null;
RobotInfo nearestAllyLumberjack = null;
float safeDistance = lumberjackRange() + GameConstants.BULLET_SPAWN_OFFSET;
for (RobotInfo r:robots) {
if (r.getTeam() == enemy) {
if (nearestGardener == null && r.getType() == RobotType.GARDENER)
nearestGardener = r;
else if (nearestArchon == null && r.getType() == RobotType.ARCHON)
nearestArchon = r;
else if (nearestLumberjack == null && r.getType() == RobotType.LUMBERJACK)
nearestLumberjack = r;
if (nearestDanger == null && r.getType().canAttack())
nearestDanger = r;
if (nearestEnemy == null)
nearestEnemy = r;
} else {
if (nearestAllyLumberjack == null && r.getType() == RobotType.LUMBERJACK)
nearestAllyLumberjack = r;
}
}
if (nearestEnemy == null) { //There are no enemies in sight but we might be being shot at
if (rc.getType() == RobotType.TANK)
returnFire();
return false;
}
if (rc.getType() == RobotType.SCOUT && damageAtLocation(rc.getLocation()) > 0) {
//We are better off dodging by moving away
shoot(nearestEnemy);
safeDistance = nearestEnemy.getType().sensorRadius + rc.getType().bodyRadius + GameConstants.BULLET_SPAWN_OFFSET; //Move out of its sight radius
MapLocation away = rc.getLocation().add(nearestEnemy.getLocation().directionTo(rc.getLocation()).rotateLeftDegrees(5), safeDistance);
tryMove(away);
return false;
}
MapLocation combatPosition = null;
// If there is a threat ...
if (nearestDanger != null) {
MapLocation dangerLoc = nearestDanger.getLocation();
//If we are a scout then find the nearest available tree to shoot from
//Must be close to target and us and safe
TreeInfo nearestTree = null;
if (rc.getType() == RobotType.SCOUT) {
TreeInfo[] near = rc.senseNearbyTrees(dangerLoc, 3, null);
for (TreeInfo t:near) {
if (isTreeSafe(t)) {
nearestTree = t;
break;
}
}
}
if (nearestTree != null) { //Scouts can hide in trees
float bulletOffset = GameConstants.BULLET_SPAWN_OFFSET / 2;
float dist = nearestTree.radius - RobotType.SCOUT.bodyRadius - bulletOffset;
//debug(2, "Hiding in tree " + nearestTree + " target = " + nearestDanger);
if (dist >= 0)
combatPosition = nearestTree.getLocation().add(nearestTree.getLocation().directionTo(dangerLoc),dist);
else
combatPosition = nearestTree.getLocation().add(nearestTree.getLocation().directionTo(dangerLoc).opposite(),-dist);
} else if (nearestDanger.getType() == RobotType.LUMBERJACK || (nearestLumberjack != null && myLocation.distanceTo(nearestLumberjack.getLocation()) < safeDistance)) {
//debug(2, "Keeping at range from enemy lumberjack" + nearestLumberjack);
combatPosition = nearestLumberjack.getLocation().add(nearestLumberjack.getLocation().directionTo(myLocation).rotateLeftDegrees(5), safeDistance);
} else if (canShoot(nearestDanger) && canBeat(nearestDanger)) {
RobotType t = nearestDanger.getType();
//debug(2, "Can Win: Closing on " + nearestDanger);
overrideDanger = true;
TreeInfo tr = null;
if (rc.canSenseLocation(nearestDanger.getLocation()))
tr = rc.senseTreeAtLocation(nearestDanger.getLocation());
if (tr == null) {
safeDistance = rc.getType().bodyRadius + t.bodyRadius; //Right up close and personal
combatPosition = dangerLoc.add(dangerLoc.directionTo(myLocation).rotateLeftDegrees(5), safeDistance);
} else { //Move to edge of tree closest to scout
safeDistance = rc.getType().bodyRadius + tr.getRadius(); //edge of tree
if (nearestDanger.getLocation() == tr.getLocation()) {
combatPosition = dangerLoc.add(dangerLoc.directionTo(myLocation), safeDistance);
} else {
combatPosition = tr.getLocation().add(tr.getLocation().directionTo(nearestDanger.getLocation()), safeDistance);
}
}
} else {
//debug(2, "Running from " + nearestDanger);
RobotType t = nearestDanger.getType();
safeDistance = t.sensorRadius + rc.getType().bodyRadius + GameConstants.BULLET_SPAWN_OFFSET;
combatPosition = nearestDanger.getLocation().add(nearestDanger.getLocation().directionTo(myLocation).rotateLeftDegrees(5), safeDistance);
}
} else if (nearestAllyLumberjack != null && nearestEnemy != null && myLocation.distanceTo(nearestAllyLumberjack.getLocation()) < safeDistance) {
//debug(2, "Keeping at range from our lumberjack" + nearestAllyLumberjack);
combatPosition = nearestAllyLumberjack.getLocation().add(nearestAllyLumberjack.getLocation().directionTo(myLocation).rotateLeftDegrees(5), safeDistance);
} else { //Not in danger so close with best enemy target
RobotInfo target = null;
if (nearestGardener != null)
target = nearestGardener;
else if (nearestArchon != null)
target = nearestArchon;
if (target != null) {
//debug(2, "Safe: Closing on " + target);
combatPosition = target.getLocation().add(target.getLocation().directionTo(myLocation).rotateLeftDegrees(5), rc.getType().bodyRadius + target.getType().bodyRadius + GameConstants.BULLET_SPAWN_OFFSET);
}
}
if (combatPosition != null) {
disengageWallMode();
tryMove(combatPosition);
}
if (!rc.hasAttacked()) {
//Now find nearest target to new position
RobotInfo[] targets = rc.senseNearbyRobots(-1, rc.getTeam().opponent());
if (targets.length > 0) {
shoot(targets[0]);
}
}
return true;
}
static boolean canBeat(RobotInfo enemy) {
if (!rc.getType().canAttack())
return false;
if (!enemy.getType().canAttack())
return true;
if (rc.getType() == RobotType.LUMBERJACK) { //These can't shoot so run away from soldiers and tanks
if (enemy.getType() == RobotType.SOLDIER || enemy.getType() == RobotType.TANK)
return false;
}
if (rc.getType() == RobotType.SCOUT && enemy.getType() != RobotType.SCOUT) //Assume we will lose as we are better off finding non-combat units to shoot
return false;
int turnsToKill = (int) (enemy.getHealth() / rc.getType().attackPower);
int turnsToDie = (int) (rc.getHealth() / enemy.getType().attackPower);
return turnsToKill <= turnsToDie;
}
/*
* Scouts are used to kill from the safety of trees
* Once in a tree (just back from the edge) our shots will safely fire but the enemy will hit the tree!
* Lumberjacks are our nemesis as they can strike us in the trees so we always move away from them
* Even our own lumberjacks will hit us if they can see an enemy
*/
static void runScout() throws GameActionException {
//debug(1, "I'm a scout!");
Team enemy = rc.getTeam().opponent();
MapLocation[] archons = rc.getInitialArchonLocations(enemy);
int archon_to_visit = 0;
//Work out which of our archons we are nearest
MapLocation[] myArchons = rc.getInitialArchonLocations(rc.getTeam());
int nearest = -1;
int i = 0;
for (MapLocation m: myArchons) {
if (nearest == -1 || rc.getLocation().distanceTo(m) < rc.getLocation().distanceTo(myArchons[nearest]))
nearest = i;
i++;
}
// The code you want your robot to perform every round should be in this loop
while (true) {
// Try/catch blocks stop unhandled exceptions, which cause your robot to explode
try {
checkWin();
sense();
checkShake();
boolean stay = manageCombat();
// Move towards current enemy archon position
if (!stay && !rc.hasMoved()) {
if (archon_to_visit >= archons.length) {
wander();
} else {
if (rc.getLocation().distanceTo(archons[(archon_to_visit+nearest)%archons.length]) < rc.getType().strideRadius)
archon_to_visit++;