Tag Archive for 'php design patterns'

Page 2 of 3

PHP OOP Game Coding: Collision Detection

ropeDistance in 2D Space

For a number of years I’ve had David Bourg’s book, Physics for Game Developers (2002, O’Reilly), and I’ve been meaning to translate a set of formulas into OOP classes that could be used as part of a PHP game development library. After spending time on (simple) game development last summer using Python, I decided it was time to get busy with a similar project using more OOP and PHP. I wanted something that was small enough to run on Raspberry Pi computers, but still an animated video game.

On previous posts on this blog I’ve used SVG graphics with PHP, but the examples I used were fairly static. Here I’d like to try them in a more dynamic role to see if PHP could generate code to make them dance. For starters I thought that a simple 2D space game would be appropriate — more on the order of Astroids than Space Aliens.

2D Outer Space on a Grid: Plane Geometry

In order to get anywhere, I decided that the universe (galaxy, solar system, whatever; you choose) would live on a 500 x 400 grid. It can be adjusted for different screens, but the first step is to set up a common grid for clear discussion. Further, I thought that starting with rectangles as ‘space ships’ would make everything else easier. (You can build something more elaborate later in the series.) The two space crafts are Oopz and Titeaz. Oopz is crewed by OOP developers, and Titeaz has a crew of sequential and procedural programmers who keep getting in trouble because of spaghetti knots and tight bindings. The Oopz goes on rescue missions to send them PHP code packages of classes and design patterns. Figure 1 shows the initial positions of the two ships:

Figure 1: Grid with Oopz and Titeaz

Figure 1: Grid with Oopz and Titeaz


Each of the grid squares in Figure 1 is 50 x 50 pixels, and the space ships use conventional a x|y position denotation.

Determining Distance and Collision Detection

The first thing we’ll tackle in Rocket Science 101 is determining the distance between two objects.

Raspberry Pi Users: You will need the Chromium browser for the graphics in this series. You can download it using the following code:
sudo apt-get install chromium

The distance between objects can be used for everything from determining when two objects have collided (distance = 0 + fudge-factor) to when another ship is in rescue range to receive project-saving OOP code. The SVG objects on your screen (without the grid) can be seen in Figure 2:

Figure 2: Determining Distance

Figure 2: Determining Distance

The code for this starting screen is based on the SVG W3 standards and saved as an XML file:

< ?xml version="1.0" standalone="no"?>
< !DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> 
<svg width="500" height="400" viewBox="0 0 500 400"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
<desc>Oopz and Titaz</desc>
<!-- Show outline of canvas using 'rect' element -->
<rect x="0" y="0" width="500" height="400"
        fill="#DCDCDC" stroke="blue" stroke-width="1"></rect>
<!-- Space craft Oopz -->
<rect x="100" y="100" width="30" height="20"
        fill="#cf5300" stroke="#369" stroke-width=".4"></rect>
<!-- Space craft Titeaz -->
<rect x="300" y="200" width="30" height="20"
        fill="#369" stroke="#00cc00" stroke-width=".4"></rect>
</svg>

To see the distance calculation, click the Play button. See if you can figure out what formula is used before you look at the code:

PlayDownload

The calculations are based on one of the most fundamental theorems in plane geometry. Before continuing, see if you can figure it out and resolve the solution.
Continue reading ‘PHP OOP Game Coding: Collision Detection’

Share

The Composite Design Pattern in PHP: Part I from Conceptual to Practical

compositionShow Me the Practical!

A defining characteristic of PHP programmers is their practicality. Ironically, because of their practical orientation, they sometimes overlook the practicality of the abstract and conceptual. Focusing too much on a single (albeit quite useful and practical) implementation is like focusing on a single pixel in a graphic image—you can only see the pixel and miss the larger picture. That’s because the focus is in the wrong place. If you want to see the whole picture (the whole pattern and its parts), the individual pixels are not very practical, even though they are the atomic matter in computer graphics. In other posts on this blog, I have stressed the importance of having a complete design pattern with all of the participants a given design pattern is designed to include and provided a look-up table to check the parts list of all of the core patterns the Gang of Four developed. So in selecting an example to launch a discussion of the Composite pattern, I wanted an example with all of its parts. You can download the files and play a sample using the following two buttons:
PlayDownload

