Cocos2d-x 3.6 lua, cocos2d-xlua
A few simple words:
Recently used the lua Script Development in the game project, the project uses the MVC Framework. From cocos2d-x 3.6 create lua demo, a simple share of ideas and some development skills.
Let's talk about MVC, that is, Model View Controller.
Model: generally responsible for data processing.
View: displays the interface.
Controller: generally responsible for front-end logic processing
For example, for a mobile game, the display and layout of the UI are the responsibility of the View. If you click a button, the Controller will handle operations such as gesture sliding; the data resources required in the game are handed over to the Model.
Game instances:
The directory structure of the project I created:
When explaining the code, let's first introduce what this demo is for. That's right. In fact, it is an introduction to the "insecticide" game, such:
Gameplay:Initialize 5 pieces of blood, and run them randomly to the ant or spider who crawls the holes until the accumulation enters 5 bugs, and the game ends.
How can we achieve this game? See the design sequence diagram and class diagram:
Sequence diagram:
Class diagram:
Code:
After the creation, the main. lua you first see is started to MyApp. lua.
require("app.MyApp"):create():run()
View the MyApp. lua file:
1. require ("app. MyApp ")
The MyApp. lua code executed here is:
Local MyApp = class ("MyApp", cc. load ("mvc "). appBase) -- inherits cc. mvc. appBasefunction MyApp: onCreate () math. randomseed (OS. time () endreturn MyApp
2. require ("app. MyApp"). create ()
After MyApp. create () is executed, the Code executed is:
function MyApp:ctor() MyApp.super.ctor(self)end
Why will MyApp: ctor () be executed after create ()? See the function class (classname, super) method under function. lua:
cls.new = function(...) local instance if cls.__create then instance = cls.__create(...) else instance = {} end setmetatableindex(instance, cls) instance.class = cls instance:ctor(...) return instance end cls.create = function(_, ...) return cls.new(...) end
We can see that in the implementation method of the class, a new () method is declared for each created class. The method calls the ctor () constructor method (the ctor is just a name, so not some people think that after the create operation, of course, the constructor will be called. lua has no class, but we have imitated the class)
3. require ("app. MyApp"). create (): run ()
function AppBase:run(initSceneName) initSceneName = initSceneName or self.configs_.defaultSceneName self:enterScene(initSceneName)end
In fact, self. configs _. defaultSceneName = "MainScene" is to enter the initial interface.
For the MyApp. lua file, if I change it to the following format, do you understand the above:
Local AppBase = class ("AppBase") -- initialize and call function AppBase: ctor (configs) self. configs _ = {viewsRoot = "app. views ", modelsRoot =" app. models ", defaultSceneName =" MainScene ",} for k, v in pairs (configs or {}) do self. configs _ [k] = v end if type (self. configs _. viewsRoot )~ = "Table" then self. configs _. viewsRoot = {self. configs _. viewsRoot} end if type (self. configs _. modelsRoot )~ = "Table" then self. configs _. modelsRoot = {self. configs _. modelsRoot} end if DEBUG> 1 then dump (self. configs _, "AppBase configs") end if CC_SHOW_FPS then cc. director: getInstance (): setDisplayStats (true) end -- event self: onCreate () end -- run scenario function AppBase: run (initSceneName) initSceneName = initSceneName or self. configs _. defaultSceneName self: enterScene (initSceneName) end -- select the scenario function AppBase: enterScene (sceneName, transition, time, more) local view = self: createView (sceneName) view: showWithScene (transition, time, more) return viewend -- select the UI, that is, viewfunction AppBase: createView (name) for _, root in ipairs (self. configs _. viewsRoot) do local packageName = string. format ("% s. % s ", root, name) local status, view = xpcall (function () return require (packageName) end, function (msg) if not string. find (msg, string. format ("'% s' not found:", packageName) then print ("load view error:", msg) end) local t = type (view) if status and (t = "table" or t = "userdata") then return view: create (self, name) end error (string. format ("AppBase: createView ()-not found view \" % s \ "in search paths \" % s \ "", name, table. concat (self. configs _. viewsRoot, ","), 0) end -- call function AppBase: onCreate () endreturn AppBase when creating
MainScene. lua
Local MainScene = class ("MainScene", cc. load ("mvc "). viewBase) function MainScene: onCreate () -- add background image display. newSprite ("MainSceneBg.jpg"): move (display. center): addTo (self) -- add play button local playButton = cc. menuItemImage: create ("PlayButton.png", "PlayButton.png"): onClicked (function () self: getApp (): enterScene ("PlayScene") -- enter the game Interface end) cc. menu: create (playButton): move (display. cx, display. cy-200): addTo (self) endreturn MainScene
PlayScene. lua
Local PlayScene = class ("PlayScene", cc. load ("mvc "). viewBase) local GameView = import (". gameView ") function PlayScene: onCreate () -- create game view and add it to stage self. gameView _ = GameView: create (): addEventListener (GameView. events. PLAYER_DEAD_EVENT, handler (self, self. onPlayerDead): start (): addTo (self) end -- call the game end (note that GameView bind is bound) function PlayScene: onPlayerDead (event) -- add game over text local text = string. format ("You killed % d bugs", self. gameView _: getKills () cc. label: createWithSystemFont (text, "Arial", 96): align (display. CENTER, display. center): addTo (self) -- add exit button local exitButton = cc. menuItemImage: create ("ExitButton.png", "ExitButton.png"): onClicked (function () self: getApp (): enterScene ("MainScene") end) cc. menu: create (exitButton): move (display. cx, display. cy-200): addTo (self) endreturn PlayScene
GameView. lua
The code is long, so we will focus on several sections of code:
Frame Rate refresh
Function GameView: step (dt) if self. lives _ <= 0 then return end self. addBugInterval _ = self. addBugInterval _-dt if self. addBugInterval _ <= 0 then self. addBugInterval _ = math. random (GameView. ADD_BUG_INTERVAL_MIN, GameView. ADD_BUG_INTERVAL_MAX) self: addBug () -- randomly generate the bug end for _, bug in pairs (self. bugs _) do bug: step (dt) -- worm crawling if bug: getModel (): getDist () <= 0 then self: bugEnterHole (bug) -- enter the cave end return selfend
Load bugs
Function GameView: addBug () local bugType = BugBase. BUG_TYPE_ANT -- randomly selects ant and spider if math. random (1, 2) % 2 = 0 then bugType = BugBase. BUG_TYPE_SPIDER end -- create the ant and spider models. local bugModel if bugType = BugBase. BUG_TYPE_ANT then bugModel = BugAnt: create () else bugModel = BugSpider: create () end -- load insect view select the corresponding model local bug = BugSprite: create (GameView. IMAGE_FILENAMES [bugType], bugModel): start (GameView. HOLE_POSITION): addTo (self. bugsNode _, GameView. ZORDER_BUG) self. bugs _ [bug] = bug return selfend
Bind event
-- bind the "event" component cc.bind(self, "event")
After the game ends, you can directly jump to the PlayScene scenario. I will not introduce much about Code such as killing insects and deducting blood. Refer to the class diagram below and you will understand it. I will not list it one by one.