Mini-Lab: Ascending and Descending Fish

Implementing New Methods


This Mini-Lab Exercise is the fifth in a series in which students build a small program with several fish moving around in an aquarium. The set includes the following exercise:

Each section in this series, contains an Introduction to a problem or task, descriptions or examples of one or more Concepts to apply in solving the problem or completing the task, and an Exercise.

In the exercises that precede this one, students will have created a vector of fish that move randomly back and forth in an aquarium, being careful not to hit the sides. Students should understand how to identify the responsibilities of different classes, construct class methods, and use instance variables within methods.



Ascending and Descending Fish

Introduction

Our program would be much more interesting if the fish moved up and down as well as side to side. In this exercise, you will implement two new methods in the AquaFish class, ascend and descend, to support this behavior.

Exercise: Simulating Up and Down Movement

  • To make the simulation more believable, the distance that a fish moves up or down should be related to its height. Fish come in different sizes, so the size of any particular fish is one of the properties of that fish. Its position in the aquarium is another relevant property for this exercise. Read the implementation (code) for the AquaFish class to determine which methods or instance variables will be useful in implementing ascend and descend.

  • Determine what parameters (if any) you will need for the new ascend method. Then determine what its return type should be. Add an empty ascend method (one that consists of a declaration and empty braces) to the AquaFish class after the moveForward and changeDir methods.

  • Implement the ascend method. You may use the moveForward method as a guide if you like, but the ascend method is simpler. The movement amount should simply be the height of the fish.

  • Implement the descend method.

  • Read the class documentation for the NavigationalAide class to determine what methods are available to tell whether a fish is at the surface, at the bottom, or somewhere in between.

    Modify your move method in the AquaFish class to allow fish to ascend or descend before moving forward, according to the following formula:

    • A fish at the surface has a 2/3 chance of descending and a 1/3 chance of staying at the surface.
    • A fish at the bottom has a 1/3 chance of ascending and a 2/3 chance of staying at the bottom.
    • A fish that is neither at the surface nor at the bottom has a 1/3 chance of ascending, a 1/3 chance of descending, and a 1/3 chance of staying at the same depth.

  • Test your program.