However, too much of a love affair with the conceptual and abstract is equally problematic. If you cannot use a pattern to get something accomplished, why waste time with it? Ironically, design patterns were developed solely for practical purposes, but in order to accomplish those practical goals, they had to provide a set of patterns that would be useful for a wide range of certain recurring programming problems. With these concepts in mind, this post begins with a conceptual example to see how the pattern works and then follow it up with a simple more practical example.

Overview

First things first. The class diagram for the Composite design pattern is both very simple, but it hides a real beauty and subtle complexity. Figure 1 shows the basic pattern:

Figure 1: Composite Design Pattern class diagram

Figure 1: Composite Design Pattern class diagram

Before going too far with an example, even an abstract one, consider the simplicity and irony of the pattern. First of all, the Composite implementation of the Component interface looks fairly cut and dried. However, the Leaf participant also implements the interface, but it doesn’t implement all of the abstract methods. It only implements the operation(). So maybe the interface is an abstract class? It doesn’t matter in PHP. If all of the abstract methods of a class that inherits an abstract class are not implemented, you get the following error:

Fatal error: Class Leaf contains 1 abstract method and must therefore be declared abstract or implement the remaining methods

Since you can only declare an abstract method within an abstract class, you really have no choice but to implement it. Likewise with an interface all methods must be implemented; so with this first abstract example, I decided to use an interface instead of an abstract class.

Favoring Composition: A Tattoo for Your Spouse

One of the fundamental principles of design patterns is,

Favor object composition over class inheritance.

Figure 3: Tats for PHP Developers

Figure 3: Tats for PHP Developers

I tried to get my wife to get a tattoo with that piece of wisdom, but she balked at the idea. (I have no idea why; it’d be cool.) If any pattern adheres to that dictum, it’s the Composite pattern. The Composite participants are made up of Leaf primitives. So you can think of Composite implementations as compositions. The Leaf participants have no children. Think of the Leaf participants as parts that can be employed to create Composite participants.

For the longest time, that simple yet fundamental idea eluded me. In part, this was due to the Gang of Four’s intent statement that the pattern was to Compose objets into tree structures to represent part-whole hierarchies. I was too focused on the concept of hierarchy and not enough on compose to really appreciate the importance of the Composite design pattern.

So here, the first thing to do is to realize that the hierarchy is a form of composition. Imagine an automobile assembly plant where you have lots of parts, yet with those parts you can assemble different models of cars. You just have to use different selections of parts to compose the different models. The fact that the parts have a hierarchic arrangement is for efficiency; not the final product itself. Figure two shows what we hope to create in this initial implementation:

Figure 2: Different Compositions from Leaf Selections

Figure 2: Different Compositions from Leaf Selections


Continue reading ‘The Composite Design Pattern in PHP: Part I from Conceptual to Practical’

Share

PHP Game Making Part II: The State Machine

stateObey the State!

When you hear the term State Machine, you may think of totalitarian societies as depicted in George Orwell’s 1984 run by ruthless dictators. However, in programming, state machines are quite benign and helpful in solving certain kinds of programming problems. Chapter 10 of Learning PHP Design Patterns, explains the State design pattern in full detail. In this post I want to introduce the concept of a state machine, but we will not see a true State design pattern just yet. Here, we’ll just look at a state machine and how it can be used in OOP programming in general. As you will see, we can use a state machine in standard OOP programming without a full State design pattern. In Part III, we’ll examine a full State Design Pattern.

Generally speaking in programming, a state is the current value of a variable. A state machine (or finite state machine) is a system where each state waits for a transition to another state. (In Learning PHP Design Patterns, I used the example of a light having states of “on” or “off,” with the transition through the trigger of a light switch.) In the game of Rock, paper, scissors, lizard, Spock (R-P-S-L-S), each of the five gestures represents a state, and the transition occurs each time the players throw a gesture. (See PHP Game Making Part I.) To get started, play the revised version of the game and download the files for the State Machine version of the game:
PlayDownload

