Project 3: Ants Vs. SomeBees

The bees are coming!
Create a better soldier
With inherit-ants.
Introduction
Important submission note: For full credit,
- Submit with Phases 1 & 2 complete by Tuesday, November 26 (worth 1 pt).
- Submit with Phases 3 & 4 complete by Friday, November 29.
You may work with one other partner for the entire project.
In this project, you will create a tower defense game called Ants Vs. SomeBees. As the ant queen, you populate your colony with the bravest ants you can muster. Your ants must protect their queen from the evil bees that invade your territory. Irritate the bees enough by throwing leaves at them, and they will be vanquished. Fail to pester the airborne intruders adequately, and your queen will succumb to the bees' wrath. This game is inspired by PopCap Games' Plants Vs. Zombies.
This project combines functional and object-oriented programming paradigms, focusing on the material from Chapter 2.5 of Composing Programs. The project also involves understanding, extending, and testing a large program.
Download starter files
The ants.zip archive contains several files, but all of your
changes will be made to ants.py.
ants.py: The game logic of Ants Vs. SomeBeesants_gui.py: The original GUI for Ants Vs. SomeBeesgui.py: A new GUI for Ants Vs. SomeBeesgraphics.py: Utilities for displaying simple two-dimensional animationsstate.py: Abstraction for gamestate forgui.pyutils.py: Some functions to facilitate the game interfaceucb.py: Utility functions for CS 61Aassets: A directory of images and files used bygui.pyimg: A directory of images used byants_gui.py
Logistics
This is a 8-day project. You may work with one other partner. You should not share your code with students who are not your partner or copy from anyone else's solutions. In the end, you will submit one project for both partners. We strongly encourage you to work on all parts of the project together rather than splitting up the work. Switch off who writes the code, but whoever is not coding should contribute by looking at the code and providing comments on a direction to go and catching bugs.
The project is worth 30 points. 27 points are assigned for correctness, 1 point for submitting Phases 1-2 by the checkpoint date, and 2 points for the overall composition.
You will turn in the following files:
ants.py
You do not need to modify or turn in any other files to complete the project.
For the functions that we ask you to complete, there may be some initial code that we provide. If you would rather not use that code, feel free to delete it and start from scratch. You may also add new function definitions as you see fit.
However, please do not modify any other functions. Doing so may result in your code failing our autograder tests. Also, please do not change any function signatures (names, argument order, or number of arguments).
Throughout this project, you should be testing the correctness of your code. It is good practice to test often, so that it is easy to isolate any problems. However, you should not be testing too often, to allow yourself time to think through problems.
We recommend that you submit after you finish each problem. Only your last submission will be graded. It is also useful for us to have more backups of your code in case you run into a submission issue.
The Game
A game of Ants Vs. SomeBees consists of a series of turns. In each turn, new bees may enter the ant colony. Then, new ants are placed to defend their colony. Finally, all insects (ants, then bees) take individual actions. Bees either try to move toward the end of the tunnel or sting ants in their way. Ants perform a different action depending on their type, such as collecting more food, or throwing leaves at the bees. The game ends either when a bee reaches the ant queen (you lose), or the entire bee fleet has been vanquished (you win).
Core concepts
The Colony. This is where the game takes place. The colony consists of several places that are chained together to form a tunnel where bees can travel through. The colony has some quantity of food that can be expended to deploy ant troops.
Places. A place links to another place to form a tunnel. The player can place a single ant into each place. However, there can be many bees in a single place.
The Hive. This is the place where bees originate. Bees exit the beehive to enter the ant colony.
Ants. Ants are the usable troops in the game that the player places into
the colony. Each type of ant takes a different action and requires a different
amount of food to place. The two most basic ant types are the HarvesterAnt,
which adds one food to the colony during each turn, and the ThrowerAnt, which
throws a leaf at a bee each turn. You will be implementing many more.
Bees. Bees are the antagonistic troops in the game that the player must defend the colony from. Each turn, a bee either advances to the next place in the tunnel if no ant is in its way, or it stings the ant in its way. Bees win when at least one bee reaches the end of a tunnel.
Queen Ant: There is one queen ant in the whole colony. She is able to attack bees but she also has a special ability of fortifying the other ant troops. Bees can also win if they destroy the queen ant.
Core classes
The concepts described above each have a corresponding class that encapsulates the logic for that concept. Here is a summary of the main classes involved in this game:
AntColony: Represents the colony and some state information about the game, including how much food is available, how much time has elapsed, where theQueenAntresides, and all thePlaces in the game.Place: Represents a single place that holds insects. At most oneAntcan be in a single place, but there can be manyBees.Placeobjects have anexitand anentrancewhich are also places. Bees travel through a tunnel by moving to aPlace'sexit.Hive: Represents the place whereBees start out.Insect: A superclass forAntandBee. All insects have anarmorattribute, their remaining health, and aplaceattribute, thePlacewhere they are currently located. Each turn, every activeInsectin the game performs itsaction.Ant: Represents ants. EachAntsubclass has special attributes or a specialactionthat distinguish it from otherAnttypes. For example, aHarvesterAntgets food for the colony and aThrowerAntattacksBees. Each ant type also has afood_costattribute that indicates how much it costs to deploy one unit of that type of ant.Bee: Represents bees. Each turn, a bee either moves to theexitof its currentPlaceif no ant blocks its path, or stings an ant that blocks its path.
Game Layout
Below is a visualization of an AntColony. As you work through the unlocking tests and problems, we recommend drawing out similar diagrams to help your understanding.
Playing the game
The game can be run in two modes: as a text-based game or using a graphical user interface (GUI). The game logic is the same in either case, but the GUI enforces a turn time limit that makes playing the game more exciting. The text-based interface is provided for debugging and development.
The files are separated according to these two modes. ants.py knows
nothing of graphics or turn time limits.
To start a text-based game, run
python3 ants.py
To start a graphical game, run
python3 gui.py
To start an older version of the graphics, run
python3 ants_gui.py
When you start the graphical version, a new browser window should appear. In the
starter implementation, you have unlimited food and your ants can only throw leaves
at bees in their current Place. Try playing the game anyway! You'll need to
place a lot of ThrowerAnts (the second type) in order to keep the bees from
reaching your queen.
The game has several options that you will use throughout the project,
which you can view with python3 ants.py --help.
usage: ants.py [-h] [-d DIFFICULTY] [-w] [--food FOOD]
Play Ants vs. SomeBees
optional arguments:
-h, --help show this help message and exit
-d DIFFICULTY sets difficulty of game (test/easy/medium/hard/extra-hard)
-w, --water loads a full layout with water
--food FOOD number of food to start with when testing
Your own test cases
Adding your own tests is entirely optional.
We highly recommend that you do your own tests as you work through the project. It's a really helpful way to speed up the debugging process and improve your understanding of the code.
You may also find our
debugging guide helpful. If you're
stuck on a particularly tricky Ok test case, a good first step would be to
break it up into small parts and test them out.
Phase 1: Basic gameplay
Important submission note: For full credit,
- Submit with Phases 1-2 complete by Tuesday, November 26 (worth 1 pt).
In the first phase you will complete the implementation that will allow for
basic gameplay with the two basic Ants: the HarvesterAnt and the
ThrowerAnt.
Problem 0 (0 pt)
Answer the following questions with your partner after you have read the
entire ants.py file. If you cannot answer these questions, read the file
again, consult the core concepts/classes sections above.
- What is the significance of an insect's
armorattribute? Does this value change? If so, how? - What are all of the attributes of the
Insectclass? - Is the
armorattribute of theAntclass an instance attribute or class attribute? Why? - Is the
damageattribute of anAntsubclass (such as ThrowerAnt) an instance attribute or class attribute? Why? - Which class do both
AntandBeeinherit from? - What do instances of
Antand instances ofBeehave in common? - How many insects can be in a single
Placeat any given time (until Problem 9 is complete)? - What does a
Beedo during its turn? - When does the game end?
Problem 1 (1 pt)
First, add food costs and implement harvesters. Currently, there is no cost
for deploying any type of Ant, and so there is no challenge to the
game. You'll notice that Ant starts out with a base food_cost of
zero. Override this value in each of the subclasses listed below with
the correct costs.
| Class | Food Cost | Armor |
HarvesterAnt |
2 | 1 |
ThrowerAnt |
3 | 1 |
Now that deploying Ants cost food, we need to be able gather more food!
To fix this issue, implement the HarvesterAnt class. A HarvesterAnt is a
type of Ant that adds one food to the colony.food total as its action.
Try playing the game by running python3 gui.py. Once you have placed a
HarvesterAnt, you should accumulate food each turn. You can also place
ThrowerAnts, but you'll see that they can only attack bees that are in their
Place, so it'll be a little difficult to win.
Problem 2 (3 pt)
Complete the Place constructor by adding code that tracks entrances. Right
now, a Place keeps track only of its exit. We would like a Place to keep
track of its entrance as well. A Place needs to track only one entrance.
Tracking entrances will be useful when an Ant needs to see what Bees are in
front of it in the tunnel.
However, simply passing an entrance to a Place constructor will be
problematic; we would need to have both the exit and the entrance before
creating a Place! (It's a chicken or the
egg
problem.) To get around this problem, we will keep track of entrances in the
following way instead. The Place constructor should specify that:
- A newly created
Placealways starts with itsentranceasNone. - If the
Placehas anexit, then theexit'sentranceis set to thatPlace.
Hint: Remember that when inside the definition of an
__init__method, the nameselfis bound to the newly created object.
Hint: Try drawing out two
Places next to each other if things get confusing. In the GUI, a place'sentranceis to its right while the exit is to its left.
Problem 3 (2 pt)
In order for a ThrowerAnt to attack, it must know which bee it should hit.
The provided implementation of the nearest_bee method in the ThrowerAnt
class only allows them to hit bees in the same Place. Your job is to fix it
so that a ThrowerAnt will throw_at the nearest bee in front of it that is
not still in the Hive.
The nearest_bee method returns a random Bee from the nearest place that
contains bees. Places are inspected in order by following their entrance
attributes.
- Start from the current
Placeof theThrowerAnt. - For each place, return a random bee if there is any, or consider the
next place that is stored as the current place's
entrance. - If there is no bee to attack, return
None.
Hint: The
random_or_nonefunction provided inants.pyreturns a random element of a sequence orNoneif the sequence is empty.Hint: Having trouble visualizing the test cases? Try drawing them out on paper! The example diagram provided in Game Layout shows the first test case for this problem.
After implementing nearest_bee, a ThrowerAnt should be able to throw_at a
Bee in front of it that is not still in the Hive. Make sure that your ants
do the right thing! To start a game with ten food (for easy testing):
python3 gui.py --food 10
Phase 2: Ants!
Now that you've implemented basic gameplay with two types of Ants, let's
add some flavor to the ways ants can attack bees. In this phase, you'll be
implementing several different Ants with different offensive capabilities.
After you implement each Ant subclass in this section, you'll need to set its
implemented attribute to True so that that type of ant will show up in the
GUI. Feel free to try out the game with each new ant to test the functionality!
With your Phase 2 ants, try python3 gui.py -d easy to play against a
full swarm of bees in a multi-tunnel layout and try -d normal, -d hard, or
-d extra-hard if you want a real challenge! If the bees are too numerous to
vanquish, you might need to create some new ants.
Problem 4 (2 pt)
The ThrowerAnt is a great offensive unit, but it'd be nice to have a cheaper
unit that can throw. Implement two subclasses of ThrowerAnt that are less
costly but have constraints on the distance they can throw:
- The
LongThrowercan onlythrow_ataBeethat is found after following at least 5entrancetransitions. It cannot hitBees that are in the samePlaceas it or the first 4Places in front of it. If there are twoBees, one too close to theLongThrowerand the other within its range, theLongThrowershould throw past the closerBee, instead targeting the farther one, which is within its range. - The
ShortThrowercan onlythrow_ataBeethat is found after following at most 3entrancetransitions. It cannot throw at any ants further than 3Places in front of it.
Neither of these specialized throwers can throw_at a Bee that is exactly 4
Places away. Placing a single one of these (and no other ants) should never
win a default game.
| Class | Food Cost | Armor |
ShortThrower |
2 | 1 |
LongThrower |
2 | 1 |
A good way to approach the implementation to ShortThrower and LongThrower
is to have it inherit the nearest_bee method from the base ThrowerAnt
class. The logic of choosing which bee a thrower ant will attack is essentially
the same, except the ShortThrower and LongThrower ants have maximum and
minimum ranges, respectively.
To implement these behaviors, you may need to modify the nearest_bee method
to reference min_range and max_range attributes, and only return a bee that
is in range.
The original ThrowerAnt has no minimum or maximum range, so make sure that
its min_range and max_range attributes should reflect that. Then,
implement the subclasses LongThrower and ShortThrower with appropriately
constrained ranges and correct food costs.
Hint:
float('inf')returns an infinite positive value represented as a float that can be compared with other numbers.
Don't forget to set the implemented class attribute of LongThrower and
ShortThrower to True.
Note! Please make sure your variables are called
max_rangeandmin_rangerather thanmaximum_rangeandminimum_rangeor something. The tests directly reference this variable name.
Problem 5 (3 pt)
Implement the FireAnt, which does damage when it receives damage. Specifically,
if it is damaged by x armor units, and does not die, it does a damage of
x to all bees in it's place (reflected damage).
If it dies, it does an additional amount of damage, which is specified by its damage attribute (by default 3).
To implement this, we have to override the FireAnt's
reduce_armor method. Normally, Insect.reduce_armor will decrement the
insect's armor by the given amount and remove the insect from its place if
armor reaches zero or lower. However, FireAnt also does damage to all the
bees in it's place when it receives damage, with a special bonus when it's damage
drops to 0, before being removed from its place.
| Class | Food Cost | Armor |
FireAnt |
5 | 3 |
Hint: To damage a
Bee, call thereduce_armormethod inherited fromInsect.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
listfunction.>>> 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
Insect.reduce_armorfunction, you can still use it in your implementation by calling it directly (rather than viaself). Note that this is not recursion (why?)
You can also test your program by playing a game or two! A FireAnt should
destroy all co-located Bees when it is stung. To start a game with ten food
(for easy testing):
python3 gui.py --food 10
Problem 6 (2 pt)
Implement the HungryAnt, which will select a random Bee from its place
and eat it whole. After eating a Bee, it must spend 3 turns digesting before
eating again. If there is no bee available to eat, it will do nothing.
| Class | Food Cost | Armor |
HungryAnt |
4 | 1 |
Give HungryAnt a time_to_digest class attribute that holds the number of
turns that it takes a HungryAnt to digest (default to 3). Also, give each
HungryAnt an instance attribute digesting that counts the number of turns
it has left to digest (default is 0, since it hasn't eaten anything at the
beginning).
Implement the action method of the HungryAnt to check if it's digesting; if
so, decrement its digesting counter. Otherwise, eat a random Bee in its
place by reducing the Bee's armor to 0 and restart the digesting timer.
Problem 7 (2 pt)
Implement the NinjaAnt, which damages all Bees that pass by, but can never
be stung.
| Class | Food Cost | Armor |
NinjaAnt |
5 | 1 |
A NinjaAnt does not block the path of a Bee that flies by. To implement
this behavior, first modify the Ant class to include a new class attribute
blocks_path that is True by default. Set the value of blocks_path to
False in the NinjaAnt class.
Second, modify the Bee's method blocked to return False if either
there is no Ant in the Bee's place or if there is an Ant, but
its blocks_path attribute is False. Now Bees will just fly past
NinjaAnts.
Finally, we want to make the NinjaAnt damage all Bees that fly past.
Implement the action method in NinjaAnt to reduce the armor of all Bees
in the same place as the NinjaAnt by its damage attribute. Similar to
the FireAnt, you must iterate over a list of bees that may change.
Hint: Having trouble visualizing the test cases? Try drawing them out on paper! See the example in Game Layout for help.
For a challenge, try to win a game using only HarvesterAnt
and NinjaAnt.
Congratulations! You have finished Phases 1 and 2 of this project!
Phase 3: More Ants!
Important submission note: For full credit,
- Submit with Phases 3-4 complete by Friday, November 29.
We now have some great offensive troops to help vanquish the bees, but let's make sure we're also keeping our defensive efforts up. In this phase you will implement ants that have special defensive capabilities such as increased armor and the ability to protect other ants.
Problem 8 (1 pt)
We are going to add some protection to our glorious
AntColonyby implementing theWallAnt, which is an ant that does nothing each turn. AWallAntis useful because it has a largearmorvalue.
Class Food Cost Armor ![]()
WallAnt4 4 Unlike with previous ants, we have not provided you with a class header. Implement the
WallAntclass from scratch. Give it a class attributenamewith the value'Wall'(so that the graphics work) and a class attributeimplementedwith the valueTrue(so that you can use it in a game).Problem 9 (4 pt)
Right now, our ants are quite frail. We'd like to provide a way to help them last longer against the onslaught of the bees. Enter the
BodyguardAnt.
Class Food Cost Armor ![]()
BodyguardAnt4 2 A
BodyguardAntdiffers from a normal ant because it is a container; it can contain another ant and protect it, all in onePlace. When aBeestings the ant in aPlacewhere one ant contains another, only the container is damaged. The ant inside the container can still perform its original action. If the container perishes, the contained ant still remains in the place (and can then be damaged).Each
BodyguardAnthas an instance attributecontained_antthat stores the ant it contains. It initially starts off asNone, to indicate that no ant is being protected. Implement thecontain_antmethod so that it sets the bodyguard'scontained_antinstance attribute to the passed inantargument. Also implement theBodyguardAnt'sactionmethod to perform itscontained_ant's action if it is currently containing an ant.In addition, you will need to make the following modifications throughout your program so that a container and its contained ant can both occupy a place at the same time (a maximum of two ants per place), but only if exactly one is a container:
- Add an
Ant.is_containerclass attribute that indicates whether a subclass ofAntis a container. For allAntinstances, except forBodyguardAntinstances,is_containershould beFalse. TheBodyguardAnt.is_containerattribute should beTrue.Implement the method
BodyguardAnt.can_containwhich takes anotherant as an argument and returnsTrueif:
- This ant does not already contain another ant.
- The other ant is not a container.
Currently
Ant.can_containreturns False by default; it needs to be overridden inBodyguardAntModify
Place.add_insectto allow a container and a non-container ant to occupy the same place according to the following rules:
- If the
antcurrently occupying aPlacecan contain theinsect(anAnt) passed toadd_insect, then it does.- If the
insect(anAnt) passed toadd_insectcan contain theantcurrently occupying aPlace, then it does. Also, set thePlace'santto be the container insect.- If neither
Antcan contain the other, raise the sameAssertionErroras before (the one already present in the starter code).Problem 10 (1 pt)
The
BodyguardAntprovides great defense, but they say the best defense is a good offense. TheTankAntis a container that protects an ant in its place and also deals 1 damage to all bees in its place each turn.
Class Food Cost Armor ![]()
TankAnt6 2 You should not need to modify any code outside of the
TankAntclass. If you find yourself needing to make changes elsewhere, look for a way to write your code for the previous question such that it applies not just toBodyguardAntandTankAntobjects, but to container ants in general.Phase 4: Water and Might
In the final phase, you're going to add one last kick to the game by introducing a new type of place and new ants that are able to occupy this place. One of these ants is the most important ant of them all: the queen of the colony.
Problem 11 (1 pt)
Let's add water to the colony! Currently there are only two types of places, the
Hiveand a basicPlace. To make things more interesting, we're going to create a new type ofPlacecalledWater.Only an ant that is watersafe can be deployed to a
Waterplace. In order to determine whether anInsectis watersafe, add a new attribute to theInsectclass namedis_watersafethat isFalseby default. Since bees can fly, make theiris_watersafeattributeTrue, overriding the default.Now, implement the
add_insectmethod forWater. First, add the insect to the place regardless of whether it is watersafe. Then, if the insect is not watersafe, reduce the insect's armor to 0. Do not repeat code from elsewhere in the program. Instead, use methods that have already been defined.Once you've finished this problem, play a game that includes water. To access the
wet_layoutwhich includes water, add the--wateroption (or-wfor short) when you start the game.python3 gui.py --waterProblem 12 (1 pt)
Currently there are no ants that can be placed on
Water. Implement theScubaThrower, which is a subclass ofThrowerAntthat is more costly and watersafe, but otherwise identical to its base class. AScubaThrowershould not lose its armor when placed inWater.
Class Food Cost Armor ![]()
ScubaThrower6 1 We have not provided you with a class header. Implement the
ScubaThrowerclass from scratch. Give it a class attributenamewith the value'Scuba'(so that the graphics work) and remember to set the class attributeimplementedwith the valueTrue(so that you can use it in a game).Problem 13 (4 pt)
Finally, implement the
QueenAnt. The queen is a waterproofScubaThrowerthat inspires her fellow ants through her bravery. TheQueenAntdoubles the damage of all the ants behind her each time she performs an action. Once an ant's damage has been doubled, it is not doubled again for subsequent turns.Note that the reflected damage of a fire ant should not be doubled, only the extra damage it deals when it's armor is reduced to 0
Class Food Cost Armor ![]()
QueenAnt7 1 However, with great power comes great responsibility. The
QueenAntis governed by three special rules:
- If the queen ever has its armor reduced to 0, the bees win. The bees also still win if any bee reaches the end of a tunnel. You can call
bees_win()to signal to the simulator that the game is over.- There can be only one true queen. Any queen instantiated beyond the first one is an impostor, and should have its armor reduced to 0 upon taking its first action, without doubling any ant's damage or throwing anything. If an impostor dies, the game should still continue as normal.
- The true (first) queen cannot be removed. Attempts to remove the queen should have no effect (but should not cause an error). You will need to modify the
remove_insectmethod ofPlaceto enforce this condition.Some hints:
- All instances of the same class share the same class attributes. How can you use this information to tell whether a QueenAnt instance is the true QueenAnt?
- You can find each
Placein a tunnel behind theQueenAntby starting at the ant'splace.exitand then repeatedly following itsexit. Theexitof aPlaceat the end of a tunnel isNone.- To avoid doubling an ant's damage twice, keep track of all the ants who have been buffed in a way that persists across calls to
QueenAnt.action.- When buffing the ants' damage, keep in mind that there can be more than one ant in one place!
You may find the
isinstancefunction useful for checking if an object is an instance of a given class. For example:>>> a = Foo() >>> isinstance(a, Foo) TrueExtra Credit (2 pt)
During Office Hours and Project Parties, the staff will prioritize helping students with required questions. We will not be offering help with this question unless the queue is empty.
Implement two final thrower ants that do zero damage, but instead produce a temporary "effect" on the
actionmethod of aBeeinstance that theythrow_at. This effect is an alternative action that lasts for a certain number of.action(colony)calls, after which theBee's action reverts to its previous behavior.We will be implementing two new ants that subclass
ThrowerAnt.
SlowThrowerthrows sticky syrup at a bee, applying a slow effect for 3 turns.ScaryThrowerintimidates a nearby bee, causing it to back away instead of advancing. (If the bee is already right next to the Hive and cannot go back further, it should not move.) The scare effect lasts for 2 turns. Once a bee has been scared once, it can't be scared again.
Class Food Cost Armor ![]()
SlowThrower4 1 ![]()
ScaryThrower6 1 In order to complete the implementations of these two ants, you will need to set their class attributes appropriately and implement the following three functions:
make_slowis an effect that takes anactionmethod and abee, and returns a newactionmethod that performs the original action on turns wherecolony.timeis even and does nothing on other turns.make_scareis an effect that takes anactionmethod and abee, and returns a newactionmethod that makes the bee go backwards.apply_effecttakes aneffect(eithermake_slowormake_scare), aBee, and aduration. It uses the effect on theBee's.actionmethod to produce a newactionmethod, and then arranges to have the new method become the bee's action method for the nextdurationtimes that.actionis called, after which the previous.actionmethod is restored.Hint: to make a bee go backwards, consider adding an instance variable indicating its current direction. Where should you change the bee's direction? Once the direction is known, how can you modify the
actionmethod ofBeeto move appropriately?Hint: To prevent the same bee from being scared twice, you will also need to add an instance variable to
Beeand set it appropriately!Hint: You will need to rebind a method in one of the functions. Note that when assigning to an instance, the self parameter isn't bound.
class X: pass def f(x): return x ** 3 x = X() x.f = f print(x.f(2)) # prints 8As an example of what "previous behavior" means, take the example of a bee that has been slowed twice (say by two separate
SlowThrowers). It will have the following behavior
- on time 1, it will do nothing. The outer slow has 2 turns to go, the inner one still has 3 turns
- on time 2, it moves forward. The outer slow has 1 turn to go, the inner one has 2 turns
- on time 3, it will do nothing. The outer slow has no turns left, the inner one has 2 turns
- on time 4, it moves forward. The inner slow has 1 turn left
- on time 5, it does nothing. The inner slow has no turns left
Make sure to test your code! Your code should be able to apply multiple effects on a target; each new effect applies to the current (possibly affected) action method of the bee.
Optional Problem (0 pt)
We've been developing this ant for a long time in secret. It's so dangerous that we had to lock it in the super hidden CS61A underground vault, but we finally think it's ready to go out on the field. In this problem, you'll be implementing the final ant --
LaserAnt, aThrowerAntwith a twist.
Class Food Cost Armor ![]()
LaserAnt10 1 The
LaserAntshoots out a powerful laser, damaging all that dare to stand in its path. BothBees andAnts, of all types, are at risk of being damaged byLaserAnt. When aLaserAnttakes its action, it will damage allInsects in its place (excluding itself, but including its container if it has one) and thePlaces in front of it, excluding theHive.But, if that were it,
LaserAntwould be too powerful for us to contain. TheLaserAnthas a base damage of2. But,LaserAnt's laser comes with some quirks. It is weakened by0.2each place it travels away fromLaserAnt's place. Additionally,LaserAnt's laser has limited battery. Each timeLaserAntactually damages anInsectits laser's total damage goes down by0.05. IfLaserAnt's damage becomes negative due to these restrictions, it simply does 0 damage instead.In order to complete the implementation of this ultimate ant, read through the
LaserAntclass, set the class attributes appropriately, and implement the following two functions:
insects_in_frontis an instance method, called by theactionmethod, that takes inbeehive(the currentHive), and returns a dictionary where each key is anInsectand each corresponding value is the distance (in places) that thatInsectis away fromLaserAnt. The dictionary should include allInsectson the same place or in front of theLaserAnt, excludingLaserAntitself.
calculate_damageis an instance method that takes indistance, the distance that an insect is away from theLaserAntinstance. It returns the damage that theLaserAntinstance should afflict based on:
- The
distanceaway from theLaserAntinstance that anInsectis.- The number of
Insectsthat thisLaserAnthas damaged, stored in theinsects_shotinstance attribute.In addition to implementing the methods above, you may need to modify, add, or use class or instance attributes to the
LaserAntclass as needed.Make sure to test your code!
Submission
Again, you will be turning in the following files:
ants.pyConclusion
You are now done with the project! If you haven't yet, you should try playing the game! There are two GUIs that you can use. The first is a new browser GUI that has fancy graphics and animations. The command to run it is:
python3 gui.py [-h] [-d DIFFICULTY] [-w] [--food FOOD]The second is an older, but tried-and-true interface that we have been using over the past few years. The command to run it is:
python3 ants_gui.py [-h] [-d DIFFICULTY] [-w] [--food FOOD]Acknowledgments: Tom Magrino and Eric Tzeng developed this project with John DeNero. Jessica Wan contributed the original artwork. Joy Jeng and Mark Miyashita invented the queen ant. Many others have contributed to the project as well!
Colin Schoen developed the new browser GUI. The beautiful new artwork was drawn by the efforts of Alana Tran, Andrew Huang, Emilee Chen, Jessie Salas, Jingyi Li, Katherine Xu, Meena Vempaty, Michelle Chang, and Ryan Davis.