A creative and sometimes technical blog about Design and Programming as well as other things.

PHP Class Practice: Creating a Simple Pet Script

For the vast majority of the time I’ve been programming I haven’t used Classes in my code. They are relatively new to me. Because of this, I decided to practice writing classes since I realized how useful they are. Here’s something I made when I was learning.

What We’re Making Today:
We’re going to be making a small script comprised of a class, called Pet, with variables and functions inside of it to perform actions. Also keep in mind that this is extremely simple and most likely cannot be used for anything outside of practice without heavy modification.

Let’s Begin, Shall We?

  1. Create a new file. Let’s call it pet.php.
  2. Open up the file and prepare for editing! (I use Dreamweaver for most code editing, but you can use plenty of other programs like the built in TextEdit (Mac) and NotePad (Windows).
  3. Always remember to save it as a PHP file! Saving it accidentally as .txt or .rtf will make it not work at all.

Now for some code.

//Some class practice.
class Pet
{

We’ve now started the file and recognized it’s a PHP document. Then we initiated the class “Pet”.

var $name = "";
var $age = 1;
var $fullness = 50;
var $health = 70;
public $dead = false;

We’ve now created the variables name, age, fullness, and health for the class to use, and a public variable ‘dead’.

public function SetName($txt)
{
$this->name = $txt;
echo "<p>You have named your pet ".$txt.".";
echo "Fullness: ".$this->fullness." Health: ".$this->health." Age: ".$this->age."";
echo "";
}

Now we have a public function (A function that can be used outside of just inside the class code) called SetName. By calling the function with a string parameter, you assign that string to the class variable $name. It also echoes some text telling you about the pet.

public function GetName()
{
return $this->name;
}

Since the variables we set earlier in the class (like $name) are not public, we can only access them through the inside code. So, using this simple function called GetName(), we can retrieve the contents of the $name variable for that object.

public function Feed()
{
//Increase pet's fullness by a random amount between 5 and 10.
$fulladd = rand(5,10);
$this->fullness += $fulladd;
echo "</p><p>You have fed ".$this->name." some food. Fullness increased by $fulladd.</p>";
}

Every pet needs to be fed, right? Well, since I said this is simple, we are just picking a number between 5 and 10 to add to it’s Fullness total.

function PassTime()
{
//Simulate some sort of reality I suppose..
$this->fullness -= ($this->fullness*.10)+5;
$this->health -= ($this->health*(rand(10,25)/100))+2;
//Make sure stats are whole numbers
$this->fullness = ceil($this->fullness);
$this->health = ceil($this->health);
//Increase age by a day? (Not really logical, but oh well.)
$this->age += 1;
echo "<p style='color:#999999;'>";
echo "Some time has passed.<br />";
echo "Fullness: ".$this->fullness." Health: ".$this->health." Age: ".$this->age."";
echo "</p>";
}

Alrighty, this is a fun one. We’re pretty much giving a little illustion that there’s time with our little pet. We’re decreasing it’s fullness by 10% plus 5 (so it can die eventually), decreasing it’s hunger by a random percentage between 10% and 25% plus 2 (same reason as fullness), and using the php function ceil to round the numbers up so they are whole numbers. We’re then increasing age by one count (a day perhaps?), making the text color gray, and echo’ing out what happened to the screen.

public function Killed()
{
if($this->fullness < = 0 || $this->health < = 0)
{
echo "<p style='color:red;'>Your pet, <b>".$this->name."</b>, is now in pet heaven.";
$this->dead = true;
}
}

This function checks to see if the pet has died due to hunger and health failure. Once it’s fullness or health reach 0 or lower, the pet “goes to a better place”. ;) Notice that it’s variable $dead is set true. This will be used for exiting the loop later on.

}

Close up our class and we’re ready for the main part: The Loop!

We’re going to be using a loop to simulate a created pet’s life. This loop will keep going as long as the pet is alive, and stop when it dies.

//Demonstrate the Pet class!
$Fluffy = new Pet;
$Fluffy->SetName("Fluffy The Sheep");

We’ve created our pet and set his name to “Fluffy The Sheep”.

while($Fluffy->dead == false)
{

if(rand(1,3) == 1)
{
$Fluffy->Feed();
}

$Fluffy->PassTime();
$Fluffy->Killed(); //Is our poor pet deceased?
}

The final part is the loop. Like I said before, the loop keeps going as long as the pet is alive. Once it is dead (determined by the Killed() function), it’s state changes and the loop exits.

And there you have it! Try running the program and see your little pet in action. Feel free to also customize the experience (name it!). I hope you were able to learn something new out of this. :) Happy coding!

(By the way, using these settings my pet lived to be around 12-14 age.)

My Little 1337 (leet) Speak Generator

For fun in class the other day, I wrote a little “1337″ speak generator.  It’s written in PHP, and it consists of just one small script page.  (It has also come to my attention that there are various degrees of 1337, so I would consider my translation to be somewhat advanced.  1337 translation help from Wikipedia.)

Try it here.

/* Leet (1337) Speak generator! */
/* Takes ordinary words and turns them to computer geek gibberish. */

//Lets be able to use all those Post variables easily.
extract($_POST);

//Convert the text?
if(!empty($to_convert))
{
    $old = $to_convert; //Keep old text
    $find = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p', 'q','r','s','t','u','v','w','x','y','z');
    $repl = array('4','8',"&copy;",'[)','3','|=','6','#','1','_|','|< ','1','|v|','N','0','|*','Q','R','5','7','(_)','V','VV','>< ','Y','2');
    $to_convert = str_replace($find,$repl,strtolower($to_convert));
    echo "<p><b>".nl2br(stripslashes($to_convert))."</b><br />(".nl2br(stripslashes($old)).")";
}

//No text to convert, must be the Main Page.
echo "<form action='$PHP_SELF' method='post'>";
echo "Text to be converted:<br /><textarea id='to_convert' name='to_convert' rows='20' cols='35'></textarea>";
echo "<br /><input type='submit' value='1337 speak!'/>";
echo "</form>";


Copyright Mike Wojtkowski 2008-2010; PHail [dot net] Blog – Design, Programming, and other things..
Powered by WordPress. Theme by Mike Wojtkowski.