A State Class

To get started, begin with an interface that encompasses all of the different states (moves) in R-P-S-L-S. The following listing, IPlayer, has methods for each move:

< ?php
interface IPlayer
{
    public function rockMove();
    public function spockMove();
    public function paperMove();
    public function lizardMove();
    public function scissorsMove();
}
?>

Note that all of the methods are public. This allows access to them through different implementations.

What we want to do with each method is to generate outcomes for all possible moves. Given that a player (human) is pitted against a computer that randomly makes moves, each state class with have outcomes for each of the methods based on the combination of what the player has done and what the computer will do. Take, for example, the Rock class. Each of the

< ?php
class Rock implements IPlayer
{
    public function rockMove()
    {
        return "Tie";
    }
 
    public function spockMove()
    {
        return "Computer wins!";
    }
 
    public function paperMove()
    {
        return "Computer wins!";
    }
 
    public function lizardMove()
    {
        return "Player wins!";
    }
 
    public function scissorsMove()
    {
        return "Player wins!";
    }  
}
?>

Essentially, you have self-aware state classes. For example, the Rock class is aware that if the opposition makes a Rock move, the result is a tie. Likewise, if the opposition chooses either a Lizard or Scissors move, Rock wins; but if the opposition makes either Paper or Spock moves, Rock loses. There are no conditional statements. That’s important as you will see when we move on the the State design pattern in Part III (or you saw in Chapter 10 of Learning PHP Design Patterns.

The State Machine

To understand a State Machine, it helps to use a statechart. A statechart identifies the different states in a system and the triggers that transition from one state to another. In the case of an R-P-S-L-S) finite state system, you have a triggering state (chant->throw) and the five individual states. Figure 1 shows the five states and the triggering state. Note that all changes from one state to another go through the trigger and none directly to another. (e.g., A Lizard state cannot go directly to a Paper state; it must go through the trigger.)

Figure 1: Statechart of the RPSLS State Machine

Figure 1: Statechart of the RPSLS State Machine

Importantly, the State Machine represents what actually happens in a game of R-P-S-L-S. Players enter the “chant” trigger and then throw a gesture. So we may actually refer to the RPSLS as a “state” used to transition between the five outcome states. The task now, is to implement these states. (Click below to continue.)
Continue reading ‘PHP Game Making Part II: The State Machine’

Share

PHP CMS Project Part IV: La Petite Blog

cms4Bring in the MySql

At this stage there is still no design pattern in the project. You will see that re-use is starting to creep in, and we’re getting to the point where some decisions can be made about what design pattern would best fit this project. In Part V, you will see how a design pattern pulls everything together and why one is helpful to PHP programming.

In Part III of this series, you saw how external data from text files can be placed into an array and used by the DocHere class to populate a web page. In this installment, the same process shows how this can be done using data from a MySql database.

From Data Input to Web Page Display

The whole point of a CMS is to make updating a web site or blog easy. For the time being, I’m going to treat the web page example as a little blog–La Petite Blog. Figures 1 and 2 show how the data are to be entered and the end result pulled out of a database and displayed in the web page.

Figure 1: HTML form to send data to MySql database

Figure 1: HTML form to send data to MySql database

Figure 1 shows that the same categories of data used throughout the project are still in use. Even the CSS file is the same. The form is a simple HTML5 one. (Click View Code to see listing.)

< !doctype html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="heredoc.css"/>
    <meta charset="UTF-8"/>
    <title>Blogette Data Entry</title>
