-
Notifications
You must be signed in to change notification settings - Fork 0
/
ants.py
794 lines (593 loc) · 22 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
import random
from ucb import main, interact, trace
from collections import OrderedDict
################
# Core Classes #
################
class Place:
"""A Place holds insects and has an exit to another Place."""
is_hive = False
def __init__(self, name, exit=None):
"""Create a Place with the given NAME and EXIT.
name -- A string; the name of this Place.
exit -- The Place reached by exiting this Place (may be None).
"""
self.name = name
self.exit = exit
self.bees = [] # A list of Bees
self.ant = None # An Ant
self.entrance = None # A Place
# Phase 1: Add an entrance to the exit
if self.exit:
exit.entrance = self
def add_insect(self, insect):
"""
Asks the insect to add itself to the current place. This method exists so
it can be enhanced in subclasses.
"""
insect.add_to(self)
def remove_insect(self, insect):
"""
Asks the insect to remove itself from the current place. This method exists so
it can be enhanced in subclasses.
"""
insect.remove_from(self)
def __str__(self):
return self.name
class Insect:
"""An Insect, the base class of Ant and Bee, has health and a Place."""
damage = 0
def __init__(self, health, place=None):
"""Create an Insect with a health amount and a starting PLACE."""
self.health = health
self.place = place # set by Place.add_insect and Place.remove_insect
def reduce_health(self, amount):
"""Reduce health by AMOUNT, and remove the insect from its place if it
has no health remaining.
>>> test_insect = Insect(5)
>>> test_insect.reduce_health(2)
>>> test_insect.health
3
"""
self.health -= amount
if self.health <= 0:
self.death_callback()
self.place.remove_insect(self)
def action(self, gamestate):
"""The action performed each turn.
gamestate -- The GameState, used to access game state information.
"""
def death_callback(self):
# overriden by the gui
pass
def add_to(self, place):
"""Add this Insect to the given Place"""
self.place = place
def remove_from(self, place):
self.place = None
def __repr__(self):
cname = type(self).__name__
return '{0}({1}, {2})'.format(cname, self.health, self.place)
class Ant(Insect):
"""An Ant occupies a place and does work for the colony."""
implemented = False # Only implemented Ant classes should be instantiated
food_cost = 0
is_container = False
is_waterproof = False
has_doubled = False
def __init__(self, health=1):
"""Create an Insect with a HEALTH quantity."""
super().__init__(health)
@classmethod
def construct(cls, gamestate):
"""Create an Ant for a given GameState, or return None if not possible."""
if cls.food_cost > gamestate.food:
print('Not enough food remains to place ' + cls.__name__)
return
return cls()
def can_contain(self, other):
return False
def store_ant(self, other):
assert False, "{0} cannot contain an ant".format(self)
def remove_ant(self, other):
assert False, "{0} cannot contain an ant".format(self)
def add_to(self, place):
if place.ant is None:
place.ant = self
else:
if place.ant.can_contain(self):
place.ant.store_ant(self)
elif self.can_contain(place.ant):
self.store_ant(place.ant)
place.ant = self
else:
assert place.ant is None, 'Two ants in {0}'.format(place)
Insect.add_to(self, place)
def remove_from(self, place):
if place.ant is self:
place.ant = None
elif place.ant is None:
assert False, '{0} is not in {1}'.format(self, place)
else:
place.ant.remove_ant(self)
Insect.remove_from(self, place)
def double(self):
"""Double this ants's damage, if it has not already been doubled."""
if self.has_doubled:
return
self.has_doubled = True
self.damage *= 2
class HarvesterAnt(Ant):
"""HarvesterAnt produces 1 additional food per turn for the colony."""
name = 'Harvester'
implemented = True
food_cost = 2
def action(self, gamestate):
"""Produce 1 additional food for the colony.
gamestate -- The GameState, used to access game state information.
"""
gamestate.food += 1
class ThrowerAnt(Ant):
"""ThrowerAnt throws a leaf each turn at the nearest Bee in its range."""
name = 'Thrower'
implemented = True
damage = 1
food_cost = 3
lower_bound = 0
upper_bound = float('inf')
def nearest_bee(self):
"""Return the nearest Bee in a Place that is not the HIVE, connected to
the ThrowerAnt's Place by following entrances.
This method returns None if there is no such Bee (or none in range).
"""
position = self.place
counter = 0
while position:
if position.bees and not position.is_hive and self.lower_bound <= counter <= self.upper_bound:
return random_bee(position.bees)
position = position.entrance
counter += 1
return None
def throw_at(self, target):
"""Throw a leaf at the TARGET Bee, reducing its health."""
if target is not None:
target.reduce_health(self.damage)
def action(self, gamestate):
"""Throw a leaf at the nearest Bee in range."""
self.throw_at(self.nearest_bee())
def random_bee(bees):
"""Return a random bee from a list of bees, or return None if bees is empty."""
assert isinstance(bees, list), "random_bee's argument should be a list but was a %s" % type(bees).__name__
if bees:
return random.choice(bees)
##############
# Extensions #
##############
class ShortThrower(ThrowerAnt):
"""A ThrowerAnt that only throws leaves at Bees at most 3 places away."""
name = 'Short'
food_cost = 2
upper_bound = 3
implemented = True
class LongThrower(ThrowerAnt):
"""A ThrowerAnt that only throws leaves at Bees at least 5 places away."""
name = 'Long'
food_cost = 2
lower_bound = 5
implemented = True
class FireAnt(Ant):
"""FireAnt cooks any Bee in its Place when it expires."""
name = 'Fire'
damage = 3
food_cost = 5
implemented = True
def __init__(self, health=3):
"""Create an Ant with a HEALTH quantity."""
super().__init__(health)
def reduce_health(self, amount):
"""Reduce health by AMOUNT, and remove the FireAnt from its place if it
has no health remaining.
Make sure to reduce the health of each bee in the current place, and apply
the additional damage if the fire ant dies.
"""
if amount >= self.health:
for i in self.place.bees[:]:
i.reduce_health(amount + self.damage)
Ant.reduce_health(self, amount)
else:
Ant.reduce_health(self, amount)
for i in self.place.bees[:]:
i.reduce_health(amount)
# The WallAnt class
class WallAnt(Ant):
name = 'Wall'
food_cost = 4
implemented = True
def __init__(self, health=4):
super().__init__(health)
# The HungryAnt Class
class HungryAnt(Ant):
name = 'Hungry'
food_cost = 4
implemented = True
chewing_turns = 3
def __init__(self, health=1):
super().__init__(health)
self.turns_to_chew = 0
def action(self, gamestate):
if self.turns_to_chew == 0:
if self.place.bees:
choice = random_bee(self.place.bees)
choice.reduce_health(choice.health)
self.turns_to_chew = self.chewing_turns
else:
self.turns_to_chew -= 1
class ContainerAnt(Ant):
"""
ContainerAnt can share a space with other ants by containing them.
"""
is_container = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ant_contained = None
def can_contain(self, other):
if not self.ant_contained and not other.is_container:
return True
else:
return False
def store_ant(self, ant):
self.ant_contained = ant
def remove_ant(self, ant):
if self.ant_contained is not ant:
assert False, "{} does not contain {}".format(self, ant)
self.ant_contained = None
def remove_from(self, place):
if place.ant is self:
# Container was removed. Contained ant should remain in the game
place.ant = place.ant.ant_contained
Insect.remove_from(self, place)
else:
# default to normal behavior
Ant.remove_from(self, place)
def action(self, gamestate):
if self.ant_contained:
self.ant_contained.action(gamestate)
class BodyguardAnt(ContainerAnt):
"""BodyguardAnt provides protection to other Ants."""
name = 'Bodyguard'
food_cost = 4
implemented = True
def __init__(self, health=2):
super().__init__(health)
# The TankAnt class
class TankAnt(ContainerAnt):
name = 'Tank'
implemented = True
food_cost = 6
damage = 1
def __init__(self, health=2):
super().__init__(health)
def action(self, gamestate):
for b in self.place.bees[:]:
b.reduce_health(self.damage)
super().action(gamestate)
class Water(Place):
"""Water is a place that can only hold waterproof insects."""
def add_insect(self, insect):
"""Add an Insect to this place. If the insect is not waterproof, reduce
its health to 0."""
super().add_insect(insect)
if not insect.is_waterproof:
insect.reduce_health(insect.health)
# The ScubaThrower class
class ScubaThrower(ThrowerAnt):
name = 'Scuba'
food_cost = 6
is_waterproof = True
implemented = True
class QueenAnt(ScubaThrower):
"""The Queen of the colony. The game is over if a bee enters her place."""
name = 'Queen'
food_cost = 7
implemented = True # Change to True to view in the GUI
@classmethod
def construct(cls, gamestate):
"""
Returns a new instance of the Ant class if it is possible to construct, or
returns None otherwise. Remember to call the construct() method of the superclass!
"""
if not gamestate.queen_created:
gamestate.queen_created = True
return super().construct(gamestate)
else:
return None
def action(self, gamestate):
"""A queen ant throws a leaf, but also doubles the damage of ants
in her tunnel.
"""
super().action(gamestate)
iterator = self.place.exit
while iterator != None:
if iterator.ant:
iterator.ant.double()
if iterator.ant.is_container and iterator.ant.ant_contained:
iterator.ant.ant_contained.double()
iterator = iterator.exit
def reduce_health(self, amount):
"""Reduce health by AMOUNT, and if the QueenAnt has no health
remaining, signal the end of the game.
"""
super().reduce_health(amount)
ants_lose()
def remove_from(self, place):
return
class AntRemover(Ant):
"""Allows the player to remove ants from the board in the GUI."""
name = 'Remover'
implemented = False
def __init__(self):
super().__init__(0)
class Bee(Insect):
"""A Bee moves from place to place, following exits and stinging ants."""
name = 'Bee'
damage = 1
is_waterproof = True
def sting(self, ant):
"""Attack an ANT, reducing its health by 1."""
ant.reduce_health(self.damage)
def move_to(self, place):
"""Move from the Bee's current Place to a new PLACE."""
self.place.remove_insect(self)
place.add_insect(self)
def action(self, gamestate):
"""A Bee's action stings the Ant that blocks its exit if it is blocked,
or moves to the exit of its current place otherwise.
gamestate -- The GameState, used to access game state information.
"""
destination = self.place.exit
if self.blocked():
self.sting(self.place.ant)
elif self.health > 0 and destination is not None:
self.move_to(destination)
def add_to(self, place):
place.bees.append(self)
Insect.add_to(self, place)
def remove_from(self, place):
place.bees.remove(self)
Insect.remove_from(self, place)
############
# Statuses #
############
class SlowThrower(ThrowerAnt):
"""ThrowerAnt that causes Slow on Bees."""
name = 'Slow'
food_cost = 6
implemented = True # Change to True to view in the GUI
def throw_at(self, target):
target.slowed_turns = 5
def new_action(gamestate):
if target.slowed_turns > 0:
if gamestate.time % 2 == 0:
Bee.action(target, gamestate)
target.slowed_turns -= 1
else:
Bee.action(target, gamestate)
target.action = new_action
##################
# Bees Extension #
##################
class Wasp(Bee):
"""Class of Bee that has higher damage."""
name = 'Wasp'
damage = 2
class Hornet(Bee):
"""Class of bee that is capable of taking two actions per turn, although
its overall damage output is lower. Immune to statuses.
"""
name = 'Hornet'
damage = 0.25
def action(self, gamestate):
for i in range(2):
if self.health > 0:
super().action(gamestate)
def __setattr__(self, name, value):
if name != 'action':
object.__setattr__(self, name, value)
class Boss(Wasp, Hornet):
"""The leader of the bees. Combines the high damage of the Wasp along with
status immunity of Hornets. Damage to the boss is capped up to 8
damage by a single attack.
"""
name = 'Boss'
damage_cap = 8
action = Wasp.action
def reduce_health(self, amount):
super().reduce_health(self.damage_modifier(amount))
def damage_modifier(self, amount):
return amount * self.damage_cap / (self.damage_cap + amount)
class Hive(Place):
"""The Place from which the Bees launch their assault.
assault_plan -- An AssaultPlan; when & where bees enter the colony.
"""
is_hive = True
def __init__(self, assault_plan):
self.name = 'Hive'
self.assault_plan = assault_plan
self.bees = []
for bee in assault_plan.all_bees:
self.add_insect(bee)
# The following attributes are always None for a Hive
self.entrance = None
self.ant = None
self.exit = None
def strategy(self, gamestate):
exits = [p for p in gamestate.places.values() if p.entrance is self]
for bee in self.assault_plan.get(gamestate.time, []):
bee.move_to(random.choice(exits))
gamestate.active_bees.append(bee)
class GameState:
"""An ant collective that manages global game state and simulates time.
Attributes:
time -- elapsed time
food -- the colony's available food total
places -- A list of all places in the colony (including a Hive)
bee_entrances -- A list of places that bees can enter
"""
def __init__(self, strategy, beehive, ant_types, create_places, dimensions, food=2):
"""Create an GameState for simulating a game.
Arguments:
strategy -- a function to deploy ants to places
beehive -- a Hive full of bees
ant_types -- a list of ant classes
create_places -- a function that creates the set of places
dimensions -- a pair containing the dimensions of the game layout
"""
self.time = 0
self.food = food
self.strategy = strategy
self.beehive = beehive
self.ant_types = OrderedDict((a.name, a) for a in ant_types)
self.dimensions = dimensions
self.active_bees = []
self.configure(beehive, create_places)
self.queen_created = False
def configure(self, beehive, create_places):
"""Configure the places in the colony."""
self.base = AntHomeBase('Ant Home Base')
self.places = OrderedDict()
self.bee_entrances = []
def register_place(place, is_bee_entrance):
self.places[place.name] = place
if is_bee_entrance:
place.entrance = beehive
self.bee_entrances.append(place)
register_place(self.beehive, False)
create_places(self.base, register_place, self.dimensions[0], self.dimensions[1])
def simulate(self):
"""Simulate an attack on the ant colony (i.e., play the game)."""
num_bees = len(self.bees)
try:
while True:
self.beehive.strategy(self) # Bees invade
self.strategy(self) # Ants deploy
for ant in self.ants: # Ants take actions
if ant.health > 0:
ant.action(self)
for bee in self.active_bees[:]: # Bees take actions
if bee.health > 0:
bee.action(self)
if bee.health <= 0:
num_bees -= 1
self.active_bees.remove(bee)
if num_bees == 0:
raise AntsWinException()
self.time += 1
except AntsWinException:
print('All bees are vanquished. You win!')
return True
except AntsLoseException:
print('The ant queen has perished. Please try again.')
return False
def deploy_ant(self, place_name, ant_type_name):
"""Place an ant if enough food is available.
This method is called by the current strategy to deploy ants.
"""
ant_type = self.ant_types[ant_type_name]
ant = ant_type.construct(self)
if ant:
self.places[place_name].add_insect(ant)
self.food -= ant.food_cost
return ant
def remove_ant(self, place_name):
"""Remove an Ant from the game."""
place = self.places[place_name]
if place.ant is not None:
place.remove_insect(place.ant)
@property
def ants(self):
return [p.ant for p in self.places.values() if p.ant is not None]
@property
def bees(self):
return [b for p in self.places.values() for b in p.bees]
@property
def insects(self):
return self.ants + self.bees
def __str__(self):
status = ' (Food: {0}, Time: {1})'.format(self.food, self.time)
return str([str(i) for i in self.ants + self.bees]) + status
class AntHomeBase(Place):
"""AntHomeBase at the end of the tunnel, where the queen resides."""
def add_insect(self, insect):
"""Add an Insect to this Place.
Can't actually add Ants to a AntHomeBase. However, if a Bee attempts to
enter the AntHomeBase, a AntsLoseException is raised, signaling the end
of a game.
"""
assert isinstance(insect, Bee), 'Cannot add {0} to AntHomeBase'
raise AntsLoseException()
def ants_win():
"""Signal that Ants win."""
raise AntsWinException()
def ants_lose():
"""Signal that Ants lose."""
raise AntsLoseException()
def ant_types():
"""Return a list of all implemented Ant classes."""
all_ant_types = []
new_types = [Ant]
while new_types:
new_types = [t for c in new_types for t in c.__subclasses__()]
all_ant_types.extend(new_types)
return [t for t in all_ant_types if t.implemented]
class GameOverException(Exception):
"""Base game over Exception."""
pass
class AntsWinException(GameOverException):
"""Exception to signal that the ants win."""
pass
class AntsLoseException(GameOverException):
"""Exception to signal that the ants lose."""
pass
def interactive_strategy(gamestate):
"""A strategy that starts an interactive session and lets the user make
changes to the gamestate.
For example, one might deploy a ThrowerAnt to the first tunnel by invoking
gamestate.deploy_ant('tunnel_0_0', 'Thrower')
"""
print('gamestate: ' + str(gamestate))
msg = '<Control>-D (<Control>-Z <Enter> on Windows) completes a turn.\n'
interact(msg)
###########
# Layouts #
###########
def wet_layout(queen, register_place, tunnels=3, length=9, moat_frequency=3):
"""Register a mix of wet and and dry places."""
for tunnel in range(tunnels):
exit = queen
for step in range(length):
if moat_frequency != 0 and (step + 1) % moat_frequency == 0:
exit = Water('water_{0}_{1}'.format(tunnel, step), exit)
else:
exit = Place('tunnel_{0}_{1}'.format(tunnel, step), exit)
register_place(exit, step == length - 1)
def dry_layout(queen, register_place, tunnels=3, length=9):
"""Register dry tunnels."""
wet_layout(queen, register_place, tunnels, length, 0)
#################
# Assault Plans #
#################
class AssaultPlan(dict):
"""The Bees' plan of attack for the colony. Attacks come in timed waves.
An AssaultPlan is a dictionary from times (int) to waves (list of Bees).
>>> AssaultPlan().add_wave(4, 2)
{4: [Bee(3, None), Bee(3, None)]}
"""
def add_wave(self, bee_type, bee_health, time, count):
"""Add a wave at time with count Bees that have the specified health."""
bees = [bee_type(bee_health) for _ in range(count)]
self.setdefault(time, []).extend(bees)
return self
@property
def all_bees(self):
"""Place all Bees in the beehive and return the list of Bees."""
return [bee for wave in self.values() for bee in wave]