Quick-cocos2d-x learning series 11 MVC examples

 

MVC is a design pattern, its full name is Model View Controller, which is the abbreviation of Model, View and Controller. It is a kind of software design Model, which organizes code by separating business logic, data and interface display. Aggregating business logic into a single component allows you to improve and personalize the interface and user interaction without having to rewrite the business logic. MVC has been uniquely developed to map traditional input, processing, and output functions in a logical graphical user interface structure.

1. Code organization

There are three folders: Models, Views, and Controllers.

 

1.1             Models

Main folder Actor. Lua,Hero. Lua

Hero.lua inherits from the Actor class.

The Actor class implements better attack power, defense power, initial HP, etc.

It also includes the implemented state machine.

1.2             Views

The main folder heroView.lua

The main implementation of Sprite state changes after the CHANGE of HP, level changes and other views.

Register model events with views to automatically and dynamically update views as the model changes.

1.3             Controllers

Main file playduelController.lua

The constructor is responsible for creating an object that determines whether the Player exists and creates it if it does not.

Create another enemy.

Set a variable

self.views_ = {}

self.bullets_ = {}

Set the self.views_ variable with createView function.

Create two buttons one for the left Sprite to shoot and one for the right Sprite to shoot.

Add frame event (called per frame), function tick.

 

Finally, add the NODE_EVENT event to be called on exit.

 

The tick function takes care of all bullet positions and removes them if they are off screen. In addition, need to handle whether hit, if hit also need to handle.

2. Code execution process

Start in the MainScene scene, which creates a new layer and a PlayDuelController object.

Create a REFRESH button. Press and re-enter the MainScene scene to initialize, and the transition scene is flipy.

 

The PlayDuelController object is in the Controllers folder, so it can be understood as the entire control process, as described in the previous section.

Specific details will be added later.