Problem 5 (250pts): Fire Ant
Implement the FireAnt
, which does damage when it receives damage.
Specifically, if it is damaged by health
health units, it does a damage of health
to all bees in its place (this is called reflected damage).
If it dies, it does an additional amount of damage, which is specified by its damage
attribute, which has a default value of 3 as defined in the FireAnt
class.
To implement this, we have to override the FireAnt
's reduce_health
method.
Your overriden method should call the reduce_health
method inherited from the superclass (Ant
) which inherits from it's superclass Insect
to reduce the current FireAnt
instance's health.
Calling the inherited reduce_health
method on a FireAnt
instance reduces the insect's health
by the given amount
and removes the insect from its place if its health
reaches zero or lower.
Hint: Do not call
self.reduce_health
, or you'll end up stuck in a recursive loop. (Can you see why?)
However, your method needs to also include the reflective damage logic:
- Determine the reflective damage amount: start with the
amount
inflicted on the ant, and then adddamage
if the ant's health has dropped to or below 0. - For each bee in the place, damage them with the total amount by calling the appropriate
reduce_health
method for each bee.
Important: Remember that when any
Ant
loses all itshealth
, it is removed from its place, so pay careful attention to the order of your logic inreduce_health
.
Class | Food Cost | Health | |
---|---|---|---|
![]() | FireAnt | 5 | 3 |
Hint: Damaging a bee may cause it to be removed from its place. If you iterate over a list, but change the contents of that list at the same time, you may not visit all the elements. This can be prevented by making a copy of the list. You can either use a list slice, or use the built-in
list
function to make sure we do not affect the original list.>>> lst = [1,2,3,4] >>> lst[:] [1, 2, 3, 4] >>> list(lst) [1, 2, 3, 4] >>> lst[:] is not lst and list(lst) is not lst True
Once you've finished implementing the FireAnt
, give it a class attribute implemented
with the value True
.
Note: Even though you are overriding the superclass's
reduce_health
function (Ant.reduce_health
), you can still use it in your implementation by calling it directly (rather than viaself
). Note that this is not recursion. (Why not?)
Before writing any code, unlock the tests to verify your understanding of the question:
$ python3 ok -q 05 -u
Once you are done unlocking, begin implementing your solution. You can check your correctness with:
$ python3 ok -q 05
You can also test your program by playing a game or two!
A FireAnt
should destroy all co-located Bee
s when it is stung.
To start a game with ten food (for easy testing):
$ python3 gui.py --food 10