This lesson we will simulate behavior of ants.
Use this class for the exercises.
Create a class Food
.
Each Food
has an amount, represented as an integer. It is passed as a parameter to the constructor.
The amount of the food can be accessed by getAmount
.
removeFood
should remove 1 unit of food, if the current amount is positive. It should return true in that case. If the amount is zero, it should return false and leave the amount at zero.
Only one of the getAmount
or removeFood
functions can be called on the same object at a time. (Needs synchronization.)
Create the class Environment
that will store the location of food on a grid.
It should get the size of the area (height and width) as constructor parameters.
It stores food in a thread-safe map.
The update method will generate a new food and place it on the map. The location of the food should be random.
Implement the function hasFood
that takes a point and returns a boolean value.
Implement the function dropFood
that takes a point and increments the amount of food by one at that point.
Create a class Ant
.
Each ant has at least a location, a flag indicating whether it is carrying food and a lifespan.
The behavior of ants is as follows:
An ant that carries food goes in the direction of the nest.
If an ant does not carry food but there is food at its location then it takes one unit of food.
Otherwise it will go towards a neighbouring cell.
When an ant reaches the end of its lifetime, it dies and drops its food, if any. A dead ant does not move anymore.
Optional. When an ant is away from the nest for more than 20 rounds, it goes back and then comes out again.
Create a class AntFarm
.
Each AntFarm
has an environment, a nest location and a list of ants. It also has a fixed thread pool executor.
Create a run method that makes the ants move concurently.
It waits until each ant makes its step.
Then it calls the update function of the environment.
The loop starts again.
Implement methods for displaying an ant farm.
Create a method displayPoint
in Environment
. This returns '\#'
if there is food on the given point, '\_'
otherwise.
Create a method display
in AntFarm
. This goes over each location, and displays 'N'
for the location of the nest, 'A'
for an ant, or the character that is returned by the method displayPoint
of the environment.
Create a main
function that creates an AntFarm
and runs it onf a 30x30 area.