Archive for the 'State' Category

State Maze Part 2: Play

maze2PHP Game Mechanics

In Part I of this “State Maze” series, you see that each cell in the matrix is a coordinate on a grid, and using the alphanumeric coordinate designation, each implementation of a state interface (class) is named with a grid coordinate. (If you have not looked at Part I, do so now.)

The problem with using an HTML UI (See Part I) is that each time the player makes a move, it generates a new instance of the client that makes the move in the State pattern. As a result, I had to create a Json file to store each move. This solution still does not allow the same instance to be re-used and keep a running record of where the player is, but I haven’t found a satisfactory solution elsewhere. (I’m looking at Ajax and RESTful APIs, but nothing yet.) If you’ve developed games with ActionScript (of Flash fame) or Python, you can easily keep a running record in a class property without re-instantiaing the class in a variable. Ironically, by placing the HTML code in a PHP heredoc string, the class with the HTML in it does not have to be re-instantiated, but the client it launches does. To get started, go ahead and play the maze-game and explore the different OOP and Design Pattern principles and languages that use OOP. You will be asked to provide a “seeker” name. The default name is “chump.” Don’t use that name! (Don’t be a chump…) Use a 5-letter name of your own. It will be used to track your progress through the maze.

PlayDownload

This is not an easy maze (nor does it follow the route of the maze in Part I.) So, keep track of your moves, and if you fall into a sequential trap, you have to start over.

State Overview

If you review the State design pattern, especially the class diagram in Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson and Vlissides (AKA “The Gang of Four” or GoF) you will see that the Sate pattern consists of Context, State Interface and Concrete States implementing the State Interface. In other words, it’s one of the least complex-looking patterns among design patterns.

Figure 1 shows a file diagram of the current implementation; however, the additional files beyond the basic pattern implementation are files with helper elements for CSS and Json.

Figure 1: File Diagram

Figure 1: File Diagram

With a maze, the State design does require a lot of files — one for each state, and some would prefer a table look-up for dealing with a maze-type application. However, a table look-up has its own issues, and making changes and adding actions can tie a table in a knot. Besides, it’s much easier to re-use a state pattern by changing the method calls within each state without even having to change the context or client at all. Further, since all of the states implement the same interface, once one implementation is completed, it can be copied and pasted, changing only the name of the class and the behavior of the implemented methods defined by the interface. As can be seen in Figure 2, the State pattern used in this implementation adheres to the fundamentals of the State Design Pattern as proposed by GoF.

Figure 2: State Class Diagram

Figure 2: State Class Diagram

Each of the state implementations are designated A1State to E4State. (See the labeled grid in Figure 2 in Part I). Of course, while the State design pattern diagram is relatively simple, the Context can be challenging, especially when using a Json file for recording moves. However, to get started with the code, we’ll start at the beginning with the UI and the Client that makes requests to the State pattern.

The UI and Client

The UI is an HTML5 document embedded in a PHP class and is more of an HTML document than a PHP one. A heredoc string (EXPLORE) is placed in a PHP private variable, $explorerUI. An echo statement displays the HTML on the screen when the $worker variable instantiates the PHP class.

< ?php
class ExplorerUI
{
    private $explorerUI;
    public function __construct()
    {
        //Use the Security object to encode table
        $this->explorerUI=< <<EXPLORE
        <!DOCTYPE html>
        <html>
        <head>
            <link rel="stylesheet" type="text/css" href="explorer.css"/>
            <meta charset="UTF-8"/>
            <title>OOP Cavern</title>
        </head>
 
        <body>
            <h2>OOP Explorer</h2>
        <h3>Explore Next Direction</h3>
        <fieldset>
        <legend>Move Options</legend>
        <form action="ExplorerClient.php" method="post" target="cavestate">
        <table>
            <tr><td></td><td><input type="radio" name="move" value="northMove"/>&nbsp;Move North</td><td></td></tr>
            <tr><td><input type="radio" name="move" value="westMove" checked="checked"/>&nbsp;Move West</td><td></td><td></td><td><input type="radio" name="move" value="eastMove"/>&nbsp;Move East</td></tr>
            <tr><td></td><td><input type="radio" name="move" value="southMove"/>&nbsp;Move South</td><td></td></tr>
        </table>
        </form></fieldset><p></p>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type = "text" name="seeker" maxlength="5" size="6" value ="chump"/>&nbsp Your seeker name: Five characters; no spaces<p></p>
        <input type="submit" class="submit" name ="makemove" value ="Make your move"/>
 
        <p></p>
        <iframe seamless name="cavestate" width="500" height="450">CaveState</iframe>
        </body>
        </html>
EXPLORE;
        echo $this->explorerUI;
    }
}
$worker=new ExplorerUI();
?>

I used a table for setting up the UI “move center” to make it easy for the player to select the next move. (A CSS form for the move center certainly would be more elegant, but the table worked ok; so I used it after testing it on a desktop, tablet and smartphone.) You can see how the UI looks in Figure 1 in Part I of the State maze).
Continue reading ‘State Maze Part 2: Play’

Share

The Design Pattern Principle Maze Part 1: A Story in a State Pattern

Happy New Year Everyone!

mazeFor the last ten weeks I’ve been learning functional programming and Haskell through an edX MOOC offered through Delft University (DelftX) in the Netherlands. (TU Delft is The Netherland’s equivalent to MIT in the US) Check out the YouTube video on the course here. That’s why I haven’t been creating new posts for this blog. Now it’s time to catch up! So, I’ve created a maze game that explores the major principles in design pattern programming using a State design pattern.

Play with a Purpose

This particular maze follows a trail of OOP and Design Pattern principles to the end of the maze. As you find each principle, you will see an image and a statement of the principle. For example, the first part of the maze moves through the S.O.L.I.D. acronym to help you remember five basic OOP principles. When you find the room with the Interface Segregation principle, Figure 1 shows what you will see:

Figure 1: A room in the maze with an OOP principle.

Figure 1: A room in the maze with an OOP principle.

Movement is controlled by a set of four ratio button and a “Make Move” button. Each user must include a unique user name where the moves for the user are stored in a Json file. A State Design Pattern helps not only in creating this maze, but it is a template for any 5 x 5 maze!

Why use a State Pattern on a Maze?

In building a D&D style maze, I started out with a blank sheet of paper and sketched out a 5 x 5 maze shown in Figure 2 (with labels).

Figure 2: The 5 by 5 Matrix --  coordinate values will become class names.

Figure 2: The 5 by 5 Matrix — coordinate values will become class names.

By picturing the matrix as being made up of 25 different states, the reason for using a State design pattern starts to take shape. If each grid square is a state, we can create code that determines what happens to the player who moves into a given state (square).

Adding Start/Finish Points and Trouble

You can decide which states will be the starting and ending states simply by designating them as such. As you can see in Figure 3, the game starts in B1 and ends in D5. The next step is to add back-to-the-start traps. These represent any kind of booby-trap you care to add to make the game interesting. You want to add enough to make the player pay attention but not so many as to make it impossible. Figure 3 shows six sequential traps–game re-start conditions that must be avoided.

Figure 3:  Add start and end states and booby-traps.

Figure 3: Add start and end states and booby-traps.

In building your maze, keep in mind that for the player, it will seem like a cavern; not the chessboard that you can see. Continue reading ‘The Design Pattern Principle Maze Part 1: A Story in a State Pattern’

Share

PHP Functional Programming Part II: OOP & Immutable Objects

immutableImmutable

