[In-depth Cocos2d-x] using MVC Architecture to build the game Four

Source: Internet
Author: User

If you like Four, go to GitHub and click Star!

I like my articles. Come to Weibo and follow me: Wang xuanyi is learning C ++.

Click my download project Origin

Project Logo:

The following is the project address of the game. If you want to refer to the source code, you can download the source code of this project from my GitHub.

Project Homepage

GitHub address

Bug feedback and suggestions

The original purpose of my project is to experiment with the application of MVC in the game.

Model-View-Controller (MVC) is a combination design Model that reflects the idea of Separation of concerns (SoC. MVC decouples the logic layer and the presentation layer, and divides a problem into different concerns. This enhances application stability, ease of modification, and reusability.

MVC is often used in Web frameworks, including J2EE, RoR, and. the MVC model is encapsulated on the framework layer, so that programmers can easily and easily make well-structured Web applications.

Cocos2d-x itself does not provide built-in MVC support, but we can still design the game in the game based on the MVC Architecture. In this blog post, I will show you how I use the MVC Architecture to play the Four game. Game scenarios

Four: the idea of this game comes from a traditional game called the Four-game. Here is a detailed introduction of the Four-game rule: Go to the Baidu Encyclopedia of the Four-game.

Next I will briefly discuss some features of this panel game.

  • A Game Board with four rows and four columns)
  • There will be some "Game Piece" on the board, and only one Piece can be placed on each square ).
  • During Game initialization, the four grids above and below on the board had four sunspots and four white devils respectively.
  • Players can use microphones to move the chess pieces on the board to trigger events such as eating and victory.
  • When the layout of a horizontal or vertical chess piece changes to two black, one white or two white and one black, you can eat one child.
  • When only one piece of chess (black or white) is eaten, this part is recorded as failed.

For example, the following figure shows a picture of the game. In the following game process, the sunspots at the position () Move to the left to the position () and then the white child can be eaten.

Tools provided by Cocos2d-x

Cocos2d-x has such a number of major classes, CCSprite, CCLayer, CCScene, CCNotificationCenter. We will use these classes to build the MVC Architecture in the game, if you are not familiar with the role of these classes, please refer to my blog [Cocos2d-x-Basic Concepts] ctor Scene Layer and Sprite.

The general game process is

  • Use AppDelegate to initialize the first CCScene.
  • Create multiple cclayers In the first CCScene. Control the zOrder of CClayer ).
  • Add various CCSprite, CCLabelAtlas, or particle effects to CCLayer.
  • Register the touch event listener at the CCLayer layer, and write the corresponding callback function in the implementation of the CCLayer to perform logical processing on the Child Node of the CCLayer.

This process looks simple and allows you to make games very quickly. However, the defect lies in that we have done too many things in the CCLayer. CCLayer is responsible for both the logic layer and the presentation layer. It does not conform to the separation of concerns mentioned above. If the game has more complex status changes, it will be too slow.Project file directory

The following is the directory structure of the game project. We will explain these folders separately:

The following is a simple class diagram of the project.

In the class diagram, the dotted line represents communication through the message mechanism, and in the Cocos2d-x, this communication is achieved through the ccicationicationcenter. Model)

What the Model represents in the game isMessage-driven Finite State Machine, The Model will accept the message sent by the Controller layer, change its internal data according to the message, and then send the message of internal data change to View to notify it to update.

Which class does the Model correspond to in the Cocos2d-x?

Unfortunately, but the Cocos2d-x does not provide the feature of the state machine, so we need to implement a Model class, in the Model class, we need to implement functions such as state conversion and message processing. For example, in my Model class, I provide the following interfaces.

Class Model: public CCObject {public: // Add a status transition, from-start status, msg-received message, to-end status, when msg occurs, status conversion Model * addTransition (const string & from, const string & msg, const string & to) will occur ); // check whether the current state machine can convert the status of msg to bool checkMessage (const string & msg); // trigger the status conversion of msg to void onMessage (const string & msg ); void onMessage (const string & msg, CCObject * o); // wait for a CCAction to end before sending a message. Void waitAction (cocos2d: CCNode * node, cocos2d: CCFiniteTimeAction * action, const string & msg); // get the current status name const char * getState ();};

Note the following:

  • The Model class inherits CCObject to be consistent with the memory management system of the Cocos2d-x itself.
  • In onMessage, we first find the status transition in msg. After the status is changedCCNotificationCenterSend a message to notify other components in the game to update the logic.
  • In waitAction, We are processing an asynchronous state conversion. For example, when a piece moves, it will undergo this state conversion: start-> moving-> end, after the move ends, View will send a message similar to END_MOVE to notify the Model to update its status.

The Model does not hold the View, so the View obtains the Model update events through messages.

When writing a game, we should first write a Model and then test it to ensure the correctness of the Model.

Then, when we write the View, we actually write the callback functions for various messages sent by the Model state machine.

In this way, the presentation layer and the logic layer can be separated to test each module separately, greatly improving the maintainability.Logical Data and actual data

When writing a Model, we often encounter this problem, that is, whether the data in the Model should be consistent with the data in the View.

For example, should the position information of the pawns on The View layer be consistent with that on the Model layer?

In fact, the actual situation is that it depends on the Model layer
Computing makes it easier to use the data format. For example, in the Model, we will convert the Board into a two-dimensional array, which is more advantageous for AI operations and logical judgment, therefore, the logical position of a piece must be different from the actual position.

For another example, the unit of measurement for the physical engine in the game is centimeter or meter. Rather than the coordinates in OpenGL. This is also for the convenience of logical operations.

However, some numeric values are consistent, such as the character attributes. View)

In the game, View represents the receiver of Model messages. In the Cocos2d-x, View generally refers to the child nodes of the CCLayer, that is, CCSprite, CCLabelAtlas, CCMenuItem, Particle System (Particle System) and so on.

They reload the onEnter function and register their own listening to a Message in onEnter. In the onExit function, all listeners are cleared. (It is important to clear the listener. Otherwise, a terrible wild pointer problem may occur ). Controller)

In the game, the Controller is responsible for converting user touch events into logical events (that is, the messages we mentioned above). It also needs to normalize the information in user touch events and notify changes.

Controller is generally used in Cocos2d-x CCLayer
Because CCLayer naturally inherits the CCTouchDelegate interface, it can touch events, so all xxxcontrollers in this game are inherited from CCLayer.

Another important role of the Controller is to create a View and a Model. Because the Controller is equivalent to an intermediate layer of the Model and View, the Controller will hold both the View and Model applications, to facilitate data transmission. Protocol)

Protocol defines some data shared by models, views, and controllers,

  • InMessage.hDefines various types of messages in the game,
  • InTag.hIn, it defines some Node tags in the game. In fact, the Tag definition is not very accurate. In fact, the Tag here refers to an ID that uniquely identifies CCNode.
  • InChessboardProrocol.hDefines the width of the mid-game disk and some common data structures.
References
  • Wikipedia
  • Baidu encyclopedia
  • Blog of Zilong Shan Ren-how to build a game through MVC

Related Article

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.