Text Size
Saturday, October 25, 2014

27.01.13

php object oriented test and solution for developers

Write classes to represent 3 different types of Ant - Worker, Queen and Soldier.

Each Ant has a floating-point health property, which is not writable externally and upon creation is set to a value of 100 (percent).

Each Ant has a Damage() method that takes a single integer parameter that should be a value between 0 and 100. When this method is called, the health of the ant is to be reduced by that percentage of their current health.

When a Soldier has a health below 66%, it is injured and cannot fight and therefore is pronounced Dead. When a Queen has a health below 20%, or a Worker below 50%, it is pronounced dead. This 'Dead' property should be readable from each Ant.

When an Ant is dead, no further health deductions should be recorded by the Ant, although the Damage() method should still be able to be invoked without error.

Your script should create a single list containing 10 instances of each type of Ant. It must support methods to allow Damage() to be called for each Ant, and to return the health status of each Ant, including whether it is alive or not.

The user interface should show the current status of each Ant and contain a button.

When clicked, a different random value between 0 and 80 should be selected for each Ant and applied with a call to Damage(). After each click the page should refresh to show the health status of the ants.

The code should be able to be run on a standard install of PHP 5.x, and should include all files necessary to run the web application

My PHP5 Solution below

<?php


// Ant Class
/** 
* Ant Class with 3 types of possible object types: 
* Soldier, Queen or Worker 
* @version	$Id: ant.php 2012-01-22 Mike Zriel $
* @params object $object
* @params new ant( {type} ) create Object
*/
class Ant {

	protected $_health, $_type, $_errorMessage, $_dead;
	
	public function __construct( $type ) {
	
		switch ( ucFirst ( strtolower( $type ) ) ) { // ( lowercase string, then uppercase First Letter )
		
			case "Soldier": 
			case "Queen"  : 
			case "Worker" : $this->setType( ucFirst ( strtolower( $type ) ) ); // Example setting using Setter 		
							$this->_errorMessage = "Success"; // Valid name used to create Object
							break;
			default : $this->_errorMessage =  "Invalid Ant Type only ( Soldier, Queen or Worker are valid"; // Report Error in creating the Object
					  break;
						
		}
		$this->_health = ( float ) 100.0; 
		$this->_dead = 0;
	}

	/* Public Get Health, can be accessed from object created */	
	public function errorMessage() { 
		return $this->_errorMessage;  // return ant health
	}
	
		
	/* Public Get Health, can be accessed from object created */	
	public function getHealth() { 
		return $this->_health;  // return ant health
	}

	/* Public Get Type, can be accessed from Object created */	
	public function getType() { 
		return $this->_type; // return ant type
	}

	/* Public set Health,  can only be set within other methods in class*/	
	public function setHealth( $health ) { 
		$this->_health = ( float ) $health; // Casting variable as Float
	}

	/* Private Set Type, can only be set within other methods in class */
	private function setType( $type ) {
		$this->_type = ( string ) $type; // Casting variable as String
	}
	
	/* Public Damage method ,can be accessed from Object created */
	public function Damage( $damageAmount ) {
		if( (int) $damageAmount >0 AND (int) $damageAmount < 100 ) { // if damage amount is 1 to 99
			if(!$this->Dead()) {  // When an Ant is dead, no further health deductions should be recorded by the Ant, although the Damage() method should still be able to be invoked without error.
				$this->_health -= ( float ) $damageAmount; // Deduct Health
			}
		}	
		return array( $this->_health, $this->Dead() );	// Return 2 result in array ( health annd is Ant is dear )
	}

	/* Public Dead, can be  accessed from Object created */
	public function Dead() {
		switch ( $this->getType() ) {
			case "Soldier": if ( $this->_health < 66  ) $this->_dead=1;
							break;
			case "Queen"  : if ( $this->_health < 20  ) $this->_dead=1;
							break;
			case "Worker" : if ( $this->_health < 50  ) $this->_dead=1;	
							break;
		}
		return $this->_dead;	
	}

	/* Public output Ant type and healt readonly and disabled */
	public function output($id) {
		return "<label>Ant getType()."'>".$this->getType()." with Health ".$this->getHealth()."</label>
		 		<input type='hidden' name='ant$id' id='ant$id' value='".
				$this->getHealth()."'  />";
	}
	
	/* Public createButton, create random Damage Button */
	public function createButton($id) {
		$damageAmount=100;	
		while( $damageAmount >= $this->getHealth()) { // Make sure Damage cannot be greater than health
			$damageAmount=rand(0,80);
		}
		return "<input type='button' onclick='javascript:setDamage($id,$damageAmount);' value='Damage $damageAmount' />";
	}	
}
?>
<html>
	<head>
		<title>Ant Object Test by Mike Zriel</title>
	</head>
<body>
Ant Object Test by Mike Zriel	
<style type='text/css'>
body { font-face: 'Arial','sans-serif'; font-size:12pt;}
.Queen { color: green; }
.Soldier { color: red; }
.Worker { color: blue; }
.log
</style>
<script type='text/javascript'>
// Set Damage by Ant ( old school javascript ), jQuery would have been easier
function setDamage( id, damage ) {
	document.getElementById('id').value=id;
	document.getElementById('damage').value=damage;
	document.forms['antForm'].submit();
}
</script>
<form method='post' action='ant.php' name='antForm' id='antform'>

	<table>
<?php
// for loop for 10 types of Ants
$ants = array(30);
$antTypes = array('Soldier','Queen','Worker');
$status = array(2);

$log = array();
for($j=0;$j<3;$j++) {
	for( $i=0;$i<10;$i++ ) {
		$key = ($j*10)+$i; // key unique id for Ant Object
	
		if($i==0) {
			if($j>0) {
				echo "</ol></td>";
			}
			echo "<td><ol>";
		}	
		
		echo "<li>";
		$ants[$key]=new Ant($antTypes[$j]); 	// Create Ant Object
		if( isset( $_POST["ant".$key] ) ) $ants[$key]->setHealth( $_POST["ant".$key] ); // Set Health if available
		
		if(isset($_POST["id"])) { // is id set
			if($_POST["id"]==$key) { // This is the Ant Which is going to get Damage
				$status = $ants[$key]->Damage($_POST["damage"]); // Cause Damage
				if($status[1]==1) {
					 echo "
Ant ".$ants[$key]->getType()." $key just Died. Health was ".$status[0]."";
				}
			}
		
		}
		
		$log[]=$ants[$key]->getType()." $key:".$ants[$key]->errorMessage();
		echo $ants[$key]->output($key);
		if(!$ants[$key]->Dead()) {
			echo $ants[$key]->createButton($key);
		}
		else {
			echo "Dead.";
		}
		echo "</li>";
		
	
	}
}
?>
	</ol></td>
</table>	


<!-- Log Entries Start -->
<h2>Log Entries to see if Objects were created without errors</h2>

	<table>
<?php

foreach($log as $key=> $entry ) {
	if($key % 10 == 0 ) {
		if($key>0) echo "</ul></td>";
		echo "<td><ul>";
	}
	echo "<li>".($key+1)." {$entry}</li>";
}
?>
		</ul>
	</td>

<!-- Log Entries End -->
<input type='hidden' name='id' id='id' />
<input type='hidden' name='damage' id='damage' />
</form>
</body>
</html>

Add comment


Security code
Refresh

Copyright © 2014 by Mike Zriel - Zriel.com