</head>
<body>
<h1>La Petite Blog</h1>
<h2>&nbsp;Enter data to update your blogette</h2>
<div>
    <form name = "content" action="InsertBlog.php" method="post">
        <input type="text" name="css" value="heredoc.css"/>&nbsp;CSS file
        <input type="text" name="title" />&nbsp;Title
        <input type="text" name="header1" />&nbsp;Header 1
        <input type="text" name="header2" />&nbsp;Header 2
        <textarea rows="5" cols="80" name="body1" >&nbsp;Add body text here</textarea>
        <textarea rows="5" cols="80" name="body2" >&nbsp;Add body text here</textarea>
        <input type="text" name="image1" />&nbsp;Image 1 file name
        <input type="text" name="image2"/>&nbsp;Image 2 file name
        <input type="text" name="caption1" />&nbsp;Caption for Image 1
        <input type="text" name="caption2"/>&nbsp;Caption for Image 2
        <input type="submit" value="Store data"/>
    </form>
</div>
</body>
</html>

The “entry” for the system is the class RetrieveBlog. It is almost identical to the Content class in Part III, and it generates the required results as shown in Figure 2.

Figure 2: Page content from database.

Figure 2: Page content from database.

Getting from the HTML5 data input to the PHP-generated web page takes a bit of doing, and so to get started, download the necessary files:
Download

From Data Input to Web View

The whole point of a CMS is to regularly update a web page easily. By the end of this stage, the only thing you’ll need with an FTP client for is to upload graphics. (Uploading graphic files from a web page using PHP is handled up an upcoming post apart from this series.) For now, though, you will be able to update all text in a web page as well as graphics are have already been placed in an image folder. Here’s what we’ll need:

  1. An HTML form for data entry (see above)
  2. A PHP class to create a MySQL Table to store data
  3. A PHP class to take the data from the HTML form and store it in the MySQL table
  4. A PHP class to retrieve the data from the and make it available to the web page

We’ll start with the table.
Continue reading ‘PHP CMS Project Part IV: La Petite Blog’

Share

PHP CMS Project Part II: Separating Tasks

cms2Separation of Content from Form

In Part I of A PHP CMS Project, you saw how a Web page could be placed in a variable using PHP’s HEREDOC operator. Once in HEREDOC, different parts of the page could be filled with content delivered through variables. Using a simple CSS format, it was possible to have the general layout of a Web page and updates through through a private methods in the same class.

This next step further separates the Web page structure from the data that it uses for content. Essentially, this steps makes the HEREDOC Web page a separate class and calls for content from another class. At this point, there’s no design pattern involved; just a little OOP. In fact everything is the same except the content. (Later on in this series you will see which design patterns would be useful.) Figure 1 shows what the new page looks like:

Figure 1: Content from an external source

Figure 1: Content from an external source

As you can see in Figure 1, the content on the page has changed, but the format is the same. The big difference is that all of the data were sent through an external object. You can test the page and download the source code by clicking the following buttons:
PlayDownload

Once you have downloaded the classes, you can see similarities and differences in the classes now and those in Part I. The first new class to examine is Content. Simply stated, this is the class that stores the data for the Web page. It has a single method, getContent() and no constructor function. As a rule of thumb, if I don’t need a specific constructor function (one using __construct), I don’t include one.

<?php
//Content.php
include_once('PageMaster.php');
class Content extends PageMaster
{
    public function getContent()
    {      
        $this->content = array("css" => "heredoc.css",
                         "title" => "Here's Doc!",
                         "header1" => "New York State of Mind",
                         "header2" => "The Travel Page",
                         "body1" => "<p>Let's go have some fun. This is what I did on my summer vacation. ",
                         "body2" => " There much to see in NYC. Tall buildings, yellow cabs and lots of people.</p>",
                         "image1" => "images/mermaid.png",
                         "image2" => "images/plane.png",
                         "caption1" => "<br /> New York has the best mermaids.<br /> ",
                         "caption2" => "<br /> Off to New York City.<br /> ");   
        return $this->content;
    }
}
?>

Now that the content is in a different class, it’s easier to change the content without having to change the DocHere class. Of course the idea is to leave the DocHere class alone and just change the content through the use of variables. However, instead of scalar variables, you can use a compound variable—an array in this case. So now, all of the content has moved from a set of variables in the same class as the HEREDOC Web page to an array in an external class.

