-
Notifications
You must be signed in to change notification settings - Fork 0
/
battlecode.py
1388 lines (1166 loc) · 44.2 KB
/
battlecode.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
from __future__ import print_function
'''Play battlecode hackathon games.'''
import socket
import math
import io
import time
import os
import sys
import signal
try:
import cPickle as pickle
except:
import pickle
try:
import ujson as json
except:
import json
import threading
try:
from queue import Queue
except:
from Queue import Queue
# pylint: disable = too-many-instance-attributes, invalid-name
GRASS = 'G'
DIRT = 'D'
THROW_RANGE = 7
THROW_HEDGE_DAMAGE = 1
THROW_ENTITY_DAMAGE = 4
THROW_ENTITY_RECOIL = 2
THROW_ENTITY_DIRT = 1
PICKUP_DELAY = 0
THROW_DELAY = 10
MOVEMENT_DELAY = 1
BUILD_DELAY = 10
# terminal formatting
_TERM_RED = '\033[31m'
_TERM_END = '\033[0m'
class Direction(object):
''' This is an enum for direction '''
@staticmethod
def directions():
'''
returns an array of all compass directions. It starts with SOUTH_WEST
and proceeds counter-clockwise around the compass.
This array is deterministic.
Returns:
[Direction]: An array of all compass directions
'''
return [Direction.SOUTH_WEST, Direction.SOUTH,
Direction.SOUTH_EAST, Direction.EAST,
Direction.NORTH_EAST, Direction.NORTH,
Direction.NORTH_WEST, Direction.WEST]
@staticmethod
def from_delta(dx, dy):
'''
Initializes a Direction from a delta dx, dy. This finds the cardinal
direction closest to the desired delta.
Args:
dx (int): delta in x direction
dy (int): delta in y direction
Both arguments cannot be zero
Returns:
Direction: a new Direction for that delta
'''
# This is code to approximate the the closest movement
if abs(dx) >= 2.414*abs(dy):
dy = 0
elif abs(dy) >= 2.414*abs(dx):
dx = 0
if dx < 0:
if dy < 0:
return Direction.SOUTH_WEST
elif dy == 0:
return Direction.WEST
elif dy > 0:
return Direction.NORTH_WEST
elif dx == 0:
if dy < 0:
return Direction.SOUTH
elif dy == 0:
raise BattlecodeError("not a valid delta: "+str(dx)+","+str(dy))
elif dy > 0:
return Direction.NORTH
elif dx > 0:
if dy < 0:
return Direction.SOUTH_EAST
elif dy == 0:
return Direction.EAST
elif dy > 0:
return Direction.NORTH_EAST
@staticmethod
def all():
'''
returns an generator to Directions
Returns:
Direction: An generator of all compass directions
'''
for direction in Direction.directions():
yield direction
def __eq__(self, other):
if type(other) is not Direction:
return False
return self.dx == other.dx and self.dy == other.dy
def __init__(self, dx, dy):
'''
Initialize a Direction with given delta x and delta y.
Args:
dx (int): the delta in the x direction which has to be in range 1,0,-1
dy (int): the delta in the y direction which has to be in range 1,0,-1
Returns:
Direction: A new direction with given dx and dy
'''
if __debug__:
assert dx<=1 and dx >= -1, "dx is not in the right range"
assert dy<=1 and dy >= -1, "dy is not in the right range"
self.dx = dx
self.dy = dy
def rotate_left(self):
'''
Return a direction that is 90 degrees left from the original.
Returns:
Direction: A new Direction rotated 90 degrees to the left
'''
return self.rotate_counter_clockwise_degrees(90)
def rotate_right(self):
'''
Return a direction that is 90 degrees right from the original.
Returns:
Direction: A new Direction rotated 90 degrees to the right
'''
return self.rotate_counter_clockwise_degrees(270)
def rotate_opposite(self):
'''
Return a direction that is 180 degrees rotated from the original.
Returns:
Direction: A new direction opposite to the original
'''
return self.rotate_counter_clockwise_degrees(180)
def rotate_counter_clockwise_degrees(self, degrees):
'''Rotate an angle by given number of degrees.
Args:
degree (int): degree to rotate counter clockwise by. Must be
degree%45==0
Returns:
Direction: a new rotated Direction
'''
if __debug__:
assert degrees%45==0
rotations = degrees//45
index = Direction.directions().index(self)
length = len(Direction.directions())
return Direction.directions()[(index+rotations)%length]
'''The direction (-1, -1).'''
Direction.SOUTH_WEST = Direction(-1, -1)
'''The direction (1, -1).'''
Direction.SOUTH_EAST = Direction(1, -1)
'''The direction (0, -1).'''
Direction.SOUTH = Direction(0, -1)
'''The direction (1, 1).'''
Direction.NORTH_EAST = Direction(1, 1)
'''The direction (0, 1).'''
Direction.NORTH = Direction(0, 1)
'''The direction (-1, 1).'''
Direction.NORTH_WEST = Direction(-1, 1)
'''The direction (1, 0).'''
Direction.EAST = Direction(1, 0)
'''The direction (-1, 0).'''
Direction.WEST = Direction(-1, 0)
class Entity(object):
'''
An entity in the world: a Thrower, Hedge, or Statue.
Do not modify the properties of this object; it won't do anything
Instead, call the queue functions such as entity.queue_move() and other
methods to tell the game to do something next turn.
Attributes:
id (int): the id of a entity
type (string): String type of a given entity
team (Team): team of entity
hp (int): hp of entity
cooldown_end (int): turn when cooldown is 0
held_by (Entity): Entity holding this object. If not held held_by is
None
holding (Entity): Entity held by this. If nothing is held holding is
None
'''
def __init__(self, state):
'''
Do not initialize new entities. This will cause errors in your
bot.
'''
self._state = state
self.id = None
self.type = None
self.location = None
self.team = None
self.hp = None
self.cooldown_end = None
self.holding_end = None
self.held_by = None
self.holding = None
self._disintegrated = False
def __str__(self):
contents = '<id:{},type:{},team:{},location:{},hp:{}'.format(
self.id, self.type, self.team, self.location, self.hp)
if self.cooldown > 0:
contents += ',cooldown:{}'.format(self.cooldown)
if self.holding is not None:
contents += ',holding:{},holding_end:{}'.format(self.holding.id, self.holding_end)
if self.held_by is not None:
contents += ',held_by:{}'.format(self.held_by.id)
contents += '>'
return contents
def __repr__(self):
return str(self)
def __eq__(self, other):
if not isinstance(other, Entity):
return False
if self.holding is not None and other.holding is not None \
and self.holding.id != other.holding.id:
return False
if self.held_by is not None and other.held_by is not None \
and self.held_by.id != other.held_by.id:
return False
return self.id == other.id \
and self.type == other.type \
and self.location == other.location \
and self.team == other.team \
and self.hp == other.hp \
and self.cooldown_end == other.cooldown_end \
and self.holding_end == other.holding_end
def __ne__(self, other):
return not (self == other)
def _update(self, data):
if self.location in self._state.map._occupied and \
self._state.map._occupied[self.location].id == self.id:
del self._state.map._occupied[self.location]
if __debug__:
if self.id is not None:
assert data['id'] == self.id
if self.type is not None:
assert data['type'] == self.type
if self.team is not None:
assert data['teamID'] == self.team.id
self.id = data['id']
self.type = data['type']
self.team = self._state.teams[data['teamID']]
self.hp = data['hp']
self.location = Location(data['location']['x'], data['location']['y'])
if 'cooldownEnd' in data:
self.cooldown_end = data['cooldownEnd']
else:
self.cooldown_end = None
if 'holdingEnd' in data:
self.holding_end = data['holdingEnd']
else:
self.holding_end = None
if 'heldBy' in data:
self.held_by = self._state.entities[data['heldBy']]
else:
self.held_by = None
self._state.map._occupied[self.location] = self
if 'holding' in data:
self.holding = self._state.entities[data['holding']]
else:
self.holding = None
@property
def cooldown(self):
'''
Returns:
int: The number of turns left in this entity's cooldown. If
there is no cooldown then is a 0.
'''
if self.cooldown_end is None:
return 0
if self.cooldown_end <= self._state.turn:
return 0
return self.cooldown_end - self._state.turn
@property
def is_thrower(self):
'''
Returns:
bool: True if a entity is a THROWER else False.
'''
return self.type == Entity.THROWER
@property
def is_statue(self):
'''
Returns:
bool: True if a entity is a STATUE else False.
'''
return self.type == Entity.STATUE
@property
def is_hedge(self):
'''
Returns:
bool: True if a entity is a HEDGE else False.
'''
return self.type == Entity.HEDGE
@property
def is_holding(self):
'''
Returns:
bool: True if holding an entity else False
'''
return self.holding != None
@property
def is_held(self):
'''
Returns:
bool: True if held by an entity else False
'''
return self.held_by != None
@property
def can_act(self):
'''
Returns:
bool: True if this unit can perform actions this turn.
'''
return self.cooldown == 0 and self.is_thrower and (self.held_by is None) and \
not self._disintegrated
@property
def can_be_picked(self):
'''
Returns:
bool: True if this entity can be picked up
'''
return self.is_thrower and not self.is_holding and not self.is_held
def can_throw(self, direction):
'''
To throw an entity.
Self has to be holding a unit and self has to be able to act.
The adjacent square in the given direction has to be on the map and not
occupied.
Args:
direction (Direction): Direction this entity desires to throw its
held entity
Returns:
bool: True if this entity thrown in given direction
'''
if not self.is_holding or not self.can_act:
return
held = self.holding
initial = self.location
target_loc = Location(initial.x+direction.dx, \
initial.y+direction.dy)
on_map = self._state.map.location_on_map(target_loc)
is_occupied = target_loc in self._state.map._occupied
if ((not on_map) or is_occupied):
return False
return True
def can_move(self, direction):
'''
Args:
direction (Direction): Direction this entity desires to move in
Returns:
bool: True if a unit can move in this direction
'''
if not self.can_act:
return False
location = self.location.adjacent_location_in_direction(direction)
on_map = self._state.map.location_on_map(location)
is_occupied = location in self._state.map._occupied
if ((not on_map) or is_occupied):
return False
return True
def can_build(self, direction):
'''
This is true if there is no object in the adjacent tile in that
direction and the tile is on the map.
Args:
direction (Direction): Direction this entity desires to build in
Returns:
bool: True if a unit can build in this direction
'''
return self.can_move(direction)
def can_pickup(self, entity):
'''
This is true if the other entity can be picked up which means.
The entity cannot be self.
Self cannot be holding anything, and the entity cannot be held
The two entities must be adjacent.
The entity cannot has to be a THROWER.
Args:
entity (Entity): The entity this entity desires to pickup
Returns:
bool: True if this can pickup said entity
'''
if __debug__:
assert isinstance(entity, Entity), 'Parameter ' + str(entity) + \
"is not an entity"
assert (self != entity), "You can't pickup yourself"
# Can't pickup self or if current'y holding
if entity == self or self.holding != None:
return False
# If you can't act then you can't do anything
if not self.can_act:
return False
distance_to = self.location.distance_to_squared(entity.location)
if entity == None or not entity.can_be_picked or not distance_to <=2 or \
entity._disintegrated:
return False
else:
return True
def queue_move(self, direction):
'''
Queues Move to take place next turn. Throws an assertion error if cannot
move in given direction.
Args:
direction (Direction): Direction this entity desires to move in
'''
if __debug__:
location = self.location.adjacent_location_in_direction(direction)
assert isinstance(location, Location), "Can't move to a non-location!"
assert self.can_move(direction), "Invalid move cannot move in given direction"
if(self.team != self._state.my_team):
return
self._state._queue({
'action': 'move',
'id': self.id,
'dx': direction.dx,
'dy': direction.dy
})
if self._state.speculate:
if self.can_move(direction):
del self._state.map._occupied[self.location]
self.location = self.location.adjacent_location_in_direction(direction)
if self.holding != None:
self.holding.location = self.location
self._state.map._occupied[self.location] = self
self.cooldown_end = self._state.turn + 1
def queue_build(self, direction):
'''
Queues build to take place next turn. Throws an assertion error if cannot
build in given direction.
Args:
direction (Direction): Direction this entity desires to build in
'''
location = self.location.adjacent_location_in_direction(direction)
if __debug__:
assert isinstance(location, Location), "Can't move to a non-location!"
assert self.can_build(direction), "Invalid action cannot build in given direction"
if(self.team != self._state.my_team):
return
self._state._queue({
'action': 'build',
'id': self.id,
'dx': direction.dx,
'dy': direction.dy
})
if self._state.speculate:
if self.can_build(direction):
self.cooldown_end = self._state.turn + 10
self._state._build_statue(location)
def _deal_damage(self, damage):
if self._disintegrated:
return
self.hp -= damage
if(self.hp>0):
return
if self.held_by == None:
del self._state.map._occupied[self.location]
if self.holding != None:
self.holding.held_by = None
self._state.map._occupied[self.location] = self.holding
self._disintegrated = True
del self._state.entities[self.id]
def queue_disintegrate(self):
'''
Queues a disintegration, so that this object will disintegrate in the
next turn.
'''
if(self.team != self._state.my_team):
return
self._state._queue({
'action': 'disintegrate',
'id': self.id
})
if self._state.speculate:
self._deal_damage(self.hp+1)
def queue_throw(self, direction):
'''
Queue this entity to throw a bot in given direction next turn. If this
cannot throw, will throw an assertion.
Args:
direction (Direction): Direction this entity desires to throw its
held entity
'''
if __debug__:
assert self.holding != None, "Not Holding anything"
assert self.can_throw(direction), "Not Enough space to throw"
if(self.team != self._state.my_team):
return
self._state._queue({
'action': 'throw',
'id': self.id,
'dx': direction.dx,
'dy': direction.dy
})
if self._state.speculate:
if not self.can_throw(direction):
return
held = self.holding
self.holding = None
self.holding_end = None
initial = self.location
target_loc = Location(initial.x+direction.dx, \
initial.y+direction.dy)
for i in range(THROW_RANGE+1):
on_map = self._state.map.location_on_map(target_loc)
is_occupied = target_loc in self._state.map._occupied
if ((not on_map) or is_occupied):
break
target_loc = Location(target_loc.x + direction.dx, \
target_loc.y + direction.dy)
target = self._state.map._occupied.get(target_loc, None)
if(target != None):
if(target.type == Entity.HEDGE):
target._deal_damage(THROW_HEDGE_DAMAGE)
else:
target._deal_damage(THROW_ENTITY_DAMAGE)
held._deal_damage(THROW_ENTITY_RECOIL)
landing_location = Location(target_loc.x - direction.dx, \
target_loc.y - direction.dy)
held.location = landing_location
if self._state.map.tile_at(landing_location) == DIRT:
held._deal_damage(THROW_ENTITY_DIRT)
if not held._disintegrated:
self._state.map._occupied[landing_location] = held
held.held_by = None
self.cooldown_end = self._state.turn + 10
def queue_pickup(self, entity):
'''
Queues this to pickup entity next turn. If this cannot pickup entity
will throw an assertion error.
Args:
entity (Entity): The entity this entity desires to pickup
'''
if(self.team != self._state.my_team):
return
if __debug__:
assert self.can_pickup(entity), "Invalid Pickup Command"
self._state._queue({
'action': 'pickup',
'id': self.id ,
'pickupID': entity.id
})
if self._state.speculate:
if self.can_pickup(entity):
del self._state.map._occupied[entity.location]
self.holding = entity
entity.held_by = self
entity.location = self.location
self.holding_end = self._state.turn + 10
self.cooldown_end = self._state.turn + 10
def entities_within_adjacent_distance(self, distance, include_held=False,
iterator=None):
'''
Returns all the entities within a certain adjacency distance from this
bot as an generator.
Adjacency distance is the number of adjacent blocks needed to traverse
to get to a tile, which is equivalent to max(abs(deltax), abs(deltay))
Args:
distance (float): returns all entities with distance less than <=
distance
Options Args:
include_held (bool): Defaults to false. If true held units will be
included in the iterator
iterator (iterator or list): A subset of bots to iterate through.
Will only search the bots in this
iterator
Returns:
[Entities]: Returns a generator for the entities within distance of
of this robot
'''
if iterator != None:
for entity in iterator:
if entity is self:
continue
if not include_held and entity.held_by is not None:
continue
if self.location.adjacent_distance_to(entity.location) <= distance:
yield entity
return
for entity in self._state.get_entities():
if entity is self:
continue
if not include_held and entity.held_by is not None:
continue
if self.location.adjacent_distance_to(entity.location) <= distance:
yield entity
def entities_within_euclidean_distance(self, distance, include_held=False,
iterator=None):
'''
Returns all the entities within a certain Euclidean distance from this
bot as an generator.
Euclidean distance is defined as sqrt(deltax^2+deltay^2)
Not to be confused with displacement difference, which is
max(deltax,deltay)
Args:
distance (float): returns all entities with distance less than <=
distance
Options Args:
include_held (bool): Defaults to false. If true held units will be
included in the iterator
iterator (iterator or list): A subset of bots to iterate through.
Will only search the bots in this
iterator
Returns:
[Entities]: Returns a generator for the entities within distance of
of this robot
'''
if iterator != None:
for entity in iterator:
if entity is self:
continue
if not include_held and entity.held_by is not None:
continue
if self.location.distance_to(entity.location) <= distance:
yield entity
return
for entity in self._state.get_entities():
if entity is self:
continue
if not include_held and entity.held_by is not None:
continue
if self.location.distance_to(entity.location) <= distance:
yield entity
Entity.THROWER = 'thrower'
Entity.HEDGE = 'hedge'
Entity.STATUE = 'statue'
class Location(tuple):
'''
An x,y tuple representing a location in the world.
This class is immutable.
Attributes:
x (int): x coordinate of location
y (int): y coordinate of location
'''
__slots__ = []
def __new__(cls, x=None, y=None):
if isinstance(x, int) and isinstance(y, int):
return tuple.__new__(cls, (x, y))
elif x is not None:
# used by pickle
return tuple.__new__(cls, x)
else:
raise Exception('invalid Location x,y: {},{}'.format(x,y))
@property
def x(self):
return tuple.__getitem__(self, 0)
@property
def y(self):
return tuple.__getitem__(self, 1)
def __str__(self):
return '<{},{}>'.format(self.x, self.y)
def __repr__(self):
return str(self)
def __eq__(self, other):
if type(other) is not Location:
return False
return self[0] == other[0] and self[1] == other[1]
__hash__ = tuple.__hash__
def __add__(self, other):
if isinstance(other, Location):
return Location(self.x + other.x, self.y + other.y)
elif isinstance(other, tuple):
return Location(self.x + other[0], self.y + other[1])
else:
return NotImplemented
def __sub__(self, other):
if isinstance(other, Location):
return Location(self.x - other.x, self.y - other.y)
elif isinstance(other, tuple):
return Location(self.x - other[0], self.y - other[1])
else:
return NotImplemented
def distance_to_squared(self, location):
'''
Return squared distance from self to other location.
Args:
location (Location): location we are trying to find the distance to
Returns:
int: Distance squared to the location
'''
return (location.x-self.x)**2+(location.y-self.y)**2
def distance_to(self, location):
'''
Return Euclidean distance from self to other location.
This is sqrt(deltax^2+deltay^2)
Args:
location (Location): location we are trying to find the distance to
Returns:
float: Distance squared to the location
'''
return math.sqrt((location.x-self.x)**2+(location.y-self.y)**2)
def adjacent_distance_to(self, location):
'''
Return adjacent distance from self to other location.
This is defined as max(abs(deltax),abs(deltay)), and is the number of
adjacent moves needed to get to a location.
Args:
location (Location): location we are trying to find the distance to
Returns:
float: Distance squared to the location
'''
return max(abs(self.x-location.x), abs(self.y-location.y))
def direction_to(self, location):
'''
Return a Direction from self to location. It will round to the most
closest cardinal direction.
Args:
location (Location): location we are trying to find the direction to
Returns:
Direction: The direction to the location
'''
if __debug__:
assert location != self, "Can not find direction to same location"
dx = location.x - self.x
dy = location.y - self.y
return Direction.from_delta(dx, dy)
def adjacent_location_in_direction(self, direction):
'''
Returns the location the is adjacent to a this in a certain direction.
Args:
direction (Direction): Direction that adjacency is desired
Returns:
Location: Location of the adjacent tile. Note this is not
necessarily on the map.
'''
return Location(self.x+direction.dx, self.y+direction.dy)
def is_adjacent(self, location):
'''
Return True if a tile is adjacent to given location.
Args:
location (Location): location we are trying to find if adjacent
Returns:
bool: True if adjacent else false
'''
return self.distance_to_squared(location)<=2
class Sector(object):
'''
Representation of a sector on the map
Attributes:
top_left (Location): Location of top_left corner of sector. This is the
max y and min x of the square.
team (Team): the team controlling this sector. If neither player team controls
this sector then the neutral team will control it
'''
def __init__(self, state, top_left):
'''
Do not touch this function. It initializes sectors before the game
starts
'''
self._state = state
self.top_left = top_left
self.team = None
def _update(self, data):
if __debug__:
assert self.top_left.x == data['topLeft']['x']
assert self.top_left.y == data['topLeft']['y']
assert data['controllingTeamID']!=-1, "We Done goof"
self.team = self._state.teams[data['controllingTeamID']]
def __eq__(self, other):
if not isinstance(other, Sector):
return False
return self.top_left == other.top_left and self.team == other.team
def __ne__(self, other):
return not (self == other)
def entities_in_sector(self):
'''
returns an iterator for entities in this sector
Returns:
Entities: entities in this sector
'''
for entity in self._state.get_entities():
entity_sector = self._state.map.sector_at(entity.location)
if(entity_sector != self):
continue
yield entity
class Map(object):
'''
A representation of the Game Map.
Attributes:
height (int): The max height, y.
width (int): The max width, x.
tiles ([string]): An array for the type of tile at each location.
sector_size (int): The size of each sector
'''
def __init__(self, state, height, width, tiles, sector_size):
self._state = state
self.height = height
self.width = width
self.tiles = tiles
self.sector_size = sector_size
self._sectors = {}
# occupied maps Location to Entity
self._occupied = {}
for x in range(0, self.width, self.sector_size):
for y in range(0, self.height, self.sector_size):
top_left = Location(x, y)
self._sectors[top_left] = Sector(self._state, top_left)
def tile_at(self, location):
'''
Returns the string for the tile at a given Location
This throws an assertion error if the location is out of bounds of the
map.
Args:
location (Location): the location we want to find out about
Returns:
String: The string describing the tile type. Either 'G' or 'D'
'''
assert self.location_on_map(location), "No Tile location not on map"
return self.tiles[len(self.tiles)-location.y-1][location.x]
def location_on_map(self, location):
'''
Checks whether a given location exists on this map.
Args:
location (Location): the location we want to find out about
Returns:
bool: True if this location exists on the map. else false
'''
if __debug__:
assert isinstance(location, Location), "Must pass a location"
x = location.x
y = location.y
return ((y>=0 and y < self.height) and (x>=0 and x < self.width))
def sector_at(self, location):
'''
Determine the sector for a given location
Args:
location (Location): the location we want to find out about
Returns:
Sector: The sector containing this location
'''
if __debug__:
assert self.location_on_map(location)
loc = Location(
location.x - location.x % self.sector_size,
location.y - location.y % self.sector_size
)
return self._sectors[loc]
def _update_sectors(self, data):
for sector_data in data:
top_left = Location(sector_data['topLeft']['x'], sector_data['topLeft']['y'])
if __debug__:
assert top_left.x % self.sector_size == 0
assert top_left.y % self.sector_size == 0
self._sectors[top_left]._update(sector_data)