In his book on Functional Programming in PHP Simon Holywell laments the lack of immutable structures in PHP, and while he suggests some hacks to insure immutability, we can make-do with some different hacks I’ll suggest. (Most of the hacks are mind-hacks–a way of thinking about data.) The idea of having a programming language where all objects are immutable (unchanging) sounds pretty awful. Not only that, it sounds impractical. Take, for example, a Boolean. It has two states; true and false. In functional programming, that means the Boolean variable is mutable, and so it’s out. However, you can have two objects that we can call, Alpha and `Alpha. Alpha is true and `Alpha is false. (The tick mark [`] is the key below the ‘esc’ key on your keyboard.) So instead of changing the state of Alpha from true to false, you change the object from Alpha to `Alpha.

Why would anyone want to do that? It has to do with the concept of referential transparency. In a concrete sense it means that if an object (reference) were replaced by its value, it would not affect the program. Consider the following:

   $val=5;
   $alpha= function() use ($val) {return $val * $val;};

can be replaced by;

   $alpha=25;

Nothing in the program will change if either $alpha variable is used. For a simple example of referential transparency, that’s no great shakes. Besides we lose the value of changing states. However, functional programming eschews the concept of changing states. To quote one functional programmer,

Do not try to change the state; that’s impossible. Instead only try to realize the truth: There is no state.

Again, this looks nuts both conceptually and in the real world. Take, for instance, a thermometer that changes from freezing (32F / 0C) to not freezing (say 50F / 10C). The temperature has changed states! How can anyone say it has not? Or a child changes states into an adult, or a caterpillar changes states to a butterfly?

According to the functional programming model, a freezing temperature is a different object than a non-freezing one; an adult is a different object than a child, and (clearly) a butterfly is a different object than a caterpillar. So, if I say that the thermometer has changed from 32° to 33°, it is not state that has changed, it is a different object. Objects can be as granular as you like, and if you think of atoms arranged to display a ruler, you can move from one atom (object) to the next atom (object) with no state involved at all.

The State Design Pattern: Wasn’t it Immutable All Along?

The State design pattern would seem to be the polar opposite of functional programming. However, if we examine it closely, we can re-conceptualize it as object swapping. Take a simple two-state example: a light going on and off. There’s a light-on object and a light-off object. The design is the same, but we think about it in different ways. Also, the individual state methods can include nothing but lambda functions or closures. Consider Figure 1. An “on” light JPG and an “off” light JPG can be considered two separate states or two immutable objects.

Figure 1: Two States or Two Immutable Objects

Figure 1: Two States or Two Immutable Objects

To make the State pattern more “immutable-like” the interface has two constants with the URLs for the two different images. To get started, Play the light switch State application and Download the files:
PlayDownload

The application uses a simple State design pattern. All requests go through the Context, which keeps track of the current state. However, this implementation fudged a bit because each time the UI calls the Client, it creates a new Context object; so no state is saved, and I had to add a statement to use the called method to set the correct state for switching the light on and off. (Note to self: Get busy on the RESTful API!) Also, I added two constants to the interface (IState) to impose an immutable property in the state implementations. Figure 2 shows the class diagram of the implementation:

Figure 2: State design pattern implementation

Figure 2: State design pattern implementation

The pattern diagram in Figure 2 provides an overview of the classes and key methods in those classes. The LightSwitch class is just an HTML document wrapped in a PHP class, an it is where a request originates in this model. The other roles you can see in the following outline:

  • Client: Get the request from the UI (LightSwitch) and using a Context instance and method, the request is sent to the Context.
  • Context: Always the most important participant in a State design pattern, it determines the current state and passes the request to it via the appropriate method based on the request.
  • IState: The State interface specifies the required methods and may include constants.
  • Concrete States: The On / Off states (IState implementations) return the requested state-as-an-object.

With that overview in mind, you can better understand all of the singular roles of the participants. (Continue to see listings and explanations.)
Continue reading ‘PHP Functional Programming Part II: OOP & Immutable Objects’

Share

PHP Game Making Part III: State Design Pattern

FenrirA Viking Tale

To wrap up this final post on the State Design Pattern, I thought we might make the game of R-P-S-L-S a little more interesting. So naturally I turned to the ancient Norse Gods and their stories. This one involves a giant wolf named Fenrir (pictured to the left at a PHP conference), and two gods, Tyr and Vidar. Tyr had his right hand eaten by Fenrir as he distracted the wolf with a handy snack while others tied up the wolf. Because of his bravery, Tyr became the god of war. (He also became a lefty—everyone loves a southpaw.) Later, Fenrir got loose from his bindings and went on a rampage. Eventually, he was killed by Vidar, who went into Fenrir’s giant jaws and stabbed him in the heart. As it turned out, the two Norse gods loved to play R-P-S-L-S; so naturally, they became the gods in this revised game.

In Part II of the PHP Game Making series, you saw how a state machine works. In this final part of the series, I’d like to see how we can make a two-player PHP game of R-P-S-L-S and play it over the Internet. First, though, take a look at the class diagram for the State design pattern in Figure 1:

Figure 1: State Design Pattern class diagram

Figure 1: State Design Pattern class diagram

The State Design Pattern is made up of a Context and a State Machine. In Figure 1, the state machine is everything to the right of the Context. As you saw in Part II, a state machine moves from state to state, and depending on the state, different outcomes occur. Statecharts show the states, their transitions and outcomes. The Context class keeps track of the current state. That’s it for the State Design Pattern. To get started, download the files, and set up the game (You’ll need a MySQL database for this version.)
Download

After you create the table with the CreateTable.php program, you must use the Initialize.php program to set it up for play.(Caution: Only use the Initialize program once!) Then after each game, you need to run the Reset.php program before you can play the next game.

The New UI

The new UI is like the old one, but both players must click on the Referee button to get the results. This allows two players to play remotely—one player can be in Brazil and the other in France, and they can play. Figure 2 shows the new UI:

Figure 2: The Tyr and Vidar User Interfaces

Figure 2: The Tyr and Vidar User Interfaces

As you can see, the UI is pretty similar to the original in that the player selects one of five moves from the available radio buttons. In this version, though, the moves are stored in a database table. Once both players have moved, a Referee class (the Client in this version) sends the moves to the Context and the State pattern works out which of the two players have won and stores the outcomes in a referee field in the table. The table only has a single row, and that row is updated as moves are made and the game is reset. Figure 3 is a class diagram of this revised game. (The actual participants in the State design pattern is outlined in dashed lines.)

Figure 3: Class diagram of state design pattern

Figure 3: Class diagram of state design pattern

In order to further clarify how this implementation of the State design pattern works, look at the following steps:
Continue reading ‘PHP Game Making Part III: State Design Pattern’

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