Fun & Games
Counting objects within search radius 1 on a tiled map |
[Fun & Games] |
Here is some code that counts the number of trolls and bunnys directly adjacent to the x-y location on a map. The map is a simple tiled environment where each location is defined by a combination of non-negative consecutive integers. <?php /** * @file count_around.php * @function count_around * @author Paul Meagher * @modified Jan 31, 2007 * * Inspired by a peek at the source code for Conway's game of life. * * @see http://4umi.com/web/javascript/conway.htm */ define("TROLL", "1"); define("BUNNY", "0"); /** * Counts number of objects directly adjacent (i.e., search radius of 1) * to the x-y coordinates on the supplied map. * * @param array $map a representation of the terrain * @param int $x x coordinate location on the map * @param int $y y coordinate location on the map * @param string $obj object we are looking for on the map * @return int $n number of objects around the x-y coordinate */ function count_around($map, $x, $y, $obj) { $n=0; if($map[$x-1][$y-1]==$obj) $n++; if($map[$x-1][$y ]==$obj) $n++; if($map[$x-1][$y+1]==$obj) $n++; if($map[$x ][$y-1]==$obj) $n++; if($map[$x ][$y+1]==$obj) $n++; if($map[$x+1][$y-1]==$obj) $n++; if($map[$x+1][$y ]==$obj) $n++; if($map[$x+1][$y+1]==$obj) $n++; return $n; } $map[0] = array(BUNNY,TROLL,TROLL,TROLL); $map[1] = array(TROLL,BUNNY,TROLL,TROLL); $map[2] = array(TROLL,TROLL,BUNNY,TROLL); $map[3] = array(BUNNY,TROLL,TROLL,TROLL); $x = 1; $y = 1; $num_trolls = count_around($map, $x, $y, TROLL); $num_bunnys = count_around($map, $x, $y, BUNNY); echo "The number of trolls within search radius 1 is $num_trolls <br />"; echo "The number of bunnys within search radius 1 is $num_bunnys <br />"; ?>
I encourage you to visit the “Game of Life” link that inspired this code. Exercises 1. Generalize the code so that it accepts an integer $radius
parameter that controls the how far from the x-y coordinates you will count objects. 2. Generalize the code so that it accepts a boolean $wrap_around
parameter that controls how counting occurs when you hit a map border. If, for example, the supplied x-y coordinate was the top left-hand corner (i.e., $x=0
,$y=0
) and $wrap_around=1
then you would also count the number of bunnies and trolls occurring in the right top margin and bottom left margin (because you would hit these objects in a wrap around environment if you moved left or up respectively).