Page 1 of 1

Homing pigeon

Posted: Wed Feb 15, 2012 8:24 pm
by balqan
I'm going trough the book of Matt Doyle, Beginning PHP 5.3, so far so good, but for the sake of fun, I would like to take one of the exercises a bit further and I'm getting stuck. It's called the Homing pigeon, where a "pigeon" (%) gets assigned a random x and y and it goes "home" (+). I tweaked the code to have two pigeons and was working fine, but now I try to make it with an eagle, called "sas" (W) that should hunt the pigeon. Whoever gets first, the pigeon home, or the eagle to catch the pigeon, the game should stop.

I can't get the eagle to hunt the pigeon, I don't know what I'm doing wrong... It's behaving the same way as the pigeon...

I wonder if anyone could point me to the right direction. Thanks.

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Homing pigeon simulator</title>
<style type="text/css">
div.map {
	float:left;
	text-align:center;
	border:1px solid #666;
	background-color:#fcfcfc;
	margin:5px;
	padding:1em;
}
span.home, span.bird{
	font-weight:bold;
}
span.empty{
	color:#666;
}
</style>
</head>

<body>
<?php

$mapSize = 10;

//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);
	$sasX = rand (0, $mapSize-1);
	$sasY = rand (0, $mapSize-1);
} while ( (abs($homeX - $pigeonX ) < $mapSize/2) && (abs( $homeY - $pigeonY ) < $mapSize/2) && (abs($pigeonX - $sasX ) < $mapSize/2) && (abs( $pigeonY - $sasY ) < $mapSize/2));

//move the pigeon closer to target
do {
	if ( $pigeonX < $homeX)
		$pigeonX++;
	elseif ( $pigeonX > $homeX)
		$pigeonX--;
	if ( $pigeonY < $homeY )
		$pigeonY++;
	elseif ($pigeonY > $homeY)
		$pigeonY--;
	if ( $sasX < $pigeonX)
		$sasX++;
	elseif ( $sasX > $pigeonX)
		$sasX--;
	if ( $sasY < $pigeonY )
		$sasY++;
	elseif ($sasY > $pigeonY)
		$sasY--;
	
	//display the current map
	
	echo '<div class="map" style="width:'. $mapSize .'em;"><pre>';
	
	for ( $y = 0; $y < $mapSize; $y++) {
		for ( $x = 0; $x < $mapSize; $x++) {
			if ($x==$homeX && $y == $homeY) {
				echo '<span class="home">+</span>'; //Home	
			} elseif ( $x == $pigeonX && $y == $pigeonY) {
				echo '<span class="bird">%</span>'; // Pigeon	
			} elseif ($x == $sasX && $y == $sasY) {
				echo '<span class="bird">W</span>';
			}	else {
				echo '<span class="empty">.</span>';
			}
			
			echo ( $x != $mapSize-1) ? " " : " ";
		}
		echo "\n";
	}
	echo "</pre></div>\n";
} while ($pigeonX != $homeX || $pigeonY != $homeY || $pigeonX != $sasX || $pigeonY != $sasY);
?>

</body>
</html>