87. Sharks and Fish

Langton's Ant and Life use extremely simple rules. This simulation, which I call Sharks and Fish, uses much more complicated rules in an attempt to simulate real-world interactions between predators and prey. You can find similar simulations scattered around the internet that mimic predator/prey interactions between sheep and wolves, foxes and rabbits, lynxes and rabbits, moose and wolves, and even just generic predators and prey.

In the Sharks and Fish simulation, sharks and fish occupy the squares in a grid. The sharks use the following rules:

  • Each shark has an energy level and each turn it loses some energy. If the shark's energy ever drops to zero, the shark starves and dies
  • Each turn, every shark moves randomly left, right, up, or down into a neighboring square that is empty or that contains a fish
  • If a shark moves onto a fish, it eats that fish and gains a certain amount of energy
  • If the shark's energy level ever exceeds a set amount, it spawns a new shark in an empty neighboring square and splits its energy with the child

The fish use the following rules:

  • Each turn, each fish moves randomly left, right, up, or down into a neighboring square that is empty
  • If a fish survives a certain number of turns, it spawns a new fish in a neighboring empty square and resets its breeding counter

If a rule requires an empty square but none are available, then the rule is ignored. For example, if a fish should spawn but it has no empty neighboring square, then it resets its breeding counter without creating a new child fish.

For this problem, build a Sharks and Fish program similar to the one shown in the following screenshot:

You can use a grid similar to the ones you used for the Langton's Ant and Life programs if you like. In the preceding screenshot, I chose to represent the sharks and fish as white and red and white pixels on a bitmap.

The user should enter the grid, fish, and shark parameters, and then click the Start button to begin the simulation.

This simulation is a bit more complicated than the previous ones, so you may want to use a slightly more complicated method for storing the world's information. In the example solution, I used an Ocean class to represent the world. I also defined Shark and Fish classes that inherit from a common Animal class. The program's Ocean object contains an array holding Animal objects and null values to represent empty locations.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset