-
Notifications
You must be signed in to change notification settings - Fork 0
/
raw_base_agent.py
2352 lines (2043 loc) · 117 KB
/
raw_base_agent.py
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 os
import numpy as np
import random as rd
import itertools
import cv2
import scipy
from pysc2.agents import base_agent
from pysc2.lib import actions, buffs, features, units, upgrades
from pysc2.lib.named_array import NamedNumpyArray
from memory import Memory
from settings import RESOLUTION, THRESHOLD, CAP_MINERALS, CAP_GAS, ATTACK_PRIORITY, STEP_MUL
FUNCTIONS = actions.FUNCTIONS
RAW_FUNCTIONS = actions.RAW_FUNCTIONS
class RawAgent(base_agent.BaseAgent):
def __init__(self):
super().__init__()
self.agent_name = self.__class__.__name__
self.raw_interface = True
self.episode_length = None
self.log = None # debug tool
self.game_step = 0
self.action = None
self.enemy_coordinates = None
self.dists_first_base = None
self.memory = Memory(self)
def reset(self):
super().reset()
if self.log is not None:
self.log.close()
self.log = open(f'{os.path.abspath(os.getcwd())}'
f'\\data\\logs\\log_{self.__class__.__name__}_game_{self.episodes-1}.txt', 'w')
self.game_step = 0
self.dists_first_base = None
self.memory = Memory(self)
def step(self, obs):
super().step(obs)
self.obs = obs
self.memory.update(self.obs)
if obs.first():
self.log.write('### Game log ###')
# Get enemy spawn coordinates
self.self_coordinates = self.memory.base_locations[0]
self.enemy_coordinates = np.subtract(RESOLUTION - 1, self.self_coordinates)
# Log data
if not obs.first():
self.log.write(f'\nChose action {str(self.action.function.name)}, args {self.action.arguments}')
self.log.write(f'\n\nTime step {self.game_step}')
self.log.write(f'\nResources : {self.obs.observation.player.minerals}, '
f'{self.obs.observation.player.vespene}')
self.log.write(f'\nSupply : {self.obs.observation.player.food_used}'
f'/{self.obs.observation.player.food_cap}')
self.log.write(f'\nLarvae : {self.unit_count_by_type(units.Zerg.Larva)}')
self.action = None
self.game_step += 1
# Core methods
def unit_count_by_type(self, unit_type):
return len(self.get_units_by_type(unit_type))
def get_units_by_type(self, unit_type, from_raw=False):
if from_raw:
unit_types = self.obs.observation.raw_units[:, features.FeatureUnit.unit_type]
res = self.obs.observation.raw_units[unit_types == unit_type]
res = res[res[:, features.FeatureUnit.alliance] != features.PlayerRelative.ENEMY]
return [u for u in res]
if unit_type in self.memory.self_units:
return self.memory.self_units[unit_type]
if unit_type in self.memory.neutral_units:
return self.memory.neutral_units[unit_type]
return []
def get_bases(self, how='all'):
if how == 'all':
return self.get_units_by_type(units.Zerg.Hatchery) \
+ self.get_units_by_type(units.Zerg.Lair) \
+ self.get_units_by_type(units.Zerg.Hive) \
+ self.get_units_by_type(units.Protoss.Nexus) \
+ self.get_units_by_type(units.Terran.CommandCenter) \
+ self.get_units_by_type(units.Terran.CommandCenterFlying) \
+ self.get_units_by_type(units.Terran.OrbitalCommand) \
+ self.get_units_by_type(units.Terran.OrbitalCommandFlying) \
+ self.get_units_by_type(units.Terran.PlanetaryFortress)
else:
if not isinstance(how, list):
how = [how]
return [self.get_base(i) for i in how]
def get_base(self, how=1):
return [b for b in self.get_bases() if (b.x, b.y) == self.memory.base_locations[how - 1]][0]
def get_workers(self):
return self.get_units_by_type(units.Zerg.Drone) \
+ self.get_units_by_type(units.Protoss.Probe) \
+ self.get_units_by_type(units.Terran.SCV)
def get_minerals(self, from_raw=True):
return list(itertools.chain.from_iterable(
[self.get_units_by_type(getattr(units.Neutral, attr), from_raw=from_raw)
for attr in dir(units.Neutral) if 'MineralField' in attr]))
def get_vespenes(self, from_raw=True, include_built=False, separate=False):
vespenes = list(itertools.chain.from_iterable(
[self.get_units_by_type(getattr(units.Neutral, attr), from_raw=from_raw)
for attr in dir(units.Neutral) if 'Geyser' in attr and 'Rich' not in attr]))
# Rich extractors not recognized by pysc2 ; ignored
if include_built and not separate:
return vespenes
extractors = self.get_units_by_type(units.Zerg.Extractor) \
+ self.get_units_by_type(units.Zerg.ExtractorRich) \
+ self.get_units_by_type(units.Protoss.Assimilator) \
+ self.get_units_by_type(units.Protoss.AssimilatorRich) \
+ self.get_units_by_type(units.Terran.Refinery) \
+ self.get_units_by_type(units.Terran.RefineryRich)
free = [all([(v.x, v.y) != (e.x, e.y) for e in extractors]) for v in vespenes]
free_vespenes = [v for i, v in enumerate(vespenes) if free[i]]
if not include_built:
return free_vespenes
built_vespenes = [v for i, v in enumerate(vespenes) if not free[i]]
return free_vespenes, built_vespenes
def get_premade_coordinates(self, coordinates):
if coordinates == 'proxy':
out_coordinates = 0.2 * np.array(self.self_coordinates) \
+ 0.8 * np.array(self.enemy_coordinates)
started_on_top_right = np.sign(np.subtract(*self.self_coordinates))
out_coordinates += 0.6 * out_coordinates.min() * started_on_top_right
elif coordinates == 'home':
out_coordinates = 0.7 * np.array(self.self_coordinates) \
+ 0.3 * np.array(self.enemy_coordinates)
elif coordinates == 'enemy':
out_coordinates = self.enemy_coordinates
elif coordinates == 'enemy_far':
out_coordinates = -0.07 * np.array(self.self_coordinates) \
+ 1.07 * np.array(self.enemy_coordinates)
elif coordinates == 'enemy_close':
out_coordinates = 0.07 * np.array(self.self_coordinates) \
+ 0.93 * np.array(self.enemy_coordinates)
elif coordinates == 'self':
out_coordinates = self.self_coordinates
elif coordinates == 'middle':
out_coordinates = np.array([RESOLUTION / 2, RESOLUTION / 2])
return tuple(np.array(out_coordinates).astype(int))
def get_true_buildable_map(self, action):
# Create the matrix of possible locations
creep_constraint = np.ones((RESOLUTION, RESOLUTION))
if self.race_name == 'zerg' and action != RAW_FUNCTIONS.Build_Hatchery_pt:
creep_constraint = self.obs.observation.feature_minimap.creep
player_relative = self.obs.observation.feature_minimap.player_relative
visibility_constraint = np.ones((RESOLUTION, RESOLUTION))
diam_neutral = int(THRESHOLD * 0.48) # unbuildable border around minerals / vespene
if action in [RAW_FUNCTIONS.Build_CreepTumor_Queen_pt,
RAW_FUNCTIONS.Build_CreepTumor_Tumor_pt]:
visibility_constraint = self.obs.observation.feature_minimap.visibility_map == features.Visibility.VISIBLE
diam_neutral = 1
can_build = np.stack([self.obs.observation.feature_minimap.pathable,
self.obs.observation.feature_minimap.buildable,
# should be improved to not let flying units block :
(player_relative == 0).astype('uint8'),
cv2.erode(np.array(player_relative != features.PlayerRelative.NEUTRAL)
.astype('uint8'),
np.ones((diam_neutral, diam_neutral))),
creep_constraint,
visibility_constraint]).all(axis=0).T.astype('uint8')
diam = int(THRESHOLD * 0.28) # approximate standard building size
if action in [RAW_FUNCTIONS.Build_CommandCenter_pt,
RAW_FUNCTIONS.Build_Nexus_pt,
RAW_FUNCTIONS.Build_Hatchery_pt]:
diam = int(THRESHOLD * 0.38) # approximate base building size
elif action in [RAW_FUNCTIONS.Build_CreepTumor_Queen_pt,
RAW_FUNCTIONS.Build_CreepTumor_Tumor_pt]:
diam = int(THRESHOLD * 0.12)
can_build = cv2.erode(can_build, np.ones((diam, diam)))
return can_build
def do(self, action, *args):
return action(*args)
# Base actions
def build(self, action, builder=None, how=1, where='random'):
if isinstance(builder, list):
builders = list(itertools.chain.from_iterable(
[self.get_units_by_type(unit_type) for unit_type in builder]))
elif builder is None:
builders = self.get_workers()
else:
builders = self.get_units_by_type(builder)
builders_available = [b for b in builders if b.order_id_0 == RAW_FUNCTIONS.no_op.id]
if not builders_available:
builders_available = [b for b in builders if b.order_id_0 in
[RAW_FUNCTIONS.Harvest_Gather_unit.id,
RAW_FUNCTIONS.Harvest_Gather_Drone_unit.id,
RAW_FUNCTIONS.Harvest_Gather_Mule_unit.id,
RAW_FUNCTIONS.Harvest_Gather_Probe_unit.id,
RAW_FUNCTIONS.Harvest_Gather_SCV_unit.id,
RAW_FUNCTIONS.Harvest_Return_quick.id,
RAW_FUNCTIONS.Harvest_Return_Drone_quick.id,
RAW_FUNCTIONS.Harvest_Return_Mule_quick.id,
RAW_FUNCTIONS.Harvest_Return_Probe_quick.id,
RAW_FUNCTIONS.Harvest_Return_SCV_quick.id,]]
builders = builders_available
if not builders and not (isinstance(how, int) and how > 50):
return None # keep looking for an action to take
# Choose target location / tag
if where == 'random': # tag target cannot be random, must be deterministic
can_build = self.get_true_buildable_map(action)
# Choose the marker point
if how == 'base':
minerals = self.get_minerals()
bases = self.get_bases()
def shortest_path(grid, targets, max_lookup):
wall = 0 # wall value in the pathable matrix
dist_matrix = np.zeros_like(grid).astype(float) - 1
dist = 0
for t in targets:
dist_matrix[t] = dist
edge = targets
while edge and dist < max_lookup:
new_edge = []
for x, y in edge:
for x2, y2 in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]:
# Not a wall and not seen :
if 0 <= x2 < RESOLUTION and 0 <= y2 < RESOLUTION \
and grid[x2, y2] != wall and dist_matrix[x2, y2] < 0:
dist_matrix[x2, y2] = dist + 1
new_edge.append((x2, y2))
dist += 1
edge = new_edge
dist_matrix[dist_matrix == -1] = np.inf
diam_neutral = int(THRESHOLD * 0.48) # unbuildable border around minerals / vespene
dist_matrix = np.maximum(dist_matrix, int(diam_neutral / 2))
return dist_matrix
# Select a marker point x, y :
pathable = np.stack([self.obs.observation.feature_minimap.pathable.T,
(self.obs.observation.feature_minimap.player_id > 0).T]).any(axis=0)
if self.dists_first_base is None: # only computed once
self.dists_first_base = shortest_path(pathable, [self.memory.base_locations[0]],
max_lookup=RESOLUTION**2)
dists_all_bases = np.sqrt([[(m.x - b.x)**2 + (m.y - b.y)**2 for b in bases]
for m in minerals])
if bases:
dists_all_bases = np.min(dists_all_bases, axis=1)
else:
dists_all_bases = np.zeros(len(minerals)) + np.inf
minerals = [m for i, m in enumerate(minerals) if dists_all_bases[i] > THRESHOLD]
if not minerals:
return None
dists_first_base = [self.dists_first_base[m.x, m.y] for m in minerals]
chosen_mineral = minerals[np.argmin(dists_first_base)]
x, y = chosen_mineral.x, chosen_mineral.y
# Build a score for proximity to minerals :
minerals_vespenes = self.get_minerals() \
+ self.get_vespenes(include_built=True)
dists = [(m.x - x)**2 + (m.y - y)**2 for m in minerals_vespenes]
# Select minerals and vespenes in the line :
minerals_vespenes = [minerals_vespenes[i] for i in np.argsort(dists)[:10]]
x, y = np.median([[m.x, m.y] for m in minerals_vespenes], axis=0).astype(int)
path_dists = shortest_path(pathable, [(x, y)], max_lookup=int(THRESHOLD * 1.5))
best_spots = np.exp(-THRESHOLD * 0.0025 * path_dists)
else:
base = how if how < 50 else 1
if len(self.get_bases()) < base:
return None
x, y = self.memory.base_locations[base - 1]
best_spots = None # use closest
# Find the best location near the marker point
n = int(THRESHOLD * 2)
can_build[:max(x-n, 0), :] = can_build[min(x+n, RESOLUTION-1):, :] \
= can_build[:, :max(y-n, 0)] = can_build[:, min(y+n, RESOLUTION-1):] = 0
candidates = np.argwhere(can_build == 1)
if candidates.size == 0:
return None
if best_spots is None:
scores = [-(c[0] - x)**2 - (c[1] - y)**2 for c in candidates]
else:
scores = best_spots[candidates[:, 0], candidates[:, 1]]
target = tuple(candidates[np.argmax(scores)])
else: # where is the location, or tag, of the target unit
target = where
# Choose builder
if how == 'base':
x, y = target if where == 'random' \
else self.memory.base_locations[max(len(self.get_bases()) - 1, 0)]
dists = [(b.x - x)**2 + (b.y - y)**2 for b in builders]
picked = builders[np.argmin(dists)]
tag = picked.tag
elif how < 50: # how is the number of the base to train from
x, y = self.memory.base_locations[how - 1]
dists = [(b.x - x)**2 + (b.y - y)**2 for b in builders]
picked = builders[np.argmin(dists)]
tag = picked.tag
else: # how is the tag of the builder
tag = how
return self.do(action, 'now', tag, target)
def train(self, action, trainer, how='random'):
select_all = action in [RAW_FUNCTIONS.Train_Zergling_quick,
RAW_FUNCTIONS.Train_Baneling_quick,
RAW_FUNCTIONS.Morph_Ravager_quick,
RAW_FUNCTIONS.Train_Roach_quick]
if isinstance(trainer, list):
trainers = list(itertools.chain.from_iterable(
[self.get_units_by_type(unit_type) for unit_type in trainer]))
else:
trainers = self.get_units_by_type(trainer)
trainers = [t for t in trainers if t.build_progress == 100]
trainers_available = [t for t in trainers if t.order_id_0 == RAW_FUNCTIONS.no_op.id]
if not trainers_available:
trainers_available = [t for t in trainers if t.order_id_0 in
[RAW_FUNCTIONS.Move_pt.id,
RAW_FUNCTIONS.Move_unit.id,
RAW_FUNCTIONS.Move_Move_pt.id,
RAW_FUNCTIONS.Move_Move_unit.id,
RAW_FUNCTIONS.Attack_pt.id,
RAW_FUNCTIONS.Attack_unit.id,
RAW_FUNCTIONS.Attack_Attack_pt.id,
RAW_FUNCTIONS.Attack_Attack_unit.id,
RAW_FUNCTIONS.Attack_AttackBuilding_pt.id,
RAW_FUNCTIONS.Attack_AttackBuilding_unit.id,
RAW_FUNCTIONS.Attack_Redirect_pt.id,
RAW_FUNCTIONS.Attack_Redirect_unit.id]]
trainers = trainers_available
if not trainers and not (isinstance(how, int) and how > 50):
return None # keep looking for an action to take
if select_all:
tag = [t.tag for t in trainers]
elif how == 'morph':
hps = [t.health + np.inf * (t.health <= 0) for t in trainers]
picked = trainers[np.argmin(hps)]
tag = picked.tag
elif how == 'random':
picked = rd.choice(trainers)
tag = picked.tag
elif how < 50: # how is the number of the base to train from
x, y = self.memory.base_locations[how - 1]
dists = [(t.x - x)**2 + (t.y - y)**2 for t in trainers]
picked = trainers[np.argmin(dists)]
tag = picked.tag
else: # how is the tag of the trainer
tag = how
return self.do(action, 'now', tag)
def cast(self, action, caster, target=('enemy', None), energy=0, how='random'):
# Filter casters
if isinstance(caster, list):
casters = list(itertools.chain.from_iterable(
[self.get_units_by_type(unit_type) for unit_type in caster]))
else:
casters = self.get_units_by_type(caster)
if not casters:
return None
casters = [c for c in casters if c.build_progress == 100 and c.energy >= energy]
if action == RAW_FUNCTIONS.Build_CreepTumor_Tumor_pt:
casters = [c for c in casters if c.time_alive * STEP_MUL >= 800
and c.tag not in self.memory.expired_tumors]
casters_available = [c for c in casters if c.order_id_0 == RAW_FUNCTIONS.no_op.id]
if not casters_available:
casters_available = [c for c in casters if c.order_id_0 in
[RAW_FUNCTIONS.Move_pt.id,
RAW_FUNCTIONS.Move_unit.id,
RAW_FUNCTIONS.Move_Move_pt.id,
RAW_FUNCTIONS.Move_Move_unit.id,
RAW_FUNCTIONS.Attack_pt.id,
RAW_FUNCTIONS.Attack_unit.id,
RAW_FUNCTIONS.Attack_Attack_pt.id,
RAW_FUNCTIONS.Attack_Attack_unit.id,
RAW_FUNCTIONS.Attack_AttackBuilding_pt.id,
RAW_FUNCTIONS.Attack_AttackBuilding_unit.id,
RAW_FUNCTIONS.Attack_Redirect_pt.id,
RAW_FUNCTIONS.Attack_Redirect_unit.id]]
casters = casters_available
if not casters:
return None # keep looking for an action to take
# Choose caster
if how == 'random':
picked = rd.choice(casters)
tag = picked.tag
else: # how is the tag of the trainer
tag = how
picked = [u for u in list(itertools.chain.from_iterable(self.memory.self_units.values()))
if u.tag == tag][0]
# Filter targets
alliance, target = target
if target == 'creep':
can_build = self.get_true_buildable_map(action)
y, x = np.ogrid[-picked.x:RESOLUTION - picked.x, -picked.y:RESOLUTION - picked.y]
mask = np.sqrt(x**2 + y**2) > int(0.7 * THRESHOLD)
can_build[mask] = 0
started_on_top_right = max(np.sign(np.subtract(*self.self_coordinates)),0)
if action == RAW_FUNCTIONS.Build_CreepTumor_Queen_pt:
base_x, base_y = self.self_coordinates
y, x = np.ogrid[-base_x:RESOLUTION - base_x, -base_y:RESOLUTION - base_y]
mask = np.sqrt(x**2 + y**2) > 4 * THRESHOLD
can_build[mask] = 0
elif action == RAW_FUNCTIONS.Build_CreepTumor_Tumor_pt:
if started_on_top_right:
can_build[picked.x:, :picked.y] = 0
else:
can_build[:picked.x, picked.y:] = 0
save = can_build.copy()
for t in [int(0.7 * THRESHOLD), int(0.5 * THRESHOLD), int(0.3 * THRESHOLD)]:
can_build = save.copy()
for u in self.get_units_agg('CreepTumor', with_training=True):
y, x = np.ogrid[-u.x:RESOLUTION - u.x, -u.y:RESOLUTION - u.y]
mask = np.sqrt(x**2 + y**2) <= t
can_build[mask] = 0
if can_build.sum() > 0:
break
candidates = np.argwhere(can_build == 1)
if candidates.size == 0:
self.memory.expired_tumors.add(picked.tag)
return None
if picked.tag not in self.memory.creep_tumor_tries:
self.memory.creep_tumor_tries[picked.tag] = 0
self.memory.creep_tumor_tries[picked.tag] += 1
if self.memory.creep_tumor_tries[picked.tag] > 5:
self.memory.expired_tumors.add(picked.tag)
return None
on_our_side = started_on_top_right == np.sign(np.subtract(picked.x, picked.y))
if on_our_side:
base_x, base_y = self.self_coordinates
scores = np.sqrt((candidates[:, 0] - base_x)**2 + (candidates[:, 1] - base_y)**2) \
+ np.minimum(np.sqrt(2) * RESOLUTION / 2
- np.sqrt((candidates[:, 0] - RESOLUTION / 2)**2
+ (candidates[:, 1] - RESOLUTION / 2)**2),
RESOLUTION / 2 * 0.75)
else:
base_x, base_y = self.enemy_coordinates
scores = -np.sqrt((candidates[:, 0] - base_x)**2 + (candidates[:, 1] - base_y)**2) \
+ np.minimum(np.sqrt(2) * RESOLUTION / 2
- np.sqrt((candidates[:, 0] - RESOLUTION / 2)**2
+ (candidates[:, 1] - RESOLUTION / 2)**2),
RESOLUTION / 2 * 0.75)
if action == RAW_FUNCTIONS.Build_CreepTumor_Tumor_pt:
creep_score_map = self.obs.observation.feature_minimap.creep.T
creep_prox = int(THRESHOLD * 0.3)
creep_score_map = 1 - cv2.erode(creep_score_map.astype('uint8'), np.ones((creep_prox, creep_prox)))
for i, (x, y) in enumerate(candidates):
scores[i] += RESOLUTION * 0.1 * creep_score_map[x, y]
skill_target = candidates[np.argmax(scores)]
skill_target = tuple(skill_target)
else:
if not isinstance(target, list):
target = [target]
if alliance == 'self':
candidates = list(itertools.chain.from_iterable(
[self.get_units_by_type(t) for t in target]))
elif alliance == 'enemy':
candidates = list(itertools.chain.from_iterable(
[self.memory.enemy_units[t] for t in target]))
elif alliance == 'neutral':
candidates = list(itertools.chain.from_iterable(
[self.memory.neutral_units[t] for t in target]))
else:
raise Warning(f'Unknown alliance : {alliance}')
candidates = [c for c in candidates if c.display_type == 1] # visible
if not candidates:
return None
dists = [(u.x - picked.x)**2 + (u.y - picked.y)**2 for u in candidates]
skill_target = candidates[np.argmin(dists)]
if action.name.endswith('unit'):
skill_target = skill_target.tag
else:
skill_target = (skill_target.x, skill_target.y)
return self.do(action, 'now', tag, skill_target)
def attack(self, attackers, coordinates=None, can_reach_ground=True, can_reach_air=True,
where='median', defend=False, defend_up_to=0.5, hunt=False):
busy = list(itertools.chain.from_iterable(self.memory.scouts.values()))
attackers = [u for u in attackers if u.tag not in busy]
if isinstance(coordinates, str):
coordinates = self.get_premade_coordinates(coordinates)
if not attackers:
return None
if can_reach_ground and can_reach_air:
prio = ATTACK_PRIORITY['All']
elif can_reach_ground:
prio = ATTACK_PRIORITY['Ground']
else:
prio = ATTACK_PRIORITY['Air']
if where == 'median':
army_x, army_y = np.median([[u.x, u.y] for u in attackers], axis=0)
else:
base_x, base_y = self.self_coordinates
dists = [np.abs(u.x - base_x) + np.abs(u.y - base_y) for u in attackers]
if where == 'head':
picked = attackers[np.argmax(dists)]
elif where == 'tail':
picked = attackers[np.argmin(dists)]
else:
raise Warning(f'Unknown army marker : {where}')
army_x, army_y = picked.x, picked.y
enemies = list(itertools.chain.from_iterable(self.memory.enemy_units.values()))
enemies = [u for u in enemies if u.unit_type in prio.keys()]
if defend:
self_diff = np.subtract(*self.self_coordinates)
enemy_diff = np.subtract(*self.enemy_coordinates)
target_diff = self_diff + defend_up_to * (enemy_diff - self_diff)
enemies = [u for u in enemies if np.sign(u.x - u.y - target_diff)
== np.sign(self_diff)]
dists = np.sqrt([(u.x - army_x)**2 + (u.y - army_y)**2 for u in enemies])
out_coordinates = None
visible = [u for i, u in enumerate(enemies)
if u.display_type == 1 and (dists[i] < 3 * THRESHOLD or defend)]
found_location = True
if visible:
priorities = [prio[u.unit_type] for u in visible]
candidates = [u for i, u in enumerate(visible) if priorities[i] == max(priorities)]
hps = [u.health for u in candidates]
picked = candidates[np.argmin(hps)]
out_coordinates = (picked.x, picked.y)
elif defend:
return None
else:
# Look for enemy units where we have an information on the position
if hunt:
candidates = [u for u in enemies if u.pos_tracked and u.display_type != 3]
if candidates:
dists = [(u.x - army_x)**2 + (u.y - army_y)**2 for u in candidates]
picked = candidates[np.argmin(dists)]
out_coordinates = (picked.x, picked.y)
else:
to_explore = np.stack([self.obs.observation.feature_minimap.buildable,
self.obs.observation.feature_minimap.visibility_map
== features.Visibility.HIDDEN]).all(axis=0).T
candidates = np.argwhere(to_explore == 1)
out_coordinates = tuple(rd.choice(candidates))
attackers = [u for u in attackers if u.order_id_0 == RAW_FUNCTIONS.no_op.id]
if not attackers:
return None
else:
out_coordinates = coordinates
if coordinates is None:
out_coordinates = self.enemy_coordinates
found_location = False
if not found_location:
dists = np.sqrt([(u.x - out_coordinates[0])**2 + (u.y - out_coordinates[1])**2
for u in attackers])
n_in_range = (dists < THRESHOLD / 5).sum()
if n_in_range >= min(4, len(attackers)):
return None
attackers = [u.tag for u in attackers]
return self.do(RAW_FUNCTIONS.Attack_pt, 'now', attackers, out_coordinates)
def move(self, units_to_move, coordinates='home'):
busy = list(itertools.chain.from_iterable(self.memory.scouts.values()))
units_to_move = [u for u in units_to_move if u.tag not in busy]
if isinstance(coordinates, str):
out_coordinates = self.get_premade_coordinates(coordinates)
else:
out_coordinates = coordinates
units_to_move = [u.tag for u in units_to_move]
if not units_to_move:
return None
return self.do(RAW_FUNCTIONS.Move_pt, 'now', units_to_move, out_coordinates)
def wait(self):
return self.do(RAW_FUNCTIONS.no_op)
class ZergAgent(RawAgent):
def __init__(self):
super().__init__()
self.race_name = 'zerg'
self.worker_type = units.Zerg.Drone
def step(self, obs):
super().step(obs)
self.check_rally_points_workers_hl()
# Core methods
def get_harvest_state(self, how=1):
dict_res = {}
x, y = self.memory.base_locations[how - 1]
free_vespenes, built_vespenes = self.get_vespenes(include_built=True, separate=True)
v_spots = free_vespenes + self.get_units_agg('Extractor', with_training=True)
dists = np.sqrt([(s.x - x)**2 + (s.y - y)**2 for s in v_spots])
v_spots = [s for i, s in enumerate(v_spots) if dists[i] < THRESHOLD]
neutral_vespenes = [s for s in v_spots if s.unit_type
not in [units.Zerg.Extractor, units.Zerg.ExtractorRich]]
dict_res['neutral_vespenes'] = neutral_vespenes
v_spots = [s for s in v_spots if s.unit_type
in [units.Zerg.Extractor, units.Zerg.ExtractorRich]]
linked_vespenes = [[v for v in free_vespenes + built_vespenes
if (v.x, v.y) == (s.x, s.y)][0] for s in v_spots]
dict_res['extractors'] = [NamedNumpyArray([s.tag,
s.build_progress == 100,
s.assigned_harvesters,
s.x,
s.y,
linked_vespenes[i].health],
['tag', 'is_built', 'assigned_harvesters',
'x', 'y', 'vespene_left'])
for i, s in enumerate(v_spots)]
m_spots = self.get_minerals()
dists = np.sqrt([(s.x - x)**2 + (s.y - y)**2 for s in m_spots])
m_spots = [s for i, s in enumerate(m_spots) if dists[i] < THRESHOLD]
dict_res['minerals'] = m_spots
base = self.get_base(how=how)
dict_res['base'] = base
return dict_res
def unit_count_agg(self, name, with_burrowed=True, with_training=True):
units_agg = self.get_units_agg(name, with_burrowed=with_burrowed, with_training=with_training)
if name == 'Zergling':
# 2 zerglings per cocoon
return len(units_agg) + sum([u.unit_type == units.Zerg.Cocoon for u in units_agg])
else:
return len(units_agg)
def get_units_agg(self, name, with_burrowed=True, with_training=False):
if name == 'Baneling':
res = self.get_units_by_type(units.Zerg.Baneling)
if with_burrowed:
res = res + self.get_units_by_type(units.Zerg.BanelingBurrowed)
if with_training:
res = res + self.get_units_by_type(units.Zerg.BanelingCocoon)
elif name == 'BroodLord':
res = self.get_units_by_type(units.Zerg.BroodLord)
if with_training:
res = res + self.get_units_by_type(units.Zerg.BroodLordCocoon)
elif name == 'Cocoon':
res = self.get_units_by_type(units.Zerg.Cocoon)
elif name == 'Corruptor':
res = self.get_units_by_type(units.Zerg.Corruptor)
if with_training:
res = res + [u for u in self.get_units_by_type(units.Zerg.Cocoon)
if u.order_id_0 == RAW_FUNCTIONS.Train_Corruptor_quick.id]
elif name == 'Drone':
res = self.get_units_by_type(units.Zerg.Drone)
if with_burrowed:
res = res + self.get_units_by_type(units.Zerg.DroneBurrowed)
if with_training:
res = res + [u for u in self.get_units_by_type(units.Zerg.Cocoon)
if u.order_id_0 == RAW_FUNCTIONS.Train_Drone_quick.id]
elif name == 'Hydralisk':
res = self.get_units_by_type(units.Zerg.Hydralisk)
if with_burrowed:
res = res + self.get_units_by_type(units.Zerg.HydraliskBurrowed)
if with_training:
res = res + [u for u in self.get_units_by_type(units.Zerg.Cocoon)
if u.order_id_0 == RAW_FUNCTIONS.Train_Hydralisk_quick.id]
elif name == 'Infestor':
res = self.get_units_by_type(units.Zerg.Infestor)
if with_burrowed:
res = res + self.get_units_by_type(units.Zerg.InfestorBurrowed)
if with_training:
res = res + [u for u in self.get_units_by_type(units.Zerg.Cocoon)
if u.order_id_0 == RAW_FUNCTIONS.Train_Infestor_quick.id]
elif name == 'Larva':
res = self.get_units_by_type(units.Zerg.Larva)
elif name == 'Lurker':
res = self.get_units_by_type(units.Zerg.Lurker)
if with_burrowed:
res = res + self.get_units_by_type(units.Zerg.LurkerBurrowed)
if with_training:
res = res + self.get_units_by_type(units.Zerg.LurkerCocoon)
elif name == 'Mutalisk':
res = self.get_units_by_type(units.Zerg.Mutalisk)
if with_training:
res = res + [u for u in self.get_units_by_type(units.Zerg.Cocoon)
if u.order_id_0 == RAW_FUNCTIONS.Train_Mutalisk_quick.id]
elif name == 'Overlord':
res = self.get_units_by_type(units.Zerg.Overlord) \
+ self.get_units_by_type(units.Zerg.OverlordTransport) \
+ self.get_units_by_type(units.Zerg.Overseer) \
+ self.get_units_by_type(units.Zerg.OverseerOversightMode)
if with_training:
res = res + [u for u in self.get_units_by_type(units.Zerg.Cocoon)
if u.order_id_0 == RAW_FUNCTIONS.Train_Overlord_quick.id] \
+ self.get_units_by_type(units.Zerg.OverlordTransportCocoon) \
+ self.get_units_by_type(units.Zerg.OverseerCocoon)
elif name == 'OverlordTransport':
res = self.get_units_by_type(units.Zerg.OverlordTransport)
if with_training:
res = res + self.get_units_by_type(units.Zerg.OverlordTransportCocoon)
elif name == 'Overseer':
res = self.get_units_by_type(units.Zerg.Overseer) \
+ self.get_units_by_type(units.Zerg.OverseerOversightMode)
if with_training:
res = res + self.get_units_by_type(units.Zerg.OverseerCocoon)
elif name == 'Queen':
res = self.get_units_by_type(units.Zerg.Queen)
if with_burrowed:
res = res + self.get_units_by_type(units.Zerg.QueenBurrowed)
if with_training:
res = res + [u for u in self.get_units_agg('Hatchery')
if u.order_id_0 == RAW_FUNCTIONS.Train_Queen_quick.id]
elif name == 'Ravager':
res = self.get_units_by_type(units.Zerg.Ravager)
if with_burrowed:
res = res + self.get_units_by_type(units.Zerg.RavagerBurrowed)
if with_training:
res = res + self.get_units_by_type(units.Zerg.RavagerCocoon)
elif name == 'Roach':
res = self.get_units_by_type(units.Zerg.Roach)
if with_burrowed:
res = res + self.get_units_by_type(units.Zerg.RoachBurrowed)
if with_training:
res = res + [u for u in self.get_units_by_type(units.Zerg.Cocoon)
if u.order_id_0 == RAW_FUNCTIONS.Train_Roach_quick.id]
elif name == 'SwarmHost':
res = self.get_units_by_type(units.Zerg.SwarmHost)
if with_burrowed:
res = res + self.get_units_by_type(units.Zerg.SwarmHostBurrowed)
if with_training:
res = res + [u for u in self.get_units_by_type(units.Zerg.Cocoon)
if u.order_id_0 == RAW_FUNCTIONS.Train_SwarmHost_quick.id]
elif name == 'Ultralisk':
res = self.get_units_by_type(units.Zerg.Ultralisk)
if with_burrowed:
res = res + self.get_units_by_type(units.Zerg.UltraliskBurrowed)
if with_training:
res = res + [u for u in self.get_units_by_type(units.Zerg.Cocoon)
if u.order_id_0 == RAW_FUNCTIONS.Train_Ultralisk_quick.id]
elif name == 'Viper':
res = self.get_units_by_type(units.Zerg.Viper)
if with_training:
res = res + [u for u in self.get_units_by_type(units.Zerg.Cocoon)
if u.order_id_0 == RAW_FUNCTIONS.Train_Viper_quick.id]
elif name == 'Zergling':
res = self.get_units_by_type(units.Zerg.Zergling)
if with_burrowed:
res = res + self.get_units_by_type(units.Zerg.ZerglingBurrowed)
if with_training:
res = res + [u for u in self.get_units_by_type(units.Zerg.Cocoon)
if u.order_id_0 == RAW_FUNCTIONS.Train_Zergling_quick.id]
elif name == 'BanelingNest':
res = self.get_units_by_type(units.Zerg.BanelingNest)
elif name == 'CreepTumor':
res = self.get_units_by_type(units.Zerg.CreepTumorBurrowed)
if not with_burrowed:
res = [u for u in res if u.tag not in self.memory.expired_tumors]
if with_training:
res = res + self.get_units_by_type(units.Zerg.CreepTumor) \
+ self.get_units_by_type(units.Zerg.CreepTumorQueen)
elif name == 'EvolutionChamber':
res = self.get_units_by_type(units.Zerg.EvolutionChamber)
elif name == 'Extractor':
res = self.get_units_by_type(units.Zerg.Extractor) \
+ self.get_units_by_type(units.Zerg.ExtractorRich)
elif name == 'Hatchery':
res = self.get_units_by_type(units.Zerg.Hatchery) \
+ self.get_units_by_type(units.Zerg.Lair) \
+ self.get_units_by_type(units.Zerg.Hive)
elif name == 'Lair':
res = self.get_units_by_type(units.Zerg.Lair) \
+ self.get_units_by_type(units.Zerg.Hive)
if with_training:
res = res + [u for u in self.get_units_by_type(units.Zerg.Hatchery)
if u.order_id_0 == RAW_FUNCTIONS.Morph_Lair_quick.id]
elif name == 'Hive':
res = self.get_units_by_type(units.Zerg.Hive)
if with_training:
res = res + [u for u in self.get_units_by_type(units.Zerg.Lair)
if u.order_id_0 == RAW_FUNCTIONS.Morph_Hive_quick.id]
elif name == 'HydraliskDen':
res = self.get_units_by_type(units.Zerg.HydraliskDen)
elif name == 'InfestationPit':
res = self.get_units_by_type(units.Zerg.InfestationPit)
elif name == 'LurkerDen':
res = self.get_units_by_type(units.Zerg.LurkerDen)
elif name == 'NydusCanal':
res = self.get_units_by_type(units.Zerg.NydusCanal)
elif name == 'NydusNetwork':
res = self.get_units_by_type(units.Zerg.NydusNetwork)
elif name == 'RoachWarren':
res = self.get_units_by_type(units.Zerg.RoachWarren)
elif name == 'SpawningPool':
res = self.get_units_by_type(units.Zerg.SpawningPool)
elif name == 'SpineCrawler':
res = self.get_units_by_type(units.Zerg.SpineCrawler) \
+ self.get_units_by_type(units.Zerg.SpineCrawlerUprooted)
elif name == 'Spire':
res = self.get_units_by_type(units.Zerg.Spire) \
+ self.get_units_by_type(units.Zerg.GreaterSpire)
elif name == 'GreaterSpire':
res = self.get_units_by_type(units.Zerg.GreaterSpire)
if with_training:
res = res + [u for u in self.get_units_by_type(units.Zerg.Spire)
if u.order_id_0 == RAW_FUNCTIONS.Morph_GreaterSpire_quick.id]
elif name == 'SporeCrawler':
res = self.get_units_by_type(units.Zerg.SporeCrawler) \
+ self.get_units_by_type(units.Zerg.SporeCrawlerUprooted)
elif name == 'UltraliskCavern':
res = self.get_units_by_type(units.Zerg.UltraliskCavern)
elif name == 'Burrow':
res = [True] if upgrades.Upgrades.Burrow in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('Hatchery')
if u.order_id_0 == RAW_FUNCTIONS.Research_Burrow_quick.id]
elif name == 'PneumatizedCarapace':
res = [True] if upgrades.Upgrades.PneumatizedCarapace in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('Hatchery')
if u.order_id_0 == RAW_FUNCTIONS.Research_PneumatizedCarapace_quick.id]
elif name == 'MetabolicBoost':
res = [True] if upgrades.Upgrades.MetabolicBoost in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('SpawningPool')
if u.order_id_0 == RAW_FUNCTIONS.Research_ZerglingMetabolicBoost_quick.id]
elif name == 'MeleeAttack1':
res = [True] if upgrades.Upgrades.ZergMeleeWeaponsLevel1 in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('EvolutionChamber')
if u.order_id_0 == RAW_FUNCTIONS.Research_ZergMeleeWeaponsLevel1_quick.id]
elif name == 'MeleeAttack2':
res = [True] if upgrades.Upgrades.ZergMeleeWeaponsLevel2 in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('EvolutionChamber')
if u.order_id_0 == RAW_FUNCTIONS.Research_ZergMeleeWeaponsLevel2_quick.id]
elif name == 'MeleeAttack3':
res = [True] if upgrades.Upgrades.ZergMeleeWeaponsLevel3 in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('EvolutionChamber')
if u.order_id_0 == RAW_FUNCTIONS.Research_ZergMeleeWeaponsLevel3_quick.id]
elif name == 'MissileAttack1':
res = [True] if upgrades.Upgrades.ZergMissileWeaponsLevel1 in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('EvolutionChamber')
if u.order_id_0 == RAW_FUNCTIONS.Research_ZergMissileWeaponsLevel1_quick.id]
elif name == 'MissileAttack2':
res = [True] if upgrades.Upgrades.ZergMissileWeaponsLevel2 in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('EvolutionChamber')
if u.order_id_0 == RAW_FUNCTIONS.Research_ZergMissileWeaponsLevel2_quick.id]
elif name == 'MissileAttack3':
res = [True] if upgrades.Upgrades.ZergMissileWeaponsLevel3 in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('EvolutionChamber')
if u.order_id_0 == RAW_FUNCTIONS.Research_ZergMissileWeaponsLevel3_quick.id]
elif name == 'GroundArmor1':
res = [True] if upgrades.Upgrades.ZergGroundArmorsLevel1 in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('EvolutionChamber')
if u.order_id_0 == RAW_FUNCTIONS.Research_ZergGroundArmorLevel1_quick.id]
elif name == 'GroundArmor2':
res = [True] if upgrades.Upgrades.ZergGroundArmorsLevel2 in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('EvolutionChamber')
if u.order_id_0 == RAW_FUNCTIONS.Research_ZergGroundArmorLevel2_quick.id]
elif name == 'GroundArmor3':
res = [True] if upgrades.Upgrades.ZergGroundArmorsLevel3 in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('EvolutionChamber')
if u.order_id_0 == RAW_FUNCTIONS.Research_ZergGroundArmorLevel3_quick.id]
elif name == 'FlyerAttack1':
res = [True] if upgrades.Upgrades.ZergFlyerWeaponsLevel1 in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('Spire')
if u.order_id_0 == RAW_FUNCTIONS.Research_ZergFlyerAttackLevel1_quick.id]
elif name == 'FlyerAttack2':
res = [True] if upgrades.Upgrades.ZergFlyerWeaponsLevel2 in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('Spire')
if u.order_id_0 == RAW_FUNCTIONS.Research_ZergFlyerAttackLevel2_quick.id]
elif name == 'FlyerAttack3':
res = [True] if upgrades.Upgrades.ZergFlyerWeaponsLevel3 in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('Spire')
if u.order_id_0 == RAW_FUNCTIONS.Research_ZergFlyerAttackLevel3_quick.id]
elif name == 'FlyerArmor1':
res = [True] if upgrades.Upgrades.ZergFlyerArmorsLevel1 in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('Spire')
if u.order_id_0 == RAW_FUNCTIONS.Research_ZergFlyerArmorLevel1_quick.id]
elif name == 'FlyerArmor2':
res = [True] if upgrades.Upgrades.ZergFlyerArmorsLevel2 in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('Spire')
if u.order_id_0 == RAW_FUNCTIONS.Research_ZergFlyerArmorLevel2_quick.id]
elif name == 'FlyerArmor3':
res = [True] if upgrades.Upgrades.ZergFlyerArmorsLevel3 in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('Spire')
if u.order_id_0 == RAW_FUNCTIONS.Research_ZergFlyerArmorLevel3_quick.id]
elif name == 'MuscularAugments':
res = [True] if upgrades.Upgrades.MuscularAugments in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('HydraliskDen')
if u.order_id_0 == RAW_FUNCTIONS.Research_MuscularAugments_quick.id]
elif name == 'GlialReconstitution':
res = [True] if upgrades.Upgrades.GlialReconstitution in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('RoachWarren')
if u.order_id_0 == RAW_FUNCTIONS.Research_GlialRegeneration_quick.id]
elif name == 'TunnelingClaws':
res = [True] if upgrades.Upgrades.TunnelingClaws in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('RoachWarren')
if u.order_id_0 == RAW_FUNCTIONS.Research_TunnelingClaws_quick.id]
elif name == 'CentrifugalHooks':
res = [True] if upgrades.Upgrades.CentrificalHooks in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('BanelingNest')
if u.order_id_0 == RAW_FUNCTIONS.Research_CentrifugalHooks_quick.id]
elif name == 'NeuralParasite':
res = [True] if upgrades.Upgrades.NeuralParasite in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('InfestationPit')
if u.order_id_0 == RAW_FUNCTIONS.Research_NeuralParasite_quick.id]
elif name == 'PathogenGlands':
res = [True] if upgrades.Upgrades.PathogenGlands in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('InfestationPit')
if u.order_id_0 == RAW_FUNCTIONS.Research_PathogenGlands_quick.id]
elif name == 'GroovedSpines':
res = [True] if upgrades.Upgrades.GroovedSpines in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('HydraliskDen')
if u.order_id_0 == RAW_FUNCTIONS.Research_GroovedSpines_quick.id]
elif name == 'AdrenalGlands':
res = [True] if upgrades.Upgrades.AdrenalGlands in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('SpawningPool')
if u.order_id_0 == RAW_FUNCTIONS.Research_ZerglingAdrenalGlands_quick.id]
elif name == 'ChitinousPlating':
res = [True] if upgrades.Upgrades.ChitinousPlating in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('UltraliskCavern')
if u.order_id_0 == RAW_FUNCTIONS.Research_ChitinousPlating_quick.id]
elif name == 'AnabolicSynthesis':
res = [True] if upgrades.Upgrades.AnabolicSynthesis in self.obs.observation.upgrades else []
if with_training:
res = res + [u for u in self.get_units_agg('UltraliskCavern')
if u.order_id_0 == RAW_FUNCTIONS.Research_AnabolicSynthesis_quick.id]
else:
raise Warning(f'Unknown unit name {name}')
if res and isinstance(res[0], bool):
return res
if not with_training:
res = [u for u in res if u.build_progress == 100]
return res
def get_army(self, unit_names='all', with_queen=False, with_drone=False):
if unit_names == 'all':
names = ['Baneling', 'BroodLord', 'Corruptor', 'Hydralisk', 'Infestor',
'Lurker', 'Mutalisk', 'OverlordTransport', 'Overseer',
'Ravager', 'Roach', 'SwarmHost', 'Ultralisk', 'Viper', 'Zergling']