Adding a Predator to our Fishtank

In this post, we’re going to take our fishtank from before and add a couple more fish and a shark.

Adding New Creatures

The first thing we want to do is to add a few more fish. This will be much more interesting with a shark chasing a few fish than just the one. Fortunately this is pretty easy because my code was already set up to handle multiple fish, but I was only creating one before:

Now we need to make our shark. Our shark is basically just going to be a fish that treats other fish as food, so we actually don’t even need to write any extra code here. We’ll just use our fish class, and anytime we would be passing in our array of food, we’ll pass in our array of fish. I was originally going to make shark a subclass of fish, but I realized that I wouldn’t actually need any code in that class at all.


Updating our Fishtank

Next we need to copy over and modify some code so that sharks can be handled slightly different than fish. We need a contactedFish function instead of contactedFood, our update method needs to know that sharks get rewarded for touching fish and not food, and we need our draw method to draw out our shark from a shark image instead of a fish. Most of these code changes aren’t especially interesting, so I’m not going to write them out and explain them, but check out the project on my github if you want to see the changes.

Lastly, we had to update our graph. We need each fish/shark to be tracked separately and we need a legend so we can tell which is which. Fortunately, this is pretty easy in the charting library that I’m using (CanvasJS).

Testing it Out


Next Steps

I had a list of ideas in my last post, but I’ve got a few more ideas after this one:

  • Handle death differently. It would be neat for the fish to “restart” at least a little bit instead of just teleporting somewhere else on screen.
  • Improve efficiency. This instance is laggier than the last, and I’d like to fix that.
  • Have separate graphs for each fish/shark. This would be especially useful if I implement hunger and starvation.

Thanks for Reading!

If you’ve got any questions/comments, feel free to reach out to me on twitter or email me at

Leave a Comment

Your email address will not be published. Required fields are marked *