Before looking at the updated DocHere class, you will find a small but significant change. Figure 2 shows the difference in how a variable is inserted into a HEREDOC document and how an array element from an external class is inserted into the same HTML tag:

Figure 2: Inserting variables and imported array elements.

Figure 2: Inserting variables and imported array elements.

Note that the same element names (or key names) are used as were for the variable names. (e.g., $this->header1 is now $this->hd[“header1”].) So now, the HTML page is in a single variable ($this->document), and all of the content for that page is in a single array ($this->hd).

To “catch” the data from the Content object, the DocHere class uses the $content variable ($this->content) it inherits from the abstract class PageMaster. Next, the $hd variable (short for ‘html data’) calls the getContent() method from the Content class. The getContent() method delivers the array with the data used in the HTML page.

<?php
//DocHere.php
include_once('PageMaster.php');
include_once('Content.php');
 
class DocHere extends PageMaster
{
    function __construct()
    {
        $this->content=new Content();
        $this->hd = $this->content->getContent();
        $this->document = <<<CMSTEMPLATE
        <!DOCTYPE html>
        <html>
        <head>
        <link rel="stylesheet" type="text/css" href={$this->hd["css"]}>
        <meta charset="UTF-8">
        <title>{$this->hd["title"]}</title>
        </head>
        <body>
        <header>
            <h1>{$this->hd["header1"]}</h1>
        </header>
            <article>
                <header>
                <h2>{$this->hd["header2"]}</h2>
                </header>
                {$this->hd["body1"]}
                {$this->hd["body2"]}
                <section class="doRight" >
                    <img src={$this->hd["image1"]}>
                    <caption ><span class="pixcaption">{$this->hd["caption1"]}</span> </caption>
                </section>
                <section class="doLeft">
                    <img src={$this->hd["image2"]}>
                    <caption><span class="pixcaption">{$this->hd["caption2"]}</span> </caption>
                </section>
            </article>
        </body>
        </html>
 
CMSTEMPLATE;
    echo $this->document;
    }   
}
?>

The business logic if pretty well taken care of in the DocHere and Content classes. So you may well ask, What’s up with the abstract class, PageMaster?

Adding an Abstract Class

At this state of development, the abstract class, PageMaster is nothing more than a placeholder for an abstract class or interface we may need later in the development process. The three variables (or more correctly properties) of the abstract class can be inherited using protected visibility.

<?php
//PageMaster.php
abstract Class PageMaster
{
    protected $content; 
    protected $hd;
    protected $document;
}
?>

One OOP principle that you may be able to extract from this is the use of polymorphism. The $content object is used in both implemented classes. In the Content class, the $content property is an array, while that same property name in the DocHere class is an instance of the Content object. It’s not the best example of polymorphism, but it’s a start. (You can see more typical and useful examples of polymorphism in abstract methods—with properties the polymorphism is almost the same as the difference between the same local variable name used in different functions.) Further, keep in mind that that actual array from the Content object is stored in the $hd array; not the $content object in the DocHere class. It is passed to $hd using the following:

$this->hd = $this-content->getContent())

So for now, don’t worry about the PageMaster abstract class. However, in future development, of both the abstract class and the CMS project, you may find it quite important.

Why The Baby Steps?

Some readers may wonder why this example is taking its sweet time working up to both a CMS and design pattern in PHP. In reference to the book (PHP Design Patterns, some readers have complained that it is too difficult to understand. Despite the fact that it was written for advanced PHP developers, there’s no getting around the fact that design patterns are hard to learn. (Even the authors of the original Design Patterns book say that design design patterns and OOP are hard to comprehend, and their audience consists of C++ and Java developers!) With a plethora of bad examples of design patterns in PHP that are easy to understand on the internet, I thought working slowly through the logic of some examples on this blog may come up with both a good design pattern example and make it both practical and comprehensible. Any reader feedback on this topic will be quite helpful and welcomed.

Share