forked from yanntm/YoBot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathYoBot.h
More file actions
2222 lines (1903 loc) · 80.5 KB
/
YoBot.h
File metadata and controls
2222 lines (1903 loc) · 80.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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
#pragma once
#include "sc2api/sc2_interfaces.h"
#include "sc2api/sc2_agent.h"
#include "sc2api/sc2_map_info.h"
#include "sc2lib/sc2_lib.h"
#include "UnitTypes.h"
#include "DistUtil.h"
#include "YoAgent.h"
#include "TechTree.h"
#include "MapTools.h"
#include "GameCommander.h"
#include <valarray>
//#include "Strategys.h"
//#include "WorkerManager.h"
#define DllExport __declspec( dllexport )
using namespace sc2;
using namespace sc2util;
#pragma warning( disable : 4267 4305 4244 )
class YoBot : public YoAgent {
public:
YoBot::YoBot()
: m_techTree(*this)
, m_gameCommander(*this)//, m_map)
//, m_baseLocationManager(*this) //in parentclass
//, m_unitInfoManager(*this) //in parentclass
//, m_workerManager(*this) //in parentclass
//, m_gameCommander(*this) //not used yet
//, m_strategy(*this) //not used yet
//, m_baseMan(*this) //not used yet
{
YoAgent();
}
//MapTools m_map; //in YoAgent parentclass
//BaseLocationManager m_baseLocationManager;//in YoAgent parentclass
//UnitInfoManager m_unitInfoManager; //in YoAgent parentclass
//WorkerManager m_workerManager; //in YoAgent parentclass
TechTree m_techTree;
GameCommander m_gameCommander;
int minerals = 0;
int gas = 0;
int supplyleft = 0;
sc2::Units probes;
virtual void OnGameStart() final {
std::cout << "YoStalkBot will kill you!" << std::endl;
YoAgent::OnGameStart();
m_techTree.onStart();
//m_strategy.onStart(); //not used yet
m_map.onStart();
m_baseLocationManager.onStart();
m_unitInfoManager.onStart();
m_workerManager.onStart();
m_gameCommander.onStart();
frame = 0;
nexus = nullptr;
auto list = Observation()->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_NEXUS));
nexus = list.front();
const Unit* mineral_target = FindNearestMineralPatch(nexus->pos);
Actions()->UnitCommand(nexus, ABILITY_ID::RALLY_NEXUS, mineral_target);
Actions()->UnitCommand(nexus, ABILITY_ID::TRAIN_PROBE);
probes = Observation()->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_PROBE));
/// === BOB IS THE CHOSEN ONE!!! === /// sort probes by distance to center of probes //ones on outside are best for taking as builder-bob or worker-scout
if (!probes.empty()) {
Point2D centerOfProbes = probes.front()->pos;
for (auto it = probes.begin()++; it != probes.end(); ++it) {
centerOfProbes += (*it)->pos;
}
centerOfProbes /= (float)probes.size();
std::sort(probes.begin(), probes.end(), [centerOfProbes](const sc2::Unit* a, const sc2::Unit* b) { return DistanceSquared2D(centerOfProbes, a->pos) < DistanceSquared2D(centerOfProbes, b->pos); });
}
bob = probes.back(); //builder-bob should be least-useful worker, most-likely from outer edge of worker-clump
workerStates.insert_or_assign(bob->tag, WorkerState::MovingToBuild);
const GameInfo& game_info = Observation()->GetGameInfo();
auto playerID = Observation()->GetPlayerID();
for (const auto & playerInfo : Observation()->GetGameInfo().player_info)
{
if (playerInfo.player_id != playerID)
{
enemyRace = playerInfo.race_requested;
break;
}
}
if (game_info.enemy_start_locations.size() > 1) {
proxy = cog(game_info.enemy_start_locations);
scout = *(++Observation()->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_PROBE)).begin());
workerStates.insert_or_assign(scout->tag, WorkerState::MovingToScout);
// return minerals
Actions()->UnitCommand(scout, ABILITY_ID::SMART, nexus, true);
Actions()->UnitCommand(scout, ABILITY_ID::SMART, game_info.enemy_start_locations[0], true);
scouted = 0;
target = proxy;
}
else {
target = game_info.enemy_start_locations.front();
int max = 2;
if (map.hasPockets()) max = 3;
int rnd = GetRandomInteger(0, max);
int limit = 1;
if (enemyRace == Race::Zerg) limit = 0;
if (rnd <= limit) proxy = map.getPosition(MapTopology::enemy, MapTopology::nat);
else if (rnd <= 2) proxy = map.getPosition(MapTopology::enemy, MapTopology::proxy);
else if (rnd == 3) proxy = map.getPosition(MapTopology::enemy, MapTopology::pocket);
}
/// ==== SET PROXY LOCATION === ///
float percentageTowardsEnemy = 0.0;
if (game_info.map_name == "16BitLE.SC2Map" || game_info.map_name == "16BitLE") percentageTowardsEnemy = 0.6;
else if (game_info.map_name == "Acid Plant LE") percentageTowardsEnemy = 0.75;
else if (game_info.map_name == "Catalyst LE") proxy = Point2D(93.0, 64.0);
else if (game_info.map_name == "Dreamcatcher LE") target.x > 100.0 ? proxy = Point2D(104.0, 73.0) : proxy = Point2D(73.0, 104.0);
else if (game_info.map_name == "Lost and Found LE") target.x < 50.0 ? proxy = Point2D(75.0, 57.0) : proxy = Point2D(57.0, 75.0);
else if (game_info.map_name == "Fracture LE") percentageTowardsEnemy = 0.6; //target.x > 100.0 ? proxy = Point2D(117.0, 77.0) : proxy = Point2D(??.0, 117.0);
else if (game_info.map_name == "Blueshift LE") target.x < 100.0 ? proxy = Point2D(71.0, 85.0) : proxy = Point2D(102.0, 91.0);
else if (game_info.map_name == "Cerulean Fall LE") percentageTowardsEnemy = 0.75;
else if (game_info.map_name == "Darkness Sanctuary LE") percentageTowardsEnemy = 0.45;
else percentageTowardsEnemy = 0.1;
if (percentageTowardsEnemy > 0.0) proxy = (percentageTowardsEnemy * target + (1.0 - percentageTowardsEnemy)*nexus->pos); //how far between these?
std::cout << game_info.map_name << " " << percentageTowardsEnemy << " " << proxy.x << "," << proxy.y << std::endl;
std::cout << game_info.playable_max.x << "," << game_info.playable_max.y << " - " << game_info.playable_min.x << "," << game_info.playable_min.y << std::endl;
//proxy = this->map.FindNearestBase(Point3D(proxy.x, proxy.y, 11.0f));
//proxy = this->map.FindFarthestBase(nexus->pos,target);
//proxy = game_info.start_locations[0];
//proxy = this->map.FindNearestBase(nexus->pos); //Point3D(proxy.x, proxy.y, 11.0f));
//use this???
/*getPosition(Player p, BaseType b) const {
int id = p==ally ? ourBaseStartLocIndex : (ourBaseStartLocIndex == 0) ? 1 : 0;
switch (b) {
case main: return expansions[mainBases[id]];
case nat: return expansions[naturalBases[id]];
case proxy: return expansions[proxyBases[id]];
case pocket:
if (hasPockets()) {
return expansions[pocketBases[id]];
}
else {
return expansions[naturalBases[id]];
}
}*/
enemyBaseRazed = false;
choke = (.2f * target + .8f*nexus->pos);
Actions()->UnitCommand(bob, ABILITY_ID::SMART, proxy);
TrySpreadProbes(nexus);
//babysitMineralWorkersEachFrame(probes);
}
void TrySpreadProbes(const sc2::Unit* townHall) {
auto th_pos = townHall->pos;
Units mins = Observation()->GetUnits(Unit::Alliance::Neutral, [th_pos](const Unit & u) { return IsMineral(u.unit_type) && Distance2D(u.pos, th_pos) < 15.0f; });
Units probes = Observation()->GetUnits(Unit::Alliance::Self, [th_pos](const Unit & u) { return u.unit_type == UNIT_TYPEID::PROTOSS_PROBE && Distance2D(u.pos, th_pos) < 15.0f; });
std::vector<int> targets = assignMineralWorkers(probes, mins, townHall);
for (int att = 0, e = targets.size(); att < e; att++) {
if (targets[att] != -1) {
Actions()->UnitCommand(probes[att], ABILITY_ID::SMART, mins[targets[att]]);
}
}
}
//depends on global variable "probes"
//allocate workers to the best mineral fields
std::vector<int> assignMineralWorkers(const Units & workers, const Units & mins, const Unit* townHall) {
//std::remove_if(mins.begin(), mins.end(), [npos](const Unit * u) { return Distance2D(u->pos, npos) > 6.0f; });
std::unordered_map<Tag, int> workerTagToIndexMap; //map workers' Unit.unit_tag to their index in the "workers" vector function-parameter
for (int i = 0, e = workers.size(); i < e; i++) {
workerTagToIndexMap.insert_or_assign(workers[i]->tag, i);
}
std::unordered_map<Tag, int> mineralTagToIndexMap; //map mineral-crystals' Unit.unit_tag to their index in the "mins" vector function-parameter
for (int i = 0, e = mins.size(); i < e; i++) {
mineralTagToIndexMap.insert_or_assign(mins[i]->tag, i);
}
//this will be returned where index is probe-index and value is mineralCrystal-index, of the passed-in Units lists
std::vector<int> workerToMineralTargetList;
workerToMineralTargetList.resize(workers.size(), -1);
std::vector<std::vector<int>> assignedWorkersOnMineral;
assignedWorkersOnMineral.resize(mins.size());
std::vector<int> freeAgents;
std::vector<int> freeMins;
//don't include builder or scout in freeAgents //they shouldn't be passed into here, but might at beginning of game
for (int i = 0, e = workers.size(); i < e; i++) {
if (bob != nullptr && bob->tag == workers[i]->tag)
continue;
if (scout != nullptr && scout->tag == workers[i]->tag)
continue;
//if (workerAssignedMinerals[workers[i]->tag] != nullptr) continue; don't reassign people?
freeAgents.push_back(i);
}
for (int i = 0, e = mins.size(); i < e; i++) {
freeMins.push_back(i);
}
//sort mineral-crystals by closeness-to-townHall-center in reverse-order, so we can use .back() and .pop_back()
if (!freeMins.empty() && townHall != nullptr) { //const Unit* mineral_target = FindNearestMineralPatch(nexus->pos);
std::sort(freeMins.begin(), freeMins.end(), [townHall, mins](int a, int b) { return DistanceSquared2D(townHall->pos, mins[a]->pos) > DistanceSquared2D(townHall->pos, mins[b]->pos); });
}
//choose closest freeAgent to each mineral-crystal
while (!freeMins.empty() && !freeAgents.empty()) {
int chooser = freeMins.back(); //the mineral-crystal gets to choose its miners!
freeMins.pop_back();
auto target_pos = mins[chooser]->pos; //this should probably be the magicPosition, for higher chance of avoiding workers behind mineral-line from taking precedence
std::sort(freeAgents.begin(), freeAgents.end(), [target_pos, workers](int a, int b) { return DistanceSquared2D(target_pos, workers[a]->pos) > DistanceSquared2D(target_pos, workers[b]->pos); });
int assignee = freeAgents.back();
freeAgents.pop_back();
assignedWorkersOnMineral[chooser].push_back(assignee);
workerAssignedMinerals.insert_or_assign(workers[assignee]->tag, mins[chooser]->tag); //for each worker, which crystal are they assigned?
workerToMineralTargetList[assignee] = chooser;
if (assignedWorkersOnMineral[chooser].size() < 2) { //toAlloc(mins[chooser])) {
freeMins.insert(freeMins.begin(), chooser);
}
}
return workerToMineralTargetList;
}
virtual void OnUnitCreated(const Unit* unit) final {
if (IsArmyUnitType(unit->unit_type)) {
if (unit->unit_type == UNIT_TYPEID::PROTOSS_VOIDRAY) {
for (auto u : enemies) {
if (u.second->is_flying) {
Actions()->UnitCommand(unit, ABILITY_ID::ATTACK, u.second->pos);
break;
}
}
}
else {
Actions()->UnitCommand(unit, ABILITY_ID::ATTACK, defensePoint(proxy));
}
}
else if (unit->unit_type == UNIT_TYPEID::PROTOSS_NEXUS) {
const Unit* mineral_target = FindNearestMineralPatch(unit->pos);
Actions()->UnitCommand(unit, ABILITY_ID::RALLY_NEXUS, mineral_target);
for (auto p : Observation()->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_PROBE))) {
Actions()->UnitCommand(unit, ABILITY_ID::HARVEST_GATHER, mineral_target);
}
if (nexus == nullptr) {
nexus = unit;
}
}
else if (unit->unit_type == UNIT_TYPEID::PROTOSS_GATEWAY) {
structures_in_progress.insert(structures_in_progress.begin(), unit); //check after completed to set Rally Point
}
else if (unit->unit_type == UNIT_TYPEID::PROTOSS_PROBE) {
const sc2::Unit* closestTownHall = FindNearestTownHall(unit->pos);
//TrySpreadProbes(closestTownHall); //closestTH is an iterator, so have to derefence first
}
else if (unit->unit_type == UNIT_TYPEID::PROTOSS_CYBERNETICSCORE) {
//bob has built his last necessary building, make him a Scout-Harasser now! check for staticD!
//TODO: Fix this later
/*if (scout == nullptr) { //don't overwrite a scout already on its path
scout = bob;
m_gameCommander.setScoutUnit(scout);
bob = nullptr; //or create another bob at homeBase
}*/
}
}
//safe way to remove and de-target mineral cluster
void RemoveWorkerFromMinerals(const Unit* mineralWorker) {
sc2::Tag workerTag = mineralWorker->tag;
//if worker was on Minerals
if (workerStates[workerTag] < WorkerState::ReturningMineral) { //gather/return Gas is 3,4
sc2::Tag mineralTag = workerAssignedMinerals[workerTag];
//if (mineralTag == 0) //what if its null ???
workerAssignedMinerals.erase(workerTag); //remove targeted mineral
}
workerStates.insert_or_assign(workerTag, WorkerState::MovingToScout);
//TODO: if worker is on gas
}
/*void AddWorkerToMinerals(const Unit* mineralWorker, const sc2::Unit* townHall) {
sc2::Tag workerTag = mineralWorker->tag;
//go through all minerals to find which one has least assigned
//copy "assignMineralWorkers" and "TrySpreadProbes" just without re-assignment
if (townHall == nullptr) {
auto list = Observation()->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_NEXUS));
townHall = list.front();
}
if (townHall == nullptr) return; //if no nexus, abandon mineral-assignment
auto th_pos = townHall->pos;
Units mins = Observation()->GetUnits(Unit::Alliance::Neutral, [th_pos](const Unit & u) { return IsMineral(u.unit_type) && Distance2D(u.pos, th_pos) < 15.0f; });
//Units probes = Observation()->GetUnits(Unit::Alliance::Self, [th_pos](const Unit & u) { return u.unit_type == UNIT_TYPEID::PROTOSS_PROBE && Distance2D(u.pos, th_pos) < 15.0f; });
//std::vector<int> targets = assignMineralWorkers(probes, mins, townHall);
//Actions()->UnitCommand(probes[att], ABILITY_ID::SMART, mins[targets[att]]);
std::unordered_map<Tag, int> mineralTagToIndexMap; //map mineral-crystals' Unit.unit_tag to their index in the "mins" vector function-parameter
for (int i = 0, e = mins.size(); i < e; i++) {
mineralTagToIndexMap.insert_or_assign(mins[i]->tag, i);
}
std::vector<std::vector<int>> assignedWorkersOnMineral;
assignedWorkersOnMineral.resize(mins.size());
std::vector<int> freeMins;
for (int i = 0, e = mins.size(); i < e; i++) {
freeMins.push_back(i);
}
//sort mineral-crystals by closeness-to-townHall-center in reverse-order, so we can use .back() and .pop_back()
if (!freeMins.empty() && townHall != nullptr) { //const Unit* mineral_target = FindNearestMineralPatch(nexus->pos);
std::sort(freeMins.begin(), freeMins.end(), [townHall, mins](int a, int b) { return DistanceSquared2D(townHall->pos, mins[a]->pos) > DistanceSquared2D(townHall->pos, mins[b]->pos); });
}
//choose closest freeAgent to each mineral-crystal
while (!freeMins.empty()) {
int howManyOnThisMineral = freeMins.back(); //the mineral-crystal gets to choose its miners!
auto target_pos = mins[chooser]->pos; //this should probably be the magicPosition, for higher chance of avoiding workers behind mineral-line from taking precedence
assignedWorkersOnMineral[chooser].push_back(assignee);
workerAssignedMinerals.insert_or_assign(workers[assignee]->tag, mins[chooser]->tag); //for each worker, which crystal are they assigned?
if (workerAssignedMinerals[workerTag])
workerToMineralTargetList[assignee] = chooser;
if (assignedWorkersOnMineral[chooser].size() < 2) { //toAlloc(mins[chooser])) {
freeMins.insert(freeMins.begin(), chooser);
}
}
//add worker to that mineral
workerStates.insert_or_assign(workerTag, WorkerState::GatheringMineral);
}*/
virtual void CheckIfStructuresCompleted() {
for (auto unit : structures_in_progress) {
if (unit->build_progress == 1.0) {
if (unit->unit_type == UNIT_TYPEID::PROTOSS_GATEWAY) {
const Unit* mineral_target = FindNearestMineralPatch(unit->pos);
auto direction = proxy - unit->pos;
direction /= Distance2D(Point2D(0, 0), direction);
// point towards proxy
Actions()->UnitCommand(unit, ABILITY_ID::RALLY_BUILDING, unit->pos + 2 * direction);
}
//else if (unit->unit_type == UNIT_TYPEID::PROTOSS_CYBERNETICSCORE) //send bob as a Scout Harrasser //check for spines or expo
//{ }
}
}
structures_in_progress.erase(
remove_if(structures_in_progress.begin(), structures_in_progress.end(), [](const sc2::Unit* u){ return u->build_progress == 1.0; } ),
structures_in_progress.end());
}
// return a position to defend a position from
Point2D defensePoint(const Point2D & pos) {
const Unit* min = FindNearestMineralPatch(pos);
if (Distance2D(pos, min->pos) < 10.0f) {
return 2 * pos - min->pos;
}
else {
return pos;
}
}
virtual void OnUnitHasAttacked(const Unit* unit) final { //i think this chases enemy. assumption is "after attack", you try to keep enemy in_range of you (maybe out-of-range-of-enemy, too?)
if (IsArmyUnitType(unit->unit_type)) { //unit->unit_type == UNIT_TYPEID::PROTOSS_ZEALOT || unit->unit_type == UNIT_TYPEID::PROTOSS_STALKER) { PROTOSS_ADEPT
auto targets = FindEnemiesInRange(unit->pos, 25);
if (!targets.empty() && unit->unit_type == UNIT_TYPEID::PROTOSS_SENTRY && unit->energy >= 75) {
Actions()->UnitCommand(unit, ABILITY_ID::EFFECT_GUARDIANSHIELD);
}
bool isToss = true;
for (auto r : Observation()->GetGameInfo().player_info) {
if (r.race_requested != Protoss) {
isToss = false;
break;
}
}
Units weak;
Units drones;
Units pylons;
for (auto t : targets) {
if (t->unit_type == UNIT_TYPEID::ZERG_EGG || t->unit_type == UNIT_TYPEID::ZERG_BROODLING || t->unit_type == UNIT_TYPEID::ZERG_LARVA) {
continue;
}
if ((t->health + t->shield) / (t->health_max + t->shield_max) < 0.7 && t->build_progress == 1.0f && (!isToss || t->is_powered )) {
weak.push_back(t);
}
if (t->unit_type == UNIT_TYPEID::PROTOSS_PROBE || t->unit_type == UNIT_TYPEID::TERRAN_SCV || t->unit_type == UNIT_TYPEID::ZERG_DRONE) {
drones.push_back(t);
}
if (t->unit_type == UNIT_TYPEID::TERRAN_SUPPLYDEPOT || t->unit_type == UNIT_TYPEID::TERRAN_SUPPLYDEPOTLOWERED || t->unit_type == UNIT_TYPEID::PROTOSS_PYLON) {
pylons.push_back(t);
}
}
const Unit * enemy = nullptr;
if (!weak.empty()) {
enemy = chooseClosest(unit, weak); //std::cout << "Chose a weak enemy" << std::endl;
}
else if (unit->shield > 15) {
if (!drones.empty()) {
enemy = chooseClosest(unit, drones); //std::cout << "Chose a drone enemy" << std::endl;
}
else if (!pylons.empty()) {
enemy = chooseClosest(unit, pylons); //std::cout << "Chose a pylon enemy" << std::endl;
}
}
if (enemy != nullptr && enemy->tag != unit->engaged_target_tag) {
Actions()->UnitCommand(unit, ABILITY_ID::ATTACK_ATTACK, enemy);
}
/* if (unit->orders.size() != 0) {
auto order = unit->orders.front();
if (order.ability_id == ABILITY_ID::ATTACK_ATTACK) {
Actions()->UnitCommand(unit, ABILITY_ID::MOVE, order.target_pos);
}
}*/
//std::cout << "on CD " << unit->tag << " " << unit->weapon_cooldown << std::endl;
}
else if (unit->unit_type == UNIT_TYPEID::PROTOSS_PROBE) {
OnUnitIdle(unit);
/* if (unit->orders.size() > 1 && unit->orders[1].ability_id != ABILITY_ID::ATTACK) {
// this means we just got out of a opportunistic attack
sendUnitCommand(unit, unit->orders[1]);
}
else {
}*/
//OnUnitAttacked(unit);
}
}
virtual void OnUnitReadyAttack(const Unit* unit) final {
if (IsArmyUnitType(unit->unit_type) && !unit->orders.empty() ) { // ((unit->unit_type == UNIT_TYPEID::PROTOSS_ZEALOT || PROTOSS_STALKER PROTOSS_ADEPT
auto order = unit->orders.front();
//Actions()->UnitCommand(unit, ABILITY_ID::ATTACK_ATTACK, order.target_pos);
//std::cout << "off CD " << unit->tag << std::endl;
}
}
virtual void OnError(const std::vector<ClientError>& client_errors, const std::vector<std::string>& protocol_errors) {
for (auto ce : client_errors) {
std::cout << (int)ce << std::endl;
}
for (auto ce : protocol_errors) {
std::cout << ce << std::endl;
}
}
bool evade(const Unit * unit) {
auto nmies = FindEnemiesInRange(unit->pos, 6.0f);
if (nmies.empty()) {
return false;
}
sortByDistanceTo(nmies, unit->pos);
if (nmies.size() >= 8) {
nmies.resize(8);
}
float delta =2 ;
float delta2 = delta / sqrt(2) ;
std::vector<Point2D> outs = { unit->pos,
unit->pos + Point2D(delta,0.0f), unit->pos + Point2D(0.0f,delta) , unit->pos + Point2D(-delta,0.0f) , unit->pos + Point2D(0.0f,-delta) ,
unit->pos + Point2D(delta2,delta2), unit->pos + Point2D(delta2,-delta2) , unit->pos + Point2D(-delta2,delta2) , unit->pos + Point2D(-delta2,-delta2)
};
std::vector <sc2::QueryInterface::PathingQuery> queries;
for (auto p : outs) {
queries.push_back({ 0, unit->pos, p });
for (auto nmy : nmies) {
queries.push_back({ 0, nmy->pos, p });
}
}
// double distance ?
for (auto pos : outs) {
queries.push_back({ 0, unit->pos, pos+ (pos - unit->pos) });
}
// half distance ?
for (auto pos : outs) {
queries.push_back({ 0, unit->pos, (unit->pos + pos )/2 });
}
// send the query and wait for answer
std::vector<float> distances = Query()->PathingDistance(queries);
std::vector<float> scores;
scores.reserve(outs.size());
// 0 pos is us
scores.push_back(-1);
// skip us, it's not an option
for (int outid = 1; outid < outs.size(); outid++) {
// our distance
int ind = outid * (nmies.size()+1);
float dtobob = distances[ind];
// who can beat us to it ?
float score = 0;
if (dtobob == 0 || dtobob >= 1.2 * delta) {
// non pathable
score = -1;
} else {
for (int i = 1; i <= nmies.size(); i++) {
float rank = nmies.size() - i + 1;
// from enemy to out
float dtonmy = distances[ind + i];
// it can't path is good, further than where we are now is good
if (dtonmy==0) {
score+=rank;
}
// greater dist from enemy to point than bob to point ?
// greater dist from enemy to point than enemy to bob ?
else if (dtonmy >= dtobob && dtonmy >= distances[i]) {
score += (dtonmy - distances[i]) / delta * rank;
// score += (dtonmy - distances[i]) / delta;
// score += (dtonmy - dtobob) / delta ;
// score += distances[i] / dtonmy ;
}
}
}
scores.push_back(score);
}
// double score of truly open outs
for (int outid = 1; outid < outs.size(); outid++) {
float next = distances[outs.size() * (nmies.size() + 1) + outid];
if (next != 0 && next < 2.3 * delta) {
scores[outid] *= 2;
}
}
// neg score of not truly reachable
for (int outid = 1; outid < outs.size(); outid++) {
float next = distances[outs.size() * (nmies.size() + 2) + outid];
if (next == 0 || next > 0.7 * delta) {
if (scores[outid] > 0)
scores[outid] *= -1;
}
}
int best = 0;
for (int i = 0; i < scores.size(); i++) {
if (scores[i] > scores[best]) {
best = i;
}
}
int nbouts = 0;
auto dprox = Distance2D(proxy, outs[best]);
int bestproxout = best;
for (int i = 0; i < scores.size(); i++) {
if (scores[i] > 0.5 * scores[best]) {
nbouts ++;
auto dpout = Distance2D(proxy, outs[i]);
if (dpout < dprox) {
bestproxout = i;
dprox = dpout;
}
}
}
#ifdef DEBUG
for (int i = 0; i < outs.size(); i++) {
auto out = outs[i];
if (i == best) {
Debug()->DebugLineOut(unit->pos, Point3D(out.x, out.y, unit->pos.z + 0.1f), Colors::Green);
}
else if (i == bestproxout) {
Debug()->DebugLineOut(unit->pos, Point3D(out.x, out.y, unit->pos.z + 0.1f), Colors::Blue);
}
else {
Debug()->DebugLineOut(unit->pos, Point3D(out.x, out.y, unit->pos.z + 0.1f));
}
Debug()->DebugTextOut(std::to_string(scores[i]), Point3D(out.x, out.y, unit->pos.z + 0.1f));
}
Debug()->SendDebug();
#endif // DEBUG
auto closest = Distance2D(unit->pos, (*nmies.begin())->pos);
if (nbouts <= 2 && ( unit->shield == 0 || closest <= 1.5f) && nexus != nullptr) {
// try to mineral slide our way out
Actions()->UnitCommand(unit, ABILITY_ID::HARVEST_GATHER, FindNearestMineralPatch(nexus->pos));
}
else if (nbouts >= 3 && closest >= 1.5f && unit->shield >= 0) {
Actions()->UnitCommand(unit, ABILITY_ID::MOVE, outs[bestproxout]);
}
else {
Actions()->UnitCommand(unit, ABILITY_ID::MOVE, outs[best]);
}
return true;
}
virtual void OnUnitAttacked(const Unit* unit) final {
if (unit == bob && unit->shield <= 5) {
// evasive action
evade(bob);
} else if (unit->unit_type == UNIT_TYPEID::PROTOSS_PROBE) { //OnUnitAttacked only gives us our own units, so don't need "&& unit->alliance == Unit::Alliance::Self"
auto list = Observation()->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_PROBE));
int att = 0;
for (auto unit : list) {
for (auto order : unit->orders) {
if (order.ability_id == ABILITY_ID::ATTACK_ATTACK) {
att++;
}
}
}
const auto & tpos = (nexus == nullptr) ? unit->pos : nexus->pos;
Units close = FindEnemiesInRange(tpos, 5);
if (att < 2*close.size() && att <= list.size() *.75f ) {
if (bob != nullptr) list.erase(std::remove(list.begin(), list.end(), bob), list.end());
auto targets = FindEnemiesInRange(tpos, 6);
//auto reaper = FindNearestEnemy(Observation()->GetStartLocation());
auto reaper = FindWeakestUnit(targets);
float sum = 0;
for (const auto & p : list) {
sum += p->health + p->shield;
}
sum /= list.size();
// the probes with less than half of average life are pulled
list.erase(
std::remove_if(list.begin(), list.end(), [sum](const Unit * p) { return p->health + p->shield <= sum / 2; })
,list.end());
sortByDistanceTo(list, reaper->pos);
std::sort(list.begin(), list.end(), [](const Unit * a, const Unit *b) { return a->health + a->shield > b->health + b->shield; });
if (list.size() > 3)
list.resize(3);
if (reaper != nullptr) {
if (close.size() == 1 && reaper->unit_type == UNIT_TYPEID::TERRAN_SCV || reaper->unit_type == UNIT_TYPEID::ZERG_DRONE || reaper->unit_type == UNIT_TYPEID::PROTOSS_PROBE) {
list.resize(1);
//Actions()->UnitCommand(nexus, ABILITY_ID::TRAIN_PROBE, true);
}
Actions()->UnitCommand(list, ABILITY_ID::ATTACK_ATTACK, reaper->pos);
//std::for_each(list.begin(), list.end(), [workerStates](auto worker) {workerStates.insert_or_assign(worker, WorkerState::Attacking);}); //for_each's lambda can't reference Globals!! blah!
for (auto worker: list)
{
workerStates.insert_or_assign(worker->tag, WorkerState::Attacking);
}
}
}
if (unit->shield == 0 && nexus != nullptr) {
const auto & nmy = FindNearestUnit(unit->pos, close);
if (nmy != nullptr) {
auto v = unit->pos - nmy->pos;
v /= Distance2D(Point2D(0, 0), v);
v *= 3.0f;
Actions()->UnitCommand(unit, ABILITY_ID::SMART, FindNearestMineralPatch(unit->pos +v));
}
else {
Actions()->UnitCommand(unit, ABILITY_ID::SMART, FindNearestMineralPatch(tpos ));
}
}
}
else if (IsArmyUnitType(unit->unit_type)) { //unit->unit_type == UNIT_TYPEID::PROTOSS_ZEALOT || unit->unit_type == UNIT_TYPEID::PROTOSS_STALKER) {
if (unit->health >= 20 && unit->shield < 25) {
auto nmy = FindNearestEnemy(unit->pos);
auto vec = unit->pos - nmy->pos;
Actions()->UnitCommand(unit, ABILITY_ID::MOVE, unit->pos + (vec / 2));
//std::cout << "ouch run away" << std::endl;
}
else Actions()->UnitCommand(unit, ABILITY_ID::ATTACK_ATTACK, unit->pos);
//is this "call for backup"???
for (auto friendly : FindFriendliesInRange(unit->pos, 20.0f)) {
if (IsArmyUnitType(friendly->unit_type)) { //friendly->unit_type == UNIT_TYPEID::PROTOSS_ZEALOT || unit->unit_type == UNIT_TYPEID::PROTOSS_STALKER) {
OnUnitHasAttacked(friendly); //is this supposed to be "unit has been attacked"??
}
}
}
else if (IsBuilding(unit->unit_type) && unit->build_progress < 1.0f) { //?this will be triggered once when building reaches full progress, since last turn it didn't have full health and this turn its build_progress is 100%
if (unit->health < 30 || unit->build_progress >= 0.95 && (unit->health + unit->shield) / (unit->health_max + unit->shield_max) < 0.6) {
Actions()->UnitCommand(unit,ABILITY_ID::CANCEL);
}
}
else { //is this "call for backup"???
for (auto friendly : FindFriendliesInRange(unit->pos, 20.0f)) {
if (IsArmyUnitType(friendly->unit_type)) { //friendly->unit_type == UNIT_TYPEID::PROTOSS_ZEALOT || unit->unit_type == UNIT_TYPEID::PROTOSS_STALKER) {
OnUnitHasAttacked(friendly); //is this supposed to be "unit has been attacked"??
}
}
}
}
virtual void OnUnitEnterVision(const Unit* u) final {
if (target == proxy && u->alliance == Unit::Alliance::Enemy && u->health_max >= 200 && !u->is_flying) { //health_max > 200 means a building, basically. not just a worker/Tier1scout
auto pottarget = map.FindNearestBase(u->pos);
if (Distance2D(pottarget, target) < 20)
target = pottarget;
else target = u->pos;
if (scout != nullptr) OnUnitIdle(scout);
}
int lastTurnEnemyStrength = estimateEnemyStrength();
if (u->alliance == Unit::Alliance::Enemy) {
enemies.insert_or_assign(u->tag,u);
}
int currentTurnEnemyStrength = estimateEnemyStrength();
//don't use //switch to GameCommander battle command
/*if (currentTurnEnemyStrength >= 5 && lastTurnEnemyStrength < 5) {
for (auto u : Observation()->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_ZEALOT))) {
OnUnitIdle(u);
}
for (auto u : Observation()->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_STALKER))) {
OnUnitIdle(u);
}
for (auto u : Observation()->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_ADEPT))) {
OnUnitIdle(u);
}
for (auto u : Observation()->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_SENTRY))) {
OnUnitIdle(u);
}
}*/
}
int enemiesKilled = 0; //or should be enemy supply? (about 50min per supply, better generally, without getting exact)
int enemySupplyKilled = 0;
int enemyVespeneCostDestroyed = 0;
int enemyMineralCostDestroyed = 0;
int alliesKilled = 0;
int allySupplyKilled = 0;
int allyMineralCostDestroyed = 0;
int allyVespeneCostDestroyed = 0;
virtual void OnUnitDestroyed(const Unit* unit) final {
UnitTypes all_unit_data = Observation()->GetUnitTypeData();
UnitTypeData unit_data = all_unit_data.at(static_cast<uint32_t>(unit->unit_type));
int mineral_cost = unit_data.mineral_cost;
int vespene_cost = unit_data.vespene_cost;
int supply_cost = unit_data.food_required;
if (unit->alliance == Unit::Alliance::Enemy) { //keep of list of enemys killed, their types, and total resource-costs. unit->unit_type)
enemies.erase(unit->tag);
enemiesKilled += 1;
enemySupplyKilled += supply_cost;
enemyMineralCostDestroyed += mineral_cost;
enemyVespeneCostDestroyed += vespene_cost;
}
else {
alliesKilled += 1;
allySupplyKilled += supply_cost;
allyMineralCostDestroyed += mineral_cost;
allyVespeneCostDestroyed += vespene_cost;
}
if (bob == unit) {
bob = nullptr;
for (auto probe : Observation()->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_PROBE))) {
if (probe->is_alive) {
bob = probe;
workerStates.insert_or_assign(bob->tag, WorkerState::MovingToBuild);
break;
}
}
auto nmy = Observation()->GetUnits(Unit::Alliance::Enemy, [this] (const Unit & u) { return Distance2D(u.pos, proxy) < 10.0f; } );
bool move = false;
int att = 0;
for (const auto & u : nmy) {
if (isStaticDefense(u->unit_type)) {
move = true;
}
if (IsArmyUnitType(u->unit_type)) {
att++;
}
}
if (move || att >= Observation()->GetArmyCount() || nmy.size() >= 8 || CountUnitType(UNIT_TYPEID::PROTOSS_GATEWAY) < 2) { //(CountUnitType(UNIT_TYPEID::PROTOSS_ZEALOT) + CountUnitType(UNIT_TYPEID::PROTOSS_STALKER))
proxy = map.getPosition(MapTopology::ally, MapTopology::main);
}
}
else if (nexus == unit) {
nexus = nullptr;
}
else if (unit->unit_type == UNIT_TYPEID::PROTOSS_PROBE && unit->alliance == Unit::Alliance::Self) {
auto list = Observation()->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_PROBE));
list.erase(std::remove(list.begin(), list.end(), bob), list.end());
auto reaper = FindNearestEnemy(Observation()->GetStartLocation());
list.resize(3); //take 3 attack-workers by default
if (reaper != nullptr) { //if it isn't a reaper
if (reaper->unit_type == UNIT_TYPEID::TERRAN_SCV) {
list.resize(2); //only take 2 for a harrassing-worker
//Actions()->UnitCommand(nexus, ABILITY_ID::TRAIN_PROBE, true);
}
Actions()->UnitCommand(list, ABILITY_ID::ATTACK_ATTACK, reaper->pos);
}
}
else if (unit->alliance == Unit::Alliance::Enemy && IsCommandStructure(unit->unit_type)) {
if (Distance2D(target, unit->pos) < 20) {
enemyBaseRazed = true; //cleanup now?
}
}
}
const Unit* FindWeakestUnit(const Units & units) {
float maxhp = FLT_MAX; //std::numeric_limits<float>::max(); //template was throwing errors for some reason
const Unit* targete = nullptr;
for (const auto& u : units) {
float hp = u->health + u->shield;
if (hp < maxhp) {
maxhp = hp;
targete = u;
}
}
return targete;
}
// default max is quite large, it amounts to roughly 15 game unit i.e. a circle roughly the surface of a base
const Unit* FindNearestUnit(const Point2D& start, const Units & units, float maxRangeSquared = 200.0f) {
float distance = FLT_MAX; //std::numeric_limits<float>::max(); //template was throwing errors for some reason
const Unit* targete = nullptr;
for (const auto& u : units) {
//if (u->unit_type == UNIT_TYPEID::) {
float d = DistanceSquared2D(u->pos, start);
if (d < distance && d <= maxRangeSquared) {
distance = d;
targete = u;
}
//}
}
if (distance <= maxRangeSquared) {
return targete;
}
return nullptr;
}
const Unit* FindNearestEnemy(const Point2D& start) {
return FindNearestUnit(start, Observation()->GetUnits(Unit::Alliance::Enemy));
}
const sc2::Unit* FindNearestTownHall(sc2::Point3D point) {
const sc2::Units townHalls = Observation()->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_NEXUS));
if (townHalls.size() == 0) return nullptr;
auto compareFunc = [point](const sc2::Unit* a, const sc2::Unit* b) { return Distance2D(a->pos, point) < Distance2D(b->pos, point);};
auto closestTownHall = std::min_element(townHalls.begin(), townHalls.end(), compareFunc);
return *closestTownHall; //this is an iterator, so have to dereference first
}
enum WorkerState {
MovingToMineral, //in-transit to mineral-crystal
GatheringMineral, //actively mining the crystal with ability
ReturningMineral, //returning cargo to the nearest TownHall
GatheringGas, //getting that sweet Vespene
ReturningGas, //returning gas to townHall
MovingToBuild, //moving to a location to build-structure
MovingToScout, //scouting around for info's
Attacking, //fight on to Valhalla!
Busy, //doing something important and don't bother me with mineral-gathering commands!
Idle, //no idea what I should do now
numWorkerStates //number of current SCV states
};
std::unordered_map<sc2::Tag, sc2::Tag> workerAssignedMinerals; //for each worker, which crystal are they assigned? (workerTag,mineralTag)
std::unordered_map<sc2::Tag, sc2::Point2D> magicSpots; //for each crystal, where is the magic spot?
std::unordered_map<sc2::Tag, WorkerState> workerStates; //what each worker is doing ('task', not 'job')
sc2::Point2D calcMagicSpot(const sc2::Unit* mineral) {
const sc2::Unit* closestTH = FindNearestTownHall(mineral->pos);
if (closestTH == nullptr) return sc2::Point3D(0, 0, 0); //in case there are no TownHalls left (or they're flying :)
//must give a position right in front of crystal, closest to base //base location??
float offset = 0.1f, xOffset, yOffset;
Point2D magicSpot;
/*float tx = closestTH->pos.x, ty = closestTH->pos.y;
float mx = mineral->pos.x, my = mineral->pos.y;
if (tx > mx) magicSpot.x = (tx - mx) * 0.1f;
else magicSpot.x = mineral->pos.x - offset;
if (ty > my) magicSpot.y = mineral->pos.y + offset;
else magicSpot.y = mineral->pos.y - offset;*/
if (closestTH->pos.x < 60.0f) xOffset = 0.1f; else xOffset = -0.1f;
if (closestTH->pos.y < 60.0f) yOffset = 0.1f; else yOffset = -0.1f;
return Point2D(mineral->pos.x + xOffset, mineral->pos.y + yOffset); //magicSpot
}
//manage mining-workers' behaviors
void workersOnStep(sc2::Units workers) {
//if harvesting or moving-to-magicSpot, continue behavior. keep pairings. switch to GATHER when close-enough
for (auto worker : workers) {
sc2::Tag targetTag = workerAssignedMinerals[worker->tag];
const sc2::Unit* targetMineral = Observation()->GetUnit(targetTag);
auto workerState = workerStates[worker->tag];
if (targetMineral == nullptr) continue; //don't have a targetMineral, so not a mineralWorker
if (magicSpots[targetMineral->tag] == sc2::Point3D(0, 0, 0))
{
const sc2::Point2D magicSpot = calcMagicSpot(targetMineral);
magicSpots.insert_or_assign(targetMineral->tag, magicSpot);
}
Point2D magicSpot = magicSpots[targetMineral->tag];
if (workerState > WorkerState::ReturningMineral) continue; //ignore all non-miner tasks
if (IsCarryingMinerals(*worker)) { //function wants a reference, so derefence the pointer
workerState = WorkerState::ReturningMineral;
}
if (IsCarryingVespene(*worker)) { //function wants a reference, so derefence the pointer
workerState = WorkerState::ReturningGas;
}
if (workerState == MovingToMineral) { //on the way to the crystal
float gatherDist = (float)1.7;
if (Distance2D(worker->pos, targetMineral->pos) < gatherDist //if close enough to magicSpot, gather from mineral
|| Distance2D(worker->pos, magicSpot) < gatherDist) //if close enough to a mineral, start gathering from it //kind of redundant, but matters if worker approaches from behind or side
{
workerStates.insert_or_assign(worker->tag, WorkerState::GatheringMineral);
Actions()->UnitCommand(worker, ABILITY_ID::SMART, targetMineral);
continue;
}
Actions()->UnitCommand(worker, ABILITY_ID::MOVE, magicSpot); //keep clicking!
continue;
}
if (workerState == GatheringMineral) //return-min, start-gather, or stay-on-target
{
if (IsCarryingMinerals(*worker)) //we got what we came for, head back
{
workerStates.insert_or_assign(worker->tag, WorkerState::ReturningMineral);
Actions()->UnitCommand(worker, sc2::ABILITY_ID::HARVEST_RETURN);
continue;
}
if (worker->orders.empty()) //no minerals, why not gathering from target?? //this shouldn't happen, as GatheringMineral should
{
Actions()->UnitCommand(worker, ABILITY_ID::SMART, targetMineral);
continue;
}
if (worker->orders[0].ability_id == sc2::ABILITY_ID::HARVEST_GATHER) //keep worker unit at its mineral field