Simple Application of MVC Framework in lua project development using cocos2dx
Recently, lua was used for development in game projects, and the MVC framework was used in the project. Recently, a friend asked me how to do this. Here I will share some ideas and some development skills.
Let's talk about MVC, that is, Model View Controller. Model is generally responsible for data processing; View is generally responsible for interface display; Controller is generally responsible for front-end logic processing. For a mobile game, the display and layout of the UI are the responsibility of the View. When a button is clicked, operations such as gesture sliding are handled by the Controller; the data resources required in the game are handed over to the Model.
Next, let's take a look at how to use it in game development. Here we will use Lua (the Environment uses cocos code ide) to explain it to you.
Let's take a look at the directory structure of the project:
Among them, cocos, Controller, Model, and View are needless to say. The global message type stored in the Event is used to manage the stuff in the game, such as resource management and scenario switching, layer switching. Utilities provides some tool classes, such as string processing. You can also customize directories as needed. For example, you can define a NetCenter folder for processing networks. In this example, data operations and tool classes are not used, so the two folders are empty.
The following describes the running process of the game.
Run the project and go to the main. lua file to see the main function:
local function main() collectgarbage(collect) -- avoid memory leak collectgarbage(setpause, 100) collectgarbage(setstepmul, 5000) -- initialize director local director = cc.Director:getInstance() --turn on display FPS director:setDisplayStats(true) --set FPS. the default value is 1.0/60 if you don't call this director:setAnimationInterval(1.0 / 60) cc.Director:getInstance():getOpenGLView():setDesignResolutionSize(320, 480, 1) --create scene local scene = require(GameScene) local gameScene = scene:startGame()end
Finally, we call the startGame function in the GameScene class to see the class GameScene:
Require (Managers. sceneManager) require (Managers. layerManager) local GameScene = class (GameScene) local scene = nilfunction GameScene: startGame () -- initialize scene = cc. scene: create () if cc. director: getInstance (): getRunningScene () then cc. director: getInstance (): replaceScene (scene) else cc. director: getInstance (): runWithScene (scene) Environment: initLayer (scene) self: enterGame () endfunction GameScene: enterGame () LayerManager: getInstance (): Role (LAYER_TYPE_MAIN) endreturn GameScene
In the startGame function, we create an empty scenario and call the SceneManager scenario manager to initialize the scenario. Finally, call the enterGame function to enter the main game interface. The enterGame function contains a LayerManager layer manager. Let's see how these two managers work. First look at SceneManager:
-- Scenario manager SceneManager ={}-- background layer bgLayer = nil -- game layer gameLayer = nil -- pop-up window layer panelLayer = nilfunction SceneManager: initLayer (scene) bgLayer = cc. layer: create () scene: addChild (bgLayer) gameLayer = cc. layer: create () scene: addChild (gameLayer) panelLayer = cc. layer: create () scene: addChild (panelLayer) end
It is easy to initialize three empty layers in order. Let's take a look at the LayerManager:
-- Layer manager LayerManager ={} LAYER_TYPE_MAIN = LAYER_TYPE_MAINlocal curLayer = nilfunction LayerManager: new (o) o = o or {} setretriable (o, self) self. _ index = selfreturn oendfunction LayerManager: getInstance () if self. instance = nil thenself. instance = self: new () endreturn self. instanceendfunction LayerManager: gotoLayerByType (type) if curLayer ~ = Nil then curLayer: destroy () end if type = LAYER_TYPE_MAIN thenlocal layer = require (Controller. MainLayerController): create () curLayer = layerendend
Look at the gotoLayerByType function. When switching the layer, check whether the current layer is empty. If it is not empty, delete it. Then, you can determine the layer to switch to based on the passed parameters. Here the Controller section in MVC appears to see what the situation is. Here, the create function in the MainLayerController class is called:
Function MainLayerC: create () local layer = MainLayerC: new () return layerendfunction MainLayerC: ctor () self: createUI () -- create interface self: addBtnEventListener () -- Add button to listen to endfunction MainLayerC: createUI () local layer = require (View. mainLayerView) self. mainLayer = layer: createUI () gameLayer: addChild (self. mainLayer) end
Here we can find the View in MVC. In the createUI function, we call the createUI function like MainLayerView and add it to the game layer of the scenario. Let's take a look at the MainLayerView class.
Local eventDispatcher = cc. director: getInstance (): getEventDispatcher () local MainLayerV = class (MainLayerView, function () return cc. layer: create () end) function MainLayerV: createUI () local mainLayer = MainLayerV: new () return mainLayerendfunction MainLayerV: ctor () self: initUI () endfunction MainLayerV: initUI () local winSize = cc. director: getInstance (): getWinSize () self. bg = cc. sprite: create (ResManager. main_bg) self. bg: setPosition (winSize. width/2, winSize. height/2) self: addChild (self. bg) local function menuCallback (tag, menuItem) local event = cc. eventCustom: new (EVENT_CLICK_MENU_MAIN) event. _ usedata = tag eventDispatcher: dispatchEvent (event) end self. btnItem1 = cc. menuItemImage: create (ResManager. main_btn1, ResManager. main_btn1, ResManager. main_btn1) self. btnItem1: setPosition (winSize. width/2, winSize. height/3) self. btnItem1: setTag (1) self. btnItem1: registerScriptTapHandler (menuCallback) self. btnItem2 = cc. menuItemImage: create (ResManager. main_btn2, ResManager. main_btn2) self. btnItem2: setPosition (winSize. width/2, winSize. height/2) self. btnItem2: setTag (2) self. btnItem2: registerScriptTapHandler (menuCallback) self. btnItem3 = cc. menuItemImage: create (ResManager. main_btn3, ResManager. main_btn3) self. btnItem3: setPosition (winSize. width/2, winSize. height/3*2) self. btnItem3: setTag (3) self. btnItem3: registerScriptTapHandler (menuCallback) -- create menu self. menu = cc. menu: create (self. btnItem1, self. btnItem2, self. btnItem3) self. menu: setPosition (0, 0) self: addChild (self. menu) endreturn MainLayerV
We can see that a background image and three buttons are added to the main interface. We use resource manager ResManager to manage materials in the game. The ResManager file is simple:
-- Resource Manager ResManager ={} -- Main Interface ResManager. main_bg = bg_big.pngResManager.main_btn1 = cell.png ResManager. main_btn2 = cell2.pngResManager. main_btn3 = cell3.png
The advantage of this is that if the image name or path is changed, you only need to change it once.
We can see that we have registered the response function menuCallback for the three buttons. In this function, it is the "communication" between V and C in MVC. We have defined a Custom Event EVENT_CLICK_MENU_MAIN, and added an additional parameter _ usedata for this event. This parameter stores the tags of the three buttons. Then, send the event to the listener. Here we should understand that we have registered the EVENT_CLICK_MENU_MAIN listener in the corresponding Controller, but when this event is sent, we will respond. Based on the parameter _ usedata carried by the event, we know which button the player clicks in the View. The advantage of this is that each interface has only one message, we only need to determine the specific event based on the additional parameters carried by the message, thus reducing the number of messages, which helps the efficiency of the game. In addition, we will make some optimizations when responding to this message. Let's take a look at the response functions of the MainLayerController class:
Function MainLayerC: addBtnEventListener () -- button event processing local function eventBtnListener (event) local eventNum = event. _ usedata local switch = {[1] = function () print (Btn one) end, [2] = function () print (Btn two) end, [3] = function () print (Btn three) end} switch [eventNum] () end -- register event processing self. _ eventBtnListener = cc. eventListenerCustom: create (EVENT_CLICK_MENU_MAIN, eventBtnListener) eventDispatcher: addEventListenerWithSceneGraphPriority (self. _ eventBtnListener, self. mainLayer) end
We can see that we do not need to judge the passed parameters, but define a function array to directly call the corresponding message response according to the subscript. Then, the game content will be changed through various managers, similar to that of MainLayerController and MainLayerView.