Page 106 - Beginning PHP 5.3
P. 106

Part II: Learning the Language































                     Figure 4-4

                How It Works
                This script uses a number of decisions and loops to simulate the pigeon flying toward home and
                displays the results.
                First, the script displays an XHTML page header. Then it sets a variable, $mapSize, representing the
                width and height of the map square (you might want to try experimenting with different values to see
                how it affects the simulation):

                    $mapSize = 10;

                Next, you encounter the first loop of the script: a do...while loop. This code uses PHP’s rand()
                function to randomly position the home point and the pigeon within the boundaries of the map. After
                positioning the home and pigeon, the condition of the do...while loop checks to ensure that the
                home and the pigeon are at least half the width (or height) of the map apart from each other; if they’re
                not, the loop repeats itself with new random positions. This ensures that the pigeon always has a
                reasonable distance to travel:
                    // Position the home and the pigeon
                    do {
                      $homeX = rand ( 0, $mapSize-1 );
                      $homeY = rand ( 0, $mapSize-1 );
                      $pigeonX = rand ( 0, $mapSize-1 );
                      $pigeonY = rand ( 0, $mapSize-1 );
                    } while ( ( abs( $homeX - $pigeonX ) < $mapSize/2 ) && ( abs( $homeY -
                    $pigeonY ) < $mapSize/2 ) );



              68





                                                                                                      9/21/09   8:52:12 AM
          c04.indd   68                                                                               9/21/09   8:52:12 AM
          c04.indd   68
   101   102   103   104   105   106   107   108   109   110   111