This repository has been archived by the owner on Nov 29, 2020. It is now read-only.
forked from berak/ants-tcp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ants.py
1836 lines (1598 loc) · 70.5 KB
/
ants.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
#!/usr/bin/env python
from random import randrange, choice, shuffle, randint, seed, random
from math import sqrt
from collections import deque, defaultdict
from fractions import Fraction
import operator
from game import Game
from copy import deepcopy
try:
from sys import maxint
except ImportError:
from sys import maxsize as maxint
ANTS = 0
DEAD = -1
LAND = -2
FOOD = -3
WATER = -4
UNSEEN = -5
PLAYER_ANT = 'abcdefghij'
HILL_ANT = string = 'ABCDEFGHIJ'
PLAYER_HILL = string = '0123456789'
MAP_OBJECT = '?%*.!'
MAP_RENDER = PLAYER_ANT + HILL_ANT + PLAYER_HILL + MAP_OBJECT
HILL_POINTS = 2
RAZE_POINTS = -1
# possible directions an ant can move
AIM = {'n': (-1, 0),
'e': (0, 1),
's': (1, 0),
'w': (0, -1)}
# precalculated sqrt
SQRT = [int(sqrt(r)) for r in range(101)]
class Ants(Game):
def __init__(self, options=None):
# setup options
map_text = options['map']
self.turns = int(options['turns'])
self.loadtime = int(options['loadtime'])
self.turntime = int(options['turntime'])
self.viewradius = int(options["viewradius2"])
self.attackradius = int(options["attackradius2"])
self.spawnradius = int(options["spawnradius2"])
self.engine_seed = options.get('engine_seed', randint(-maxint-1, maxint))
self.player_seed = options.get('player_seed', randint(-maxint-1, maxint))
seed(self.engine_seed)
self.food_rate = options.get('food_rate', (5,11)) # total food
if type(self.food_rate) in (list, tuple):
self.food_rate = randrange(self.food_rate[0], self.food_rate[1]+1)
self.food_turn = options.get('food_turn', (19,37)) # per turn
if type(self.food_turn) in (list, tuple):
self.food_turn = randrange(self.food_turn[0], self.food_turn[1]+1)
self.food_start = options.get('food_start', (75,175)) # per land area
if type(self.food_start) in (list, tuple):
self.food_start = randrange(self.food_start[0], self.food_start[1]+1)
self.food_visible = options.get('food_visible', (3,5)) # in starting loc
if type(self.food_visible) in (list, tuple):
self.food_visible = randrange(self.food_visible[0], self.food_visible[1]+1)
self.food_extra = Fraction(0,1)
self.cutoff_percent = options.get('cutoff_percent', 0.85)
self.cutoff_turn = options.get('cutoff_turn', 150)
self.hill_kill = False # used to stall cutoff counter
self.do_attack = {
'focus': self.do_attack_focus,
'closest': self.do_attack_closest,
'support': self.do_attack_support,
'damage': self.do_attack_damage
}.get(options.get('attack'), self.do_attack_focus)
self.do_food = {
'none': self.do_food_none,
'random': self.do_food_random,
'sections': self.do_food_sections,
'symmetric': self.do_food_symmetric
}.get(options.get('food'), self.do_food_sections)
self.scenario = options.get('scenario', False)
map_data = self.parse_map(map_text)
self.turn = 0
self.num_players = map_data['num_players']
self.current_ants = {} # ants that are currently alive
self.killed_ants = [] # ants which were killed this turn
self.all_ants = [] # all ants that have been created
self.all_food = [] # all food created
self.current_food = {} # food currently in game
self.pending_food = defaultdict(int)
self.hills = {} # all hills
self.hive_food = [0]*self.num_players # food waiting to spawn for player
self.hive_history = [[0] for _ in range(self.num_players)]
# used to cutoff games early
self.cutoff = None
self.cutoff_bot = LAND # Can be ant owner, FOOD or LAND
self.cutoff_turns = 0
# used to calculate the turn when the winner took the lead
self.winning_bot = None
self.winning_turn = 0
# used to calculate when the player rank last changed
self.ranking_bots = None
self.ranking_turn = 0
# initialize size
self.height, self.width = map_data['size']
self.land_area = self.height*self.width - len(map_data['water'])
# initialize map
# this matrix does not track hills, just ants
self.map = [[LAND]*self.width for _ in range(self.height)]
# initialize water
for row, col in map_data['water']:
self.map[row][col] = WATER
# for new games
# ants are ignored and 1 ant is created per hill
# food is ignored
# for scenarios, the map file is followed exactly
# initialize hills
for owner, locs in map_data['hills'].items():
for loc in locs:
hill = self.add_hill(loc, owner)
if not self.scenario or len(map_data['ants']) == 0:
self.add_ant(hill)
if self.scenario:
# initialize ants
for player, player_ants in map_data['ants'].items():
for ant_loc in player_ants:
self.add_initial_ant(ant_loc, player)
# initialize food
for food in map_data['food']:
self.add_food(food)
self.original_map = []
for map_row in self.map:
self.original_map.append(map_row[:])
# initialize scores
# points start at # of hills to prevent negative scores
self.score = [len(map_data['hills'][0])]*self.num_players
self.bonus = [0]*self.num_players
self.score_history = [[s] for s in self.score]
# used to remember where the ants started
self.initial_ant_list = sorted(self.current_ants.values(), key=operator.attrgetter('owner'))
self.initial_access_map = self.access_map()
# cache used by neighbourhood_offsets() to determine nearby squares
self.offsets_cache = {}
# used to track dead players, ants may still exist, but orders are not processed
self.killed = [False for _ in range(self.num_players)]
# used to give a different ordering of players to each player
# initialized to ensure that each player thinks they are player 0
self.switch = [[None]*self.num_players + list(range(-5,0)) for i in range(self.num_players)]
for i in range(self.num_players):
self.switch[i][i] = 0
# used to track water and land already reveal to player
self.revealed = [[[False for col in range(self.width)]
for row in range(self.height)]
for _ in range(self.num_players)]
# used to track what a player can see
self.init_vision()
# the engine may kill players before the game starts and this is needed to prevent errors
self.orders = [[] for i in range(self.num_players)]
def distance(self, a_loc, b_loc):
""" Returns distance between x and y squared """
d_row = abs(a_loc[0] - b_loc[0])
d_row = min(d_row, self.height - d_row)
d_col = abs(a_loc[1] - b_loc[1])
d_col = min(d_col, self.width - d_col)
return d_row**2 + d_col**2
def parse_map(self, map_text):
""" Parse the map_text into a more friendly data structure """
ant_list = None
hill_list = []
hill_count = defaultdict(int)
width = height = None
water = []
food = []
ants = defaultdict(list)
hills = defaultdict(list)
row = 0
score = None
hive = None
num_players = None
for line in map_text.split('\n'):
line = line.strip()
# ignore blank lines and comments
if not line or line[0] == '#':
continue
key, value = line.split(' ', 1)
key = key.lower()
if key == 'cols':
width = int(value)
elif key == 'rows':
height = int(value)
elif key == 'players':
num_players = int(value)
if num_players < 2 or num_players > 10:
raise Exception("map",
"player count must be between 2 and 10")
elif key == 'score':
score = list(map(int, value.split()))
elif key == 'hive':
hive = list(map(int, value.split()))
elif key == 'm':
if ant_list is None:
if num_players is None:
raise Exception("map",
"players count expected before map lines")
ant_list = [chr(97 + i) for i in range(num_players)]
hill_list = list(map(str, range(num_players)))
hill_ant = [chr(65 + i) for i in range(num_players)]
if len(value) != width:
raise Exception("map",
"Incorrect number of cols in row %s. "
"Got %s, expected %s."
%(row, len(value), width))
for col, c in enumerate(value):
if c in ant_list:
ants[ant_list.index(c)].append((row,col))
elif c in hill_list:
hills[hill_list.index(c)].append((row,col))
hill_count[hill_list.index(c)] += 1
elif c in hill_ant:
ants[hill_ant.index(c)].append((row,col))
hills[hill_ant.index(c)].append((row,col))
hill_count[hill_ant.index(c)] += 1
elif c == MAP_OBJECT[FOOD]:
food.append((row,col))
elif c == MAP_OBJECT[WATER]:
water.append((row,col))
elif c != MAP_OBJECT[LAND]:
raise Exception("map",
"Invalid character in map: %s" % c)
row += 1
if score and len(score) != num_players:
raise Exception("map",
"Incorrect score count. Expected %s, got %s"
% (num_players, len(score)))
if hive and len(hive) != num_players:
raise Exception("map",
"Incorrect score count. Expected %s, got %s"
% (num_players, len(score)))
if height != row:
raise Exception("map",
"Incorrect number of rows. Expected %s, got %s"
% (height, row))
# look for ants without hills to invalidate map for a game
if not self.scenario:
for hill, count in hill_count.items():
if count == 0:
raise Exception("map",
"Player %s has no starting hills"
% hill)
return {
'size': (height, width),
'num_players': num_players,
'hills': hills,
'ants': ants,
'food': food,
'water': water
}
def neighbourhood_offsets(self, max_dist):
""" Return a list of squares within a given distance of loc
Loc is not included in the list
For all squares returned: 0 < distance(loc,square) <= max_dist
Offsets are calculated so that:
-height <= row+offset_row < height (and similarly for col)
negative indicies on self.map wrap thanks to python
"""
if max_dist not in self.offsets_cache:
offsets = []
mx = int(sqrt(max_dist))
for d_row in range(-mx,mx+1):
for d_col in range(-mx,mx+1):
d = d_row**2 + d_col**2
if 0 < d <= max_dist:
offsets.append((
d_row%self.height-self.height,
d_col%self.width-self.width
))
self.offsets_cache[max_dist] = offsets
return self.offsets_cache[max_dist]
def init_vision(self):
""" Initialise the vision data """
# calculate and cache vision offsets
cache = {}
# all offsets that an ant can see
locs = set(self.neighbourhood_offsets(self.viewradius))
locs.add((0,0))
cache['new'] = list(locs)
cache['-'] = [list(locs)]
for d in AIM:
# determine the previous view
p_r, p_c = -AIM[d][0], -AIM[d][1]
p_locs = set(
(((p_r+r)%self.height-self.height),
((p_c+c)%self.width-self.width))
for r,c in locs
)
cache[d] = [list(p_locs), list(locs-p_locs), list(p_locs-locs)]
self.vision_offsets_cache = cache
# create vision arrays
self.vision = []
for _ in range(self.num_players):
self.vision.append([[0]*self.width for __ in range(self.height)])
# initialise the data based on the initial ants
self.update_vision()
self.update_revealed()
def update_vision(self):
""" Incrementally updates the vision data """
for ant in self.current_ants.values():
if not ant.orders:
# new ant
self.update_vision_ant(ant, self.vision_offsets_cache['new'], 1)
else:
order = ant.orders[-1]
if order in AIM:
# ant moved
self.update_vision_ant(ant, self.vision_offsets_cache[order][1], 1)
self.update_vision_ant(ant, self.vision_offsets_cache[order][-1], -1)
# else: ant stayed where it was
for ant in self.killed_ants:
order = ant.orders[-1]
self.update_vision_ant(ant, self.vision_offsets_cache[order][0], -1)
def update_vision_ant(self, ant, offsets, delta):
""" Update the vision data for a single ant
Increments all the given offsets by delta for the vision
data for ant.owner
"""
a_row, a_col = ant.loc
vision = self.vision[ant.owner]
for v_row, v_col in offsets:
# offsets are such that there is never an IndexError
vision[a_row+v_row][a_col+v_col] += delta
def update_revealed(self):
""" Make updates to state based on what each player can see
Update self.revealed to reflect the updated vision
Update self.switch for any new enemies
Update self.revealed_water
"""
self.revealed_water = []
for player in range(self.num_players):
water = []
revealed = self.revealed[player]
switch = self.switch[player]
for row, squares in enumerate(self.vision[player]):
for col, visible in enumerate(squares):
if not visible:
continue
value = self.map[row][col]
# if this player encounters a new enemy then
# assign the enemy the next index
if value >= ANTS and switch[value] is None:
switch[value] = self.num_players - switch.count(None)
# mark square as revealed and determine if we see any
# new water
if not revealed[row][col]:
revealed[row][col] = True
if value == WATER:
water.append((row,col))
# update the water which was revealed this turn
self.revealed_water.append(water)
def get_perspective(self, player=None):
""" Get the map from the perspective of the given player
If player is None, the map is return unaltered.
Squares that are outside of the player's vision are
marked as UNSEEN.
Enemy identifiers are changed to reflect the order in
which the player first saw them.
"""
if player is not None:
v = self.vision[player]
result = []
for row, squares in enumerate(self.map):
map_row = []
for col, square in enumerate(squares):
if player is None or v[row][col]:
if (row,col) in self.hills:
if (row,col) in self.current_ants:
# assume ant is hill owner
# numbers should be divisible by the length of PLAYER_ANT
map_row.append(square+10)
else:
map_row.append(square+20)
else:
map_row.append(square)
else:
map_row.append(UNSEEN)
result.append(map_row)
return result
def render_changes(self, player):
""" Create a string which communicates the updates to the state
Water which is seen for the first time is included.
All visible transient objects (ants, food) are included.
"""
updates = self.get_state_changes()
v = self.vision[player]
visible_updates = []
# first add unseen water
for row, col in self.revealed_water[player]:
visible_updates.append(['w', row, col])
# next list all transient objects
for update in updates:
ilk, row, col = update[0:3]
# only include updates to squares which are visible
# and the current players dead ants
if v[row][col] or (ilk == 'd' and update[-1] == player):
visible_updates.append(update)
# switch player perspective of player numbers
if ilk in ['a', 'd', 'h']:
# an ant can appear in a bots vision and die the same turn
# in this case the ant has not been assigned a number yet
# assign the enemy the next index
if self.switch[player][update[-1]] is None:
self.switch[player][update[-1]] = self.num_players - self.switch[player].count(None)
update[-1] = self.switch[player][update[-1]]
visible_updates.append([]) # newline
return '\n'.join(' '.join(map(str,s)) for s in visible_updates)
def get_state_changes(self):
""" Return a list of all transient objects on the map.
Food, living ants, ants killed this turn
Changes are sorted so that the same state will result in the same output
"""
changes = []
# hills not razed
changes.extend(sorted(
[['h', hill.loc[0], hill.loc[1], hill.owner]
for _, hill in self.hills.items()
if hill.killed_by is None]
))
# current ants
changes.extend(sorted(
['a', ant.loc[0], ant.loc[1], ant.owner]
for ant in self.current_ants.values()
))
# current food
changes.extend(sorted(
['f', row, col]
for row, col in self.current_food
))
# ants killed this turn
changes.extend(sorted(
['d', ant.loc[0], ant.loc[1], ant.owner]
for ant in self.killed_ants
))
return changes
def get_map_output(self, player=None, replay=False):
""" Render the map from the perspective of the given player.
If player is None, then no squares are hidden and player ids
are not reordered.
"""
result = []
if replay and self.scenario:
for row in self.original_map:
result.append(''.join([MAP_RENDER[col] for col in row]))
else:
for row in self.get_perspective(player):
result.append(''.join([MAP_RENDER[col] for col in row]))
return result
def nearby_ants(self, loc, max_dist, exclude=None):
""" Returns ants where 0 < dist to loc <= sqrt(max_dist)
If exclude is not None, ants with owner == exclude
will be ignored.
"""
ants = []
row, col = loc
for d_row, d_col in self.neighbourhood_offsets(max_dist):
if ANTS <= self.map[row+d_row][col+d_col] != exclude:
n_loc = self.destination(loc, (d_row, d_col))
ants.append(self.current_ants[n_loc])
return ants
def parse_orders(self, player, lines):
""" Parse orders from the given player
Orders must be of the form: o row col direction
row, col must be integers
direction must be in (n,s,e,w)
"""
orders = []
valid = []
ignored = []
invalid = []
for line in lines:
line = line.strip().lower()
# ignore blank lines and comments
if not line or line[0] == '#':
continue
data = line.split()
# validate data format
if data[0] != 'o':
invalid.append((line, 'unknown action'))
continue
if len(data) != 4:
invalid.append((line, 'incorrectly formatted order'))
continue
row, col, direction = data[1:]
loc = None
# validate the data types
try:
loc = int(row), int(col)
except ValueError:
invalid.append((line,'invalid row or col'))
continue
if direction not in AIM:
invalid.append((line,'invalid direction'))
continue
# this order can be parsed
orders.append((loc, direction))
valid.append(line)
return orders, valid, ignored, invalid
def validate_orders(self, player, orders, lines, ignored, invalid):
""" Validate orders from a given player
Location (row, col) must be ant belonging to the player
direction must not be blocked
Can't multiple orders to one ant
"""
valid = []
valid_orders = []
seen_locations = set()
for line, (loc, direction) in zip(lines, orders):
# validate orders
if loc in seen_locations:
invalid.append((line,'duplicate order'))
continue
try:
if self.map[loc[0]][loc[1]] != player:
invalid.append((line,'not player ant'))
continue
except IndexError:
invalid.append((line,'out of bounds'))
continue
if loc[0] < 0 or loc[1] < 0:
invalid.append((line,'out of bounds'))
continue
dest = self.destination(loc, AIM[direction])
if self.map[dest[0]][dest[1]] in (FOOD, WATER):
ignored.append((line,'move blocked'))
continue
# this order is valid!
valid_orders.append((loc, direction))
valid.append(line)
seen_locations.add(loc)
return valid_orders, valid, ignored, invalid
def do_orders(self):
""" Execute player orders and handle conflicts
All ants are moved to their new positions.
Any ants which occupy the same square are killed.
"""
# set old ant locations to land
for ant in self.current_ants.values():
row, col = ant.loc
self.map[row][col] = LAND
# determine the direction that each ant moves
# (holding any ants that don't have orders)
move_direction = {}
for orders in self.orders:
for loc, direction in orders:
move_direction[self.current_ants[loc]] = direction
for ant in self.current_ants.values():
if ant not in move_direction:
move_direction[ant] = '-'
# move all the ants
next_loc = defaultdict(list)
for ant, direction in move_direction.items():
ant.loc = self.destination(ant.loc, AIM.get(direction, (0,0)))
ant.orders.append(direction)
next_loc[ant.loc].append(ant)
# if ant is sole occupant of a new square then it survives
self.current_ants = {}
colliding_ants = []
for loc, ants in next_loc.items():
if len(ants) == 1:
self.current_ants[loc] = ants[0]
else:
for ant in ants:
self.kill_ant(ant, True)
colliding_ants.append(ant)
# set new ant locations
for ant in self.current_ants.values():
row, col = ant.loc
self.map[row][col] = ant.owner
def do_gather(self):
""" Gather food
If there are no ants within spawnradius of a food then
the food remains.
If all the ants within spawnradius of a food are owned by the
same player then the food gets added to the hive and will
spawn a new ant as soon as possible ( 1 turn later ).
If ants of more than one owner are within spawnradius of a food
then that food disappears.
"""
# gather food
for f_loc in list(self.current_food.keys()):
# find the owners of all the ants near the food
nearby_players = set(
ant.owner for ant in self.nearby_ants(f_loc, self.spawnradius)
)
if len(nearby_players) == 1:
# gather food because there is only one player near the food
owner = nearby_players.pop()
self.remove_food(f_loc, owner)
elif nearby_players:
# remove food because it is contested
self.remove_food(f_loc)
def do_spawn(self):
""" Spawn new ants at hills from hive amount
Ants spawn at hills. The least recently touched hill has priority.
Ties are done randomly. The bot can control by standing over a hill
to prevent spawning where they don't want to spawn.
"""
# Determine new ant locations
for player in range(self.num_players):
player_hills = sorted(self.player_hills(player),
key=lambda hill: (hill.last_touched, random()))
for hill in player_hills:
# hill must not be razed or occupied to be used
# player must have food in hive to spawn
if (self.hive_food[player] > 0 and
hill.loc not in self.current_ants):
self.hive_food[player] -= 1
self.add_ant(hill)
def add_food(self, loc):
""" Add food to a location
An error is raised if the location is not free
"""
if self.map[loc[0]][loc[1]] != LAND:
raise Exception("Add food error",
"Food already found at %s" %(loc,))
self.map[loc[0]][loc[1]] = FOOD
food = Food(loc, self.turn)
self.current_food[loc] = food
self.all_food.append(food)
return food
def remove_food(self, loc, owner=None):
""" Remove food from a location
An error is raised if no food exists there.
"""
try:
self.map[loc[0]][loc[1]] = LAND
self.current_food[loc].end_turn = self.turn
if owner is not None:
self.current_food[loc].owner = owner
self.hive_food[owner] += 1
return self.current_food.pop(loc)
except KeyError:
raise Exception("Remove food error",
"Food not found at %s" %(loc,))
def add_hill(self, loc, owner):
hill = Hill(loc, owner)
self.hills[loc] = hill
return hill
def raze_hill(self, hill, killed_by):
hill.end_turn = self.turn
hill.killed_by = killed_by
self.score[killed_by] += HILL_POINTS
if not hill.raze_points:
hill.raze_points = True
self.score[hill.owner] += RAZE_POINTS
# reset cutoff_turns
self.cutoff_turns = 0
def player_hills(self, player):
""" Return the current hills belonging to the given player """
return [hill for _, hill in self.hills.items()
if hill.owner == player and hill.killed_by is None]
def add_ant(self, hill):
""" Spawn an ant on a hill
"""
loc = hill.loc
owner = hill.owner
ant = Ant(loc, owner, self.turn)
row, col = loc
self.map[row][col] = owner
self.all_ants.append(ant)
self.current_ants[loc] = ant
hill.last_touched = self.turn
return ant
def add_initial_ant(self, loc, owner):
ant = Ant(loc, owner, self.turn)
row, col = loc
self.map[row][col] = owner
self.all_ants.append(ant)
self.current_ants[loc] = ant
return ant
def kill_ant(self, ant, ignore_error=False):
""" Kill the ant at the given location
Raises an error if no ant is found at the location
(if ignore error is set to False)
"""
try:
loc = ant.loc
self.map[loc[0]][loc[1]] = LAND
self.killed_ants.append(ant)
ant.killed = True
ant.die_turn = self.turn
# check for hill kills to stall cutoff counter
if (loc in self.hills and
self.hills[loc].owner != self.cutoff_bot and
self.hills[loc].killed_by is None):
self.hill_kill = True
return self.current_ants.pop(loc)
except KeyError:
if not ignore_error:
raise Exception("Kill ant error",
"Ant not found at %s" %(loc,))
def player_ants(self, player):
""" Return the current ants belonging to the given player """
return [ant for ant in self.current_ants.values() if player == ant.owner]
def do_raze_hills(self):
for loc, hill in self.hills.items():
if loc in self.current_ants:
ant = self.current_ants[loc]
if ant.owner == hill.owner:
hill.last_touched = self.turn
elif hill.killed_by is None:
self.raze_hill(hill, ant.owner)
def do_attack_damage(self):
""" Kill ants which take more than 1 damage in a turn
Each ant deals 1/#nearby_enemy damage to each nearby enemy.
(nearby enemies are those within the attackradius)
Any ant with at least 1 damage dies.
Damage does not accumulate over turns
(ie, ants heal at the end of the battle).
"""
damage = defaultdict(Fraction)
nearby_enemies = {}
# each ant damages nearby enemies
for ant in self.current_ants.values():
enemies = self.nearby_ants(ant.loc, self.attackradius, ant.owner)
if enemies:
nearby_enemies[ant] = enemies
strenth = 10 # dot dot dot
if ant.orders[-1] == '-':
strenth = 10
else:
strenth = 10
damage_per_enemy = Fraction(strenth, len(enemies)*10)
for enemy in enemies:
damage[enemy] += damage_per_enemy
# kill ants with at least 1 damage
for ant in damage:
if damage[ant] >= 1:
self.kill_ant(ant)
def do_attack_support(self):
""" Kill ants which have more enemies nearby than friendly ants
An ant dies if the number of enemy ants within the attackradius
is greater than the number of friendly ants within the attackradius.
The current ant is not counted in the friendly ant count.
1 point is distributed evenly among the enemies of the dead ant.
"""
# map ants (to be killed) to the enemies that kill it
ants_to_kill = {}
for ant in self.current_ants.values():
enemies = []
friends = []
# sort nearby ants into friend and enemy lists
for nearby_ant in self.nearby_ants(ant.loc, self.attackradius, ant.owner):
if nearby_ant.owner == ant.owner:
friends.append(nearby_ant)
else:
enemies.append(nearby_ant)
# add ant to kill list if it doesn't have enough support
if len(friends) < len(enemies):
ants_to_kill[ant] = enemies
# actually do the killing and score distribution
for ant, enemies in ants_to_kill.items():
self.kill_ant(ant)
def do_attack_focus(self):
""" Kill ants which are the most surrounded by enemies
For a given ant define: Focus = 1/NumOpponents
An ant's Opponents are enemy ants which are within the attackradius.
Ant alive if its Focus is greater than Focus of any of his Opponents.
If an ant dies 1 point is shared equally between its Opponents.
"""
# maps ants to nearby enemies
nearby_enemies = {}
for ant in self.current_ants.values():
nearby_enemies[ant] = self.nearby_ants(ant.loc, self.attackradius, ant.owner)
# determine which ants to kill
ants_to_kill = []
for ant in self.current_ants.values():
# determine this ants weakness (1/focus)
weakness = len(nearby_enemies[ant])
# an ant with no enemies nearby can't be attacked
if weakness == 0:
continue
# determine the most focused nearby enemy
min_enemy_weakness = min(len(nearby_enemies[enemy]) for enemy in nearby_enemies[ant])
# ant dies if it is weak as or weaker than an enemy weakness
if min_enemy_weakness <= weakness:
ants_to_kill.append(ant)
# kill ants and distribute score
for ant in ants_to_kill:
self.kill_ant(ant)
def do_attack_closest(self):
""" Iteratively kill neighboring groups of ants """
# maps ants to nearby enemies by distance
ants_by_distance = {}
for ant in self.current_ants.values():
# pre-compute distance to each enemy in range
dist_map = defaultdict(list)
for enemy in self.nearby_ants(ant.loc, self.attackradius, ant.owner):
dist_map[self.distance(ant.loc, enemy.loc)].append(enemy)
ants_by_distance[ant] = dist_map
# create helper method to find ant groups
ant_group = set()
def find_enemy(ant, distance):
""" Recursively finds a group of ants to eliminate each other """
# we only need to check ants at the given distance, because closer
# ants would have been eliminated already
for enemy in ants_by_distance[ant][distance]:
if not enemy.killed and enemy not in ant_group:
ant_group.add(enemy)
find_enemy(enemy, distance)
# setup done - start the killing
for distance in range(1, self.attackradius):
for ant in self.current_ants.values():
if not ants_by_distance[ant] or ant.killed:
continue
ant_group = set([ant])
find_enemy(ant, distance)
# kill all ants in groups with more than 1 ant
# this way of killing is order-independent because the
# the ant group is the same regardless of which ant
# you start looking at
if len(ant_group) > 1:
for ant in ant_group:
self.kill_ant(ant)
def destination(self, loc, d):
""" Returns the location produced by offsetting loc by d """
return ((loc[0] + d[0]) % self.height, (loc[1] + d[1]) % self.width)
def access_map(self):
""" Determine the list of locations that each player is closest to """
distances = {}
players = defaultdict(set)
square_queue = deque()
# determine the starting squares and valid squares
# (where food can be placed)
for row, squares in enumerate(self.map):
for col, square in enumerate(squares):
loc = (row, col)
if square >= 0:
distances[loc] = 0
players[loc].add(square)
square_queue.append(loc)
elif square != WATER:
distances[loc] = None
# use bfs to determine who can reach each square first
while square_queue:
c_loc = square_queue.popleft()
for d in AIM.values():
n_loc = self.destination(c_loc, d)
if n_loc not in distances: continue # wall
if distances[n_loc] is None:
# first visit to this square
distances[n_loc] = distances[c_loc] + 1
players[n_loc].update(players[c_loc])
square_queue.append(n_loc)
elif distances[n_loc] == distances[c_loc] + 1:
# we've seen this square before, but the distance is
# the same - therefore combine the players that can
# reach this square
players[n_loc].update(players[c_loc])
# summarise the final results of the squares that are closest
# to a single unique player
access_map = defaultdict(list)
for coord, player_set in players.items():
if len(player_set) != 1: continue
access_map[player_set.pop()].append(coord)
return access_map
def find_closest_land(self, coord):
""" Find the closest square to coord which is a land square using BFS
Return None if no square is found
"""
if self.map[coord[0]][coord[1]] == LAND: