Monthly Archive for August, 2013

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’

Choosing a PHP Design Pattern: Part III —Intentions & Encapsulating Variation

PickDP3I was very sorry when I found out that your intentions were good and not what I supposed they were.Sitting Bull after the Battle of Little Big Horn

Easing into a Selection

We have a bumper crop of peaches this year, and I’ve been peeling, slicing and freezing peaches for the last couple of weeks. It reminded me that Part III of Choosing a PHP Design Pattern is due. This is the third and last installment in the series. You might want to take a look at Part I and/or Part II of this series before or after looking at this post.

Wouldn’t it be nice if you could type in the name of your intended project and up pops the best possible design pattern for that project? Even if you hold your breath until you turn blue, that’s not going to happen. However, such a project (a DP Picker) is a worthy one. You can begin to narrow down your choices by asking whether your project is one that belongs in the Creational, Structural or Behavioral categories. If you’re lucky, you’ll end up with the Creational category and only have five patterns from which to choose. (Since the Singleton is one of that group, you really only have to choose from four.) The following is a summary of each category. (The major sections of Learning PHP Design Patterns begin with a brief overview of each category. See pages 77, 121 and 167.)

  • Choose Creational When…You want to abstract the instantiation process and separate the use of the object from its creation.
  • Choose Structural When…You want to create larger structures from classes and objects.
  • Choose Behavioral When…You must focus of the communication between objects and the interaction between those objects.

Suppose I want to make an app that spends a lot of time loading and unloading different types of data and/or objects—which is something I often do. I’d probably want to choose a Creational pattern because I’m instantiating and removing lots of objects. Never mind which one; that’ll come later, but I’ve certainly narrowed my choices. On the other hand, if my main focus is going to be a game program, I’m going to need a good deal of inter-object communication and interaction and so I’m going to be looking at the Behavioral patterns. That will leave me with about half of the 24 patterns, but it’s a start.

Attention to Intention

The 24 different patterns have 24 different intentions (The Adapter pattern is counted twice since it has both Class and Object versions). The Gang of Four advise us to study the intention of each pattern to help make a decision about which one to use. Rather than listing them here, you can use the table developed in an earlier post, Design Pattern Variation and Intents Table, where you can also download the code for the table. Click the Play button to see the table:
Play

So what is an intention? Let’s take a look at the Proxy intention to get an idea:

Proxy Intention: Provide a surrogate or placeholder for another object to control access to it.

That kind of intention is pretty easy to envision. A login is one example where the user is logging into the Proxy and not the Real object. This was shown in Chapter 11 of Learning PHP Design Patterns and in a post on the Proxy pattern on this blog. (Click below to continue.)
Continue reading ‘Choosing a PHP Design Pattern: Part III —Intentions & Encapsulating Variation’

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’

PHP Game Making Part I: Algorithms and Design Patterns

cornerpicGeek Game

The Rice University MOOC course introducing Python owed part of its popularity to the fact that all of the projects involved game development. One of the first games was based on an old one called “Rock-paper-scissors” that has been revised and updated to Rock-paper-scissors-lizard-Spock. (For those of you who are Big Bang Theory fans, you may have seen it demonstrated on that show.) The game itself is pretty simple. Two players chant “Rock-paper-scissors-lizard-Spock” and as soon as “Spock” is spoken, they throw one of five hand gestures (see image in upper left corner for the five gestures.)

  • Rock – a Fist
  • Spock – Vulcan salute (hand with fingers separated at ring and middle fingers)
  • Paper – Flat hand
  • Lizard – Hand puppet shape with thumb and index finger forming ‘mouth’
  • Scissors – Two fingers in ‘cutting’ position

The winning outcome is determined by the following rules:

  • Scissors cut paper
  • Paper covers rock
  • Rock crushes lizard
  • Lizard poisons Spock
  • Spock dissenigrates scissors
  • Scissors decapitate lizard
  • Lizard eats paper
  • Paper disproves Spock
  • Spock vaporizes rock
  • Rock breaks scissors

Each gesture has two other gestures it can beat and two other gestures that beat it. For example, if a player throws a lizard gesture, it can beat paper and Spock, and it can be beaten by scissors and rock.

The Game in PHP

One of the main things that I came away with from the Python course was a more advanced and simpler way of calculating outcomes; primarily by the use of modular arithmetic. In PHP, some of you may have used the modulus (or modulo) operator (%) in setting up table lines for alternating colors something like the following algorithm:

$alternate = $counter % 2;
if($alternate)
{
  $shade = $dark;
}
else
{
  $shade = $light;
}
$alternate ++;

When a program employs modulus 2 (% 2) all outcomes are either 0 or 1, which translate to Boolean False and True, respectively. However, more can be done with modular arithmetic than alternate background shading in output.

To get started, take a look at Figure 1. Each of the gestures can defeat the two gestures counter clock-wise and is defeated by the two gestures clockwise of the gesture. For example, paper can defeat Spock and rock, but it is defeated by lizard and scissors.

Figure 1: Circle of wins and losses

Figure 1: Circle of wins and losses

Notice that each gesture has a number associated with it. That number will be used in determining the outcome. In this post I’d like to get started with the game playing against the computer. However, this being PHP, I’d like to develop a game two players can play against one another in future posts. (By the way, more than two players can play this game at the same time, but it gets cumbersome, and so throughout this series, we’ll just be using two players. Before going further, though, try out your luck against the computer:
Play

The moves of each player (you and the computer) is expressed in numbers associated with the circle. (Click below to continue.)
Continue reading ‘PHP Game Making Part I: Algorithms and Design Patterns’

Easy Writer: Setup for Raspberry Pi PHP

RaspPHPFocus on writing PHP Code

In fiddling around with PHP on a Raspberry Pi running on a Debian Linux OS more or less directly from a terminal mode, I realized that the focus (in my case) was getting the Linux commands right and very little with actually writing PHP programs. Most queries about getting the setup right involved Linux system administration and not PHP programming.

This short post is for Raspberry Pi users (and perhaps Linux users in general), and it focuses on setting up your Raspberry Pi so that you can use default Raspberry Pi editors (LeafPad) and the File Manager to work with PHP programs. Once set up, you will find the process of creating server-side programs in PHP much easier with no need to use the  terminal editors after setting up your system.

Installing Apache and PHP

Because PHP is a server-side language, you will need both a server and PHP installed on your Raspberry Pi. Using the Root Terminal (Accessories → Root Terminal), enter the following line:

sudo apt-get install apache2 php5 libapache2-mod-php5

Press the Enter key and patiently wait until it’s completed the setup. Once done, you computer will have both a web server and PHP installed. To test whether installation was successful, open a browser from the main menu (Internet → NetSurf Web Browser) and enter the following:

  http://localhost/

If everything works, you will see the message shown in Figure 1 on the right:

Figure 1: Default Web Page

Figure 1: Default Web Page

This location (http://localhost) is the root for your Web pages—PHP and any other Web page you decide to put on your Raspberry Pi Apache server. The name of the file is index.html. On your Raspberry Pi, in the Linux file system, the address is:

  /var/www/

Open the File Manager (Accessories → File Manager) and in the window where you see /home/pi enter /var/www. You will now be able to see the icon for the html file that was automatically created when you installed the Apache server.
Continue reading ‘Easy Writer: Setup for Raspberry Pi PHP’