Evolving Fish Pond 3: Fish Food

Step 1
Before we add a food class for the fish to eat, we'll need to make the Fish require food

In this lesson we will be adding a food property to the fish class, and displaying a food bar indicating how full the Fish is.


We'll also be deleting Fish whose food supply has run out.

Step 2
First add a food property to the Fish class
Step 3
When food is equal to 0 the Fish has run out and will die
Step 4
We'll add a property named "dead" to flag Fish who have run out of food

We'll later remove all Fish marked "dead == true" from fishArray.

Step 5
Each time the Fish moves it should use up some of its food to do so

Add a line here that subtracts 2 from the Fish's food

Step 6
Next we'll make an if statement that checks if food is less than or equal to 0
if (this.food <= 0) {


Put this in the Fish's move() function.

Step 7
If so, we'll set "dead" equal to true

This doesn't do anything on it's own, but we can use this to remove the Fish from the array- deleting it from the simulation.

Step 8
We can use a filter to remove all of the dead Fish from "fishArray"

In index.js we will add this filter statement to the draw loop.

It may look confusing so I've written what this code says in English beneath it:


Any Fish that is not dead will pass through the filter. Meaning all dead fish will be removed from the array

Check Your Work
Step 9
Watch your fish now and make sure they eventually run out of food and are filtered out of the array

You may want to temporarily make them lose a lot of food each time they move, just to test a bit faster

Step 10
We'll finish up by adding a "percent food" bar which shows how much food out of a maximum the fish has in its stomach
Step 11
In order to calculate the percentage of food a Fish currently has, we need to give them a maximum Food property

Add a property named maxFood to the Fish class and set it equal to 50.

Step 12
In the Fish's draw function, calculate the food percentage
Step 13
We're going to draw first a basic background for the food percent bar

I used the size of the fish to place the rectangle

Temp1546649342 Temp1546649376
Check Your Work
Step 14
Each fish should now have a floating grey bar above their heads

This represents the full size of the food percentage bar

Step 15
Now we add an inner bar whose fill color is orange and the width is multiplied by "foodPercent"
Temp1547765832 Temp1547766357
Check Your Work
Step 16
You should now see an orange foodPercent bar that fills the grey background bar
Step 17
Now that our Fish run out of food as they swim around, we are ready to introduce plants in the next lesson
Evolving Fish Pond 3: Fish Food Info


MVCode Clubs

Created By

Newprofile jamie


Evolving Fish Pond

Access Level


For Teachers and Schools

Teach coding to your students with MVCode Teach

MVCode offers an integrated product designed to teach coding to students.

Learn more about MVCode Teach