


PHP development framework Yii Framework tutorial (4) Hangman word guessing game example
With the previous "Hello, World" example and the introduction to the basics of Yii Framework Web applications, we can start to introduce a simple and relatively complete Web application-Hangman (guessing game). This example comes with Yii Development package released. Through this example, you can understand the basic steps of developing Yii applications.
Speaking of "Hangman", it reminds me of the "guessing game" I played on the CPC464 computer in high school in the late 1980s - Hangman, every time I guessed wrong Once, a villain was taken one step away from the gallows. DOS had just come out at that time :-).
To develop a Web application, the first step is to conduct a requirements analysis. This is not included in this tutorial, but for the sake of completeness, the rules of the "guessing word game" are listed below:
Guess the word The game (English: Hangman, meaning "hanged man") is a two-player game. One player thinks of a word and the other player tries to guess each letter of the word that player thinks of.
The word to be guessed is represented by a column of horizontal lines, allowing players to know how many letters the word has. If the guessing player guesses one of the letters correctly, the other player must write that letter in all the positions where that letter appears. If the guessed letter does not appear in the word, the other player will draw one of the hanging neck doll's strokes. The game will end in the following situation:
"I want the word t." "Yes, in the eighth and eleventh place."
Guess the word The player guessed all the letters, or guessed the whole word
The other player drew the complete picture:
The example given today does not draw "The Hanged Man", the guess is correct If you guess correctly, it will display "You Win", if you guess wrong, it will display "You Lose". Therefore, we can design four pages:
These four pages correspond to the Yii Framework as four Views, which can be named play, guess, win, lose. Each page Each page displays the title of "Hangman Game", so you can design a "MasterPage" and become a layout template in Yii for four Views to share. The Yii application adopts the MVC design pattern, so we can design a Controller->GameController for four Views.
The previous tutorial said that the Yii application uses the default directory structure to store different parts of the application. Use the tools provided by Yii to add a default project directory. However, I personally prefer to create each directory by myself, so based on the above requirements and interface design, the directory structure of the project can be created as follows:
The created GameController.php is placed in protected/controller directory.
The four created Views guess.php, lose.php, play.php, win.php are placed in the protected/views/game directory. The directory name game corresponds to the shared Layout created by GameController.
and is placed in the protected/views/layout directory. The default layout name is main.php
The application configuration file Place it in protected/config. The default configuration file is main.php
The application entry script is index.php
In addition, the text file for word guessing is word.txt
1. First, let’s take a look at 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 attributes of the CWebApplication application can be defined through the configuration file. We See that the configuration file defines the name of the application as "Hangman Game", and then modify the default Controller name of the Web application to game, which corresponds to GameController. If the defaultController is not redefined, the default Controller name is SiteController, so that the View To be stored in the protected/views/site directory. In addition, this Yii application opens the urlManager component. The function of this component will be introduced later. It is mainly used to define the format of URLs that users can access (routing format).
2. With this configuration file, you can use it in the entry script. The entry script index.php of each Yii application is similar. In most cases, it is Copy & Paste
3. Then define the layout file protected/views/layout/main.php main.php used by View as the default layout template. The application can modify the layout used by View. In this example Just want the default layout name main..
The layout is basically an HTML file, in which as the placeholder of the view, that is, when displaying a specific View, such as play.php, the content of play.php is used instead. $content. Thus realizing a function similar to "MasterPage".
4. You can define the four Views one by one below. They are not listed one by one here. Take play.php as an example:
You can see that it is basically HTML, and CHtml is an auxiliary class supported by the Yii framework to help generate HTML code. Hangman is relatively simple, so it does not use a separate Model, but passes in parameters through render push.
You need to call CController::render() by passing the name of the view. This method will search for the corresponding view file in the protected/views/ControllerID directory.
Inside the view script, we can access the controller instance through $this. We can use $this-> propertyName method to pull any property of the controller.
We can also use the following push method to pass data to the view:
$this->render('edit', array(
'var1'=>$value1,
'var2'=>$value2,
));
In the above method, the render() method will Extract 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 defining the layout and View, you can Wrote GameController,
Generally, the default action of Controller is index. You can modify the default Action through $defaultAction. In this case, it is changed to play. Therefore, if this example The url is http://127.0.0.1:8888/yii/demos/hangman/
then 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?game/play has the same effect. The default Controller is GameController, and the default action of GameController is play.
Action (action). An action can be defined as a method named with the word action as a prefix. Hangman defines three actions, actionPlay, actionGuess, actionGiveup, GameController, other methods and attributes, and generated words. Determining whether to guess is equivalent. The specific game logic has little to do with the Yii framework and will not be introduced.
6. First look at the default playAction. This is the default method called by the user. That is to say, when the user group address bar enters http://127.0.0.1:8888/yii/demos/hangman / Action called by index.php (or http://127.0.0.1:8888/yii/demos/hangman/index.php?game/play).
This method defines the three difficulty levels of the game, $levels, with two branches. If no difficulty level is selected, $this->render(' play',$params), display the Play page, push $params (Array) to the corresponding View, protected/views/play.php, refer to the definition of View above:
View uses Radiobutton to display the list defined by $levels.
If the user selects the difficulty level, store Level, words, etc. in the attributes defined by GameController, such as word, level, etc. GameController and CController are also subclasses of CComponent. CComponent supports attribute functions similar to C# and Java. More details will be introduced later.
Then call $this->render(‘guess’); to display the Guess page.
Guess page guess.php is defined as follows:
In View, you can directly access the methods and properties of the corresponding Controller instance object through $this. Such as $this->guessWord, $this->isGuessed(chr($i)), etc.
Click on 26 letters to trigger guessAction (array('submit'=>array('guess','g'=>chr($i))))).
7. Below The definition of guessAction
The parameter 'g' is passed in when submitted by the guess page. If all the words are guessed correctly, "You win" will be displayed or all the times of guessing incorrectly have been exhausted. Displays "You lose", $this->render($result ? 'win' : 'lose'),
If you still have a chance to guess, go back to the guess page$this->render('guess');
8. There is also a "Give up" button on the Guess page. When the user clicks it, the giveupAction is triggered. This method is relatively simple and directly displays the lose page
Now the Hangman game is basically completed. Although the game is simple, it illustrates the basic process of developing applications using Yii. The development process given in the Yii development document is given below. Hangman is relatively simple and does not use databases and internationalization.
The development process here assumes that we have completed the application requirements analysis and necessary design analysis.
Create directory structure skeleton. The yiic tool mentioned in Creating the First Web Application can quickly implement this step.
Configure this application. This is achieved by modifying the application configuration file. This step may also require writing some application components (such as user components).
Create a model class for each type of data managed. The Gii tools described in Creating First Yii Application and Automatic Code Generation can be used to quickly create active record classes for each data table. 4. Create a controller class for each type of user request. How to classify user requests depends on actual needs. Generally speaking, if a model class needs to be accessed by users, it should have a corresponding controller class. Gii tools can also automate this step.
Implement actions and their corresponding views. This is the real work that needs to be done.
Configure the necessary action filters in the controller class.
If you need theme functionality, create a theme.
If internationalization (I18N) is required, create translation information.
Apply appropriate caching techniques to cacheable data points and view points.
Final adjustment and deployment.
The above is the content of the PHP development framework Yii Framework tutorial (4) Hangman word guessing game example. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



With the continuous development of cloud computing technology, data backup has become something that every enterprise must do. In this context, it is particularly important to develop a highly available cloud backup system. The PHP framework Yii is a powerful framework that can help developers quickly build high-performance web applications. The following will introduce how to use the Yii framework to develop a highly available cloud backup system. Designing the database model In the Yii framework, the database model is a very important part. Because the data backup system requires a lot of tables and relationships

As the demand for web applications continues to grow, developers have more and more choices in choosing development frameworks. Symfony and Yii2 are two popular PHP frameworks. They both have powerful functions and performance, but when faced with the need to develop large-scale web applications, which framework is more suitable? Next we will conduct a comparative analysis of Symphony and Yii2 to help you make a better choice. Basic Overview Symphony is an open source web application framework written in PHP and is built on

The Yii framework is an open source PHP Web application framework that provides numerous tools and components to simplify the process of Web application development, of which data query is one of the important components. In the Yii framework, we can use SQL-like syntax to access the database to query and manipulate data efficiently. The query builder of the Yii framework mainly includes the following types: ActiveRecord query, QueryBuilder query, command query and original SQL query

As the Internet continues to develop, the demand for web application development is also getting higher and higher. For developers, developing applications requires a stable, efficient, and powerful framework, which can improve development efficiency. Yii is a leading high-performance PHP framework that provides rich features and good performance. Yii3 is the next generation version of the Yii framework, which further optimizes performance and code quality based on Yii2. In this article, we will introduce how to use Yii3 framework to develop PHP applications.

In the current information age, big data, artificial intelligence, cloud computing and other technologies have become the focus of major enterprises. Among these technologies, graphics card rendering technology, as a high-performance graphics processing technology, has received more and more attention. Graphics card rendering technology is widely used in game development, film and television special effects, engineering modeling and other fields. For developers, choosing a framework that suits their projects is a very important decision. Among current languages, PHP is a very dynamic language. Some excellent PHP frameworks such as Yii2, Ph

If you're asking "What is Yii?" check out my previous tutorial: Introduction to the Yii Framework, which reviews the benefits of Yii and outlines what's new in Yii 2.0, released in October 2014. Hmm> In this Programming with Yii2 series, I will guide readers in using the Yii2PHP framework. In today's tutorial, I will share with you how to leverage Yii's console functionality to run cron jobs. In the past, I've used wget - a web-accessible URL - in a cron job to run my background tasks. This raises security concerns and has some performance issues. While I discussed some ways to mitigate the risk in our Security for Startup series, I had hoped to transition to console-driven commands

With the rapid development of the Internet, APIs have become an important way to exchange data between various applications. Therefore, it has become increasingly important to develop an API framework that is easy to maintain, efficient, and stable. When choosing an API framework, Yii2 and Symfony are two popular choices among developers. So, which one is more suitable for API development? This article will compare these two frameworks and give some conclusions. 1. Basic introduction Yii2 and Symfony are mature PHP frameworks with corresponding extensions that can be used to develop

In modern software development, building a powerful content management system (CMS) is not an easy task. Not only do developers need to have extensive skills and experience, but they also need to use the most advanced technologies and tools to optimize their functionality and performance. This article introduces how to use Yii2 and GrapeJS, two popular open source software, to implement back-end CMS and front-end visual editing. Yii2 is a popular PHPWeb framework that provides rich tools and components to quickly build
