Spider | Previous | Next | Full Table of Contents | Index | Program List | Copyright

12.3 Continuing Saga: Keeping Track of Multiple Spiders

Let's return once again to the spider system, in particular to the multiple-spider package developed in Section 10.6 ( Program 10.19 and Program 10.20). This package is missing an important feature. Each location in the room can hold only one spider. We would like to add a new exception to the Spiders package specification,

    Hit_a_Spider: EXCEPTION;
 

which, by analogy with the exception Hit_the_Wall, can be raised by Jump and handled by a user's spider program, if a second spider tries to move into an occupied location. Although each individual spider's record contains its current location, nothing in the package keeps track of the overall state of the room, so there is no way to know whether any given location is occupied.

Sections 12.1 and 12.2 give us the data and control structures necessary to detect a collision. Let us define, in the body of Spiders, a type RoomType as

    TYPE RoomType IS ARRAY ( RoomHeight, RoomWidth) OF Boolean;
 

where False means an empty location and True means an occupied one. Now we can declare, in the body of the package, a room variable

    Occupied: RoomType;
 

Which spider operations must be modified accordingly?

First, we must initialize the room, with all locations unoccupied. We can do this in the DrawRoom procedure with the statement

    Occupied := ( OTHERS => ( OTHERS => False));
 

Next, when a spider enters the room at a given location, we must mark its square as occupied. We can do this in the Start procedure, to which we already pass parameters Row and Col, with the statement

    Occupied ( Row, Col) := True;
 

Finally, when a spider attempts to move (using the Jump procedure), we need to detect a collision. We write the new algorithm for Jump, leaving the details of the coding as an exercise. Note that a spider can jump over, but not into, an occupied location.

Algorithm for Spiders.Jump

1. IF the spider is trying to jump into or through the wall THEN

     2. RAISE Hit_the_Wall

ELSIF the spider is trying to jump into an occupied location THEN

     3. RAISE Hit_a_Spider

ELSE

     4. Mark the spider's current location as unoccupied

     5. Mark the spider's new location as occupied

     6. Draw the spider in its new location

     7. Change the spider's own location coordinates

END IF;


Spider | Previous | Next | Full Table of Contents | Index | Program List | Copyright

Copyright ©1996 by Addison-Wesley Publishing Company, Inc.