PHP development framework YiiFramework tutorial (4) Hangman word game instance

Source: Internet
Author: User
With the previous "Hello, World" example and introduction to the basic YiiFrameworkWeb application, you can start to introduce a simple and complete Web application-Hangman (guessing word game ), this example is released with the Yii development kit. This example shows the basic steps for Yii application development.

With the previous "Hello, World" example and introduction to the Yii Framework Web application, you can start to introduce a simple and relatively complete Web application-Hangman (guessing word game). This example was released with the Yii development kit. This example shows the basic steps for Yii application development.

Speaking of "Hangman" reminds me of the "word guessing game"-Hangman, which was completed on the CPC464 computer in the late 1980s s, let's move a villain away from the tornado. At that time, DOS just came out :-).

To develop a Web application, we first need to analyze the requirements. this is not part of this tutorial. but for the sake of completeness, we still need to list the rules for "guessing word games" below:

Word Game (Hangman, "Hanging Man") is a two-person game. One player wants one word, and the other tries to guess every letter in the player's words.

The word to be guessed is displayed in a horizontal line, allowing the player to know how many letters the word has. If a player guesses one of the letters, the other must write the letter at all positions where the letter appears. If the guess letter does not appear in the word, the other player will draw one of the hanging-neck dolls. The game will end in the following circumstances:

 

 

"I want t words ." "Yes, it is in the eighth and 11th places ."

The player guessed all the letters, or guessed the entire word.

Another player draws a complete picture:

The example given today does not show the "hanging person". I guess it is "You Win" and I guess it is "You Lose ". Therefore, we can design four pages:

The four pages correspond to four views in Yii Framework, which can be named play, guess, win, and lose respectively. each page displays the title of "Hangman Game, therefore, you can design a "MasterPage" to form a Layout template in Yii for the four views to share. Yii uses the MVC design mode, so we can design a Controller> GameController for the four views.

As mentioned in the previous tutorial, the Yii application uses the default directory structure to store different parts of the application. you can use the tool provided by Yii to participate in a default project directory. However, I personally prefer to create various directories by myself. Therefore, based on the above requirements and interface design, you can create a project directory structure as follows:

Put the created GameController. php in the protected/controller directory.

The four views guess. php, lose. php, play. php, and win. php created are stored in the protected/views/game Directory. The directory name game corresponds to the GameController used.

The created shared Layout is placed in the protected/views/layout Directory. the default Layout name is main. php.

The application configuration file is placed in protected/config. the default configuration file is main. php.

The entry script of the application is index. php.

In addition, the text file used to guess words is word.txt.

1. check the configuration file protected/config/main. php.

Return array (
'Name' => 'hangman game ',
'Defaultcontroller' => 'game ',
'Components' => array (
'Urlmanager' => array (
'Urlformat' => 'path ',
'Rules' => array (
'Game/guess/ '=> 'Game/guess ',
),
),

),
). All writable properties of the CWebApplication can be defined in the configuration file. we can see that the configuration file defines the application name as "Hangman Game ", then modify the default Controller name of the Web application to correspond to the GameController. if the defaultController is not redefined, the default Controller name is SiteController, in this way, the View will be stored in the protected/views/site Directory. In addition, the urlManager component is enabled for this Yii application. the functions of this component are described later. it is mainly used to define the URL format (routing format) that users can access ).

2. with this configuration file, you can use it in the entry script. the entry script index. php of each Yii application is similar, and most of the cases are Copy & Paste.

$ Yii = dirname (_ FILE _). '/.../../framework/yii. php ';
$ Config = dirname (_ FILE _). '/protected/config/main. php ';
Require_once ($ yii );
Yii: createWebApplication ($ config)-> run (); 3. then define the layout file protected/views/layout/main used by the View. php main. php is the default layout template. The application can modify the layout used by the View. In this example, the default layout name is main.

Transitional // EN"
Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>



Hangman Game


Hangman Game


The layout is basically an HTML file, which acts as the placeholder of the view, that is, when a specific View is displayed, for example, play. php replaces $ content with the content of play. php. Thus, a function similar to "MasterPage" is implemented. 4. here we can define four views one by one. here we will not list them one by one. take play. php as an example:

This is the game

Hangman.
You must guess a word, a letter at a time.
If you make too then mistakes, you lose the game!












You must choose a difficulty level!


As you can see, it is basically HTML. CHtml is a helper class supported by the Yii Framework to help generate HTML code. Hangman is relatively simple, so it does not use a separate Model. Instead, it uses render to push parameters.

You must call CController: render () by passing the View name (). This method will find the corresponding view file in the protected/views/ControllerID directory.

In the view script, we can use $ this to access the controller instance. in the view, we can use $ this-> propertyName to pull any attributes of the controller.

We can also use the following push method to transmit data to the view:

$ This-> render ('edit', array (
'Var1' => $ value1,
'Var2' => $ value2,
); In the preceding method, the render () method extracts the second parameter of the array into the variable. the result is that in the view script, we can directly access the variables $ var1 and $ var2.

5. after the layout and View are defined, you can write the GameController,

Class GameController

Extends CController
{
/**
* @ Var string sets the default action to be 'play'
*/
Public $ defaultAction = 'play ';

/**
* The 'play' action.
* In this action, users are asked to choose a difficulty level
* Of the game.
*/
Public function actionPlay ()
{
...
}

/**
* The 'Guess 'action.
* This action is invoked each time when the user makes a guess.
*/
Public function actionGuess ()
{
...
}

/**
* The 'Guess 'action.
* This action is invoked when the user gives up the game.
*/
Public function actionGiveup ()
{
...
}

...
} Generally, the default action of the Controller is index. you can use $ defaultAction to modify the default Action. In this example, the default action is play. if the url in this example is http: // 127.0.0.1: 8888/yii/demos/hangman/, use http: // 127.0.0.1: 8888/yii/demos/hangman/index. php and use http: // 127.0.0.1: 8888/yii/demos/hangman/index. php? The effects of game/play are the same. The default Controller is GameController, and the default action of GameController is play.

Action. an action can be defined as a method named after the Action word as the prefix. Hangman defines three actions, actionPlay, actionGuess, actionGiveup, and GameController. other methods and attributes are generated into words to determine whether to guess. the specific game logic has little to do with the Yii Framework, I will not introduce it.

6. first, let's look at the default playAction, which is the default method called by the user. that is to say, when the user group address bar is entered http: // 127.0.0.1: 8888/yii/demos/hangman/index. php (or http: // 127.0.0.1: 8888/yii/demos/hangman/index. php? Game/play.

Public function

ActionPlay ()
{
Static $ levels = array (
'10' => 'easy game; you are allowed 10 misses .',
'5' => 'medium game; you are allowed 5 misses .',
'3' => 'hard game; you are allowed 3 misses .',
);

// If a difficulty level is correctly chosen
If (isset ($ _ POST ['level'])
& Isset ($ levels [$ _ POST ['level'])
{
$ This-> word = $ this-> generateWord ();
$ This-> guessWord = str_repeat ('_', strlen ($ this-> word ));
$ This-> level = $ _ POST ['level'];
$ This-> misses = 0;
$ This-> setPageState ('guessed ', null );
// Show the guess page
$ This-> render ('Guess ');
}
Else
{
$ Params = array (
'Levels' => $ levels,
// If this is a POST request,
// It means the level is not chosen
'Error' => Yii: app ()-> request-> isPostRequest,
);
// Show the difficulty level page
$ This-> render ('play', $ params );
}
}

This method defines three difficulty levels for the game $ levels and has two branches. If no difficulty level is selected, call $ this-> render ('play', $ params ), when the Play page is displayed, $ params (Array) is pushed to the corresponding View, protected/views/play. php, refer to the above View definition:

View uses Radiobutton to display the list defined by $ levels.

If you select a Level of difficulty, store level and word in the attributes defined by GameController, such as word and Level. GameController and CController are also subclasses of CComponent. CComponent supports attribute functions similar to C # and Java. Later. Then call $ this-> render ('Guess '); to display the guess page. The Guess. php page is defined as follows:

Please make a guess


GuessWord;?>

You have made
Misses;?>
Bad guesses out of a maximum
Level;?>.





Guess:
For ($ I = ord ('A'); $ I <= ord ('Z'); ++ $ I)
{
If (! $ This-> isGuessed (chr ($ I )))
Echo "\ n". CHtml: linkButton (chr ($ I ),
Array ('submit '=> array ('Guess', 'G' => chr ($ I ))));
}
?>



Array ('submit '=> array ('giveup');?>



In View, you can directly access the methods and attributes of the corresponding Controller instance object through $ this. For example, $ this-> guessWord, $ this-> isGuessed (chr ($ I. Click 26 letters to trigger guessAction (array ('submit '=> array ('Guess', 'G' => chr ($ I ))))).

7. The following is the definition of guessAction.

Public function actionGuess ()
{
// Check to see if the letter is guessed correctly
If (isset ($ _ GET ['G'] [0]) & ($ result = $ this-> guess ($ _ GET ['G'] [0])! = Null)
$ This-> render ($ result? 'Win': 'lose ');
Else // the letter is guessed correctly, but not win yet
{
$ Guessed = $ this-> getPageState ('guessed ', array ());
$ Guessed [$ _ GET ['G'] [0] = true;
$ This-> setPageState ('guessed ', $ guessed, array ());
$ This-> render ('Guess ');
}
} The parameter 'G' is input by submitting on the guess page. If all words are correctly guessed, "You win" is displayed, or "You lose" is displayed after all times ", $ this-> render ($ result? 'Win': 'lose'). If you still have the chance to guess whether to return to the guess page $ this-> render ('Guess ');

8. there is a "Give up" button on the Guess page. the user clicks it to trigger giveupAction. this method is relatively simple and the lose page is displayed directly.

Public function actionGiveup ()
{
$ This-> render ('lose ');
} Now the Hangman game is basically complete. Although the game is simple, it illustrates the basic process of using Yii to develop applications. The following describes the development process provided by the Yii development documentation. Hangman is relatively simple and does not use databases or internationalization.

The development process here assumes that we have completed the analysis of application requirements and necessary design analysis.

Create a directory structure skeleton. The yiic tool described in the first Web application can be created to quickly implement this step.

Configure this application. This is achieved by modifying the application configuration file. You may also need to write some application components (such as user components) in this step ).

Creates a model class for each managed data type. The Gii tool described in Creating First Yii Application and Automatic Code Generation can be used to quickly create an active record class for each data table. 4. create a controller class for each type of user request. How to classify user requests depends on actual needs. In general, if a model class needs to be accessed by the user, it should have a corresponding controller class. The Gii tool can also automatically perform this step.

Implement actions and their corresponding views. This is what you really need to do.

Configure necessary action filters in the controller class.

If the topic function is required, create a topic.

If you want to internationalize (I18N), create translation information.

Apply the appropriate caching technology to cacheable data points and view points.

Final adjustment and deployment.

In each of the preceding steps, you may need to create and execute test cases.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.