mvc模式
Model(模型):一般负责数据的处理
View(视图):一般负责界面的显示
Controller(控制器):一般负责前端的逻辑处理
实例
捉虫游戏,背景介绍:两类虫(蚂蚁和蜘蛛)进洞超过3个,玩家就失败。
在实际开发中,我遇到的头疼麻烦的事,不知道M、V、C他们之间的调用是怎样的?
M模型
BugAnt和BugSpider都继承BugBase.
V视图
1.视图BugSprite依赖模型BugBase
function GameView:addBug() local bugType = BugBase.BUG_TYPE_ANT if math.random(1,2) % 2 == 0 then bugType = BugBase.BUG_TYPE_SPIDER end local bugModel if bugType == BugBase.BUG_TYPE_ANT then bugModel = BugAnt:create() else bugModel = BugSpider:create() end local bug = BugSprite:create(GameView.IMAGE_FILENAMES[bugType],bugModel) :start(GameView.HOLE_POSITION) :addTo(self.bugsNode_,GameView.ZORDER_BUG) self.bugs_[bug] = bug return self end
2.帧率刷动---虫子的生产和爬动,及进洞
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() -- 随机生成虫子 end for _,bug in pairs(self.bugs_) do bug:step(dt) -- 虫子爬动 if bug:getModel():getDist() <= 0 then self:bugEnterHole(bug) -- 进入洞穴 end end return self end function GameView:bugEnterHole(bug) self.bugs_[bug] = nil bug:fadeOut({time = 0.5,removeSelf = true}) :scaleTo({time = 0.5,scale = 0.3}) :rotateTo({time = 0.5,rotation = math.random(360,720)}) self.lives_ = self.lives_ - 1 self.livesLabel_:setString(self.lives_) audio.playSound("BugEnterHole.wav") if self.lives_ <= 0 then self:dispatchEvent({name = GameView.events.PLAYER_DEAD_EVENT}) end return self end
3.手击中虫子
function GameView:onTouch(event) if event.name ~= "began" then return end local x,y = event.x,event.y for _,bug in pairs(self.bugs_) do if bug:getModel():checkTouch(x,y) then self:bugDead(bug) end end end function GameView:bugDead(bug) local imageFilename = GameView.IMAGE_FILENAMES[bug:getModel():getType()] DeadBugSprite:create(imageFilename) :fadeOut({time = 2.0,delay = 0.5,removeSelf = true}) :move(bug:getPosition()) :rotate(bug:getRotation() + 120) :addTo(self.bugsNode_,GameView.ZORDER_DEAD_BUG) self.bugs_[bug] = nil bug:removeSelf() self.kills_ = self.kills_ + 1 audio.playSound("BugDead.wav") return self end