


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)!

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.