代码库有三个例子,第三个是
var Puzzle=function(options){ mission=0; if(options.imgPro)puzzleImgPro = options.imgPro; puzzle_difficultyX = puzzleImgPro[0].w; puzzle_difficultyY = puzzleImgPro[0].h; puzzle_hover_tint = '#009900'; imgPath = ''; _stage =null ; _canvas =null; _img =null; _pieces =null; puzzleWidth=0; puzzleHeight=0; pieceWidth=0; pieceHeight=0; mainWidth=$(window).get(0).innerWidth; mainHeight=$(window).get(0).innerHeight; mainScale=mainWidth/750; currentPiece=null; currentDropPiece=null; _mouse=null; SUPPORTS_TOUCH = null; START_EV = null; that = this; stauts="new"; imgPath = puzzleImgPro[0].path; if(options.puzzle_hover_tint)puzzle_hover_tint = options.puzzle_hover_tint; timer=0; tindex=0; tstrme=""; } Puzzle.prototype = { init:function(){ _img = new Image(); _img.addEventListener('load',this.onImage,false); _img.src =imgPath; $("#canvas").css({ "position":"absolute" }); $("#game .gameOn").css({ "position":"absolute" }).hide(); $("#game .gameOff").css({ "position":"absolute" }).hide(); $("#game .bg").css({ "width":mainWidth, "height":mainScale*1334, "position":"absolute" }); $("#game .bg").attr({ "src":"img/start.jpg" }); $("#game .gameOn p").css({'font-size':45*mainScale, 'width':225*mainScale, 'margin-top':200*mainScale}); $("#game .shijian").css({'margin-left':300*mainScale}); $("#game .gameOff p").css({ 'margin-top':580*mainScale, 'width':mainWidth, 'font-size':58*mainScale}); $("#game").click(function(){ switch(stauts){ case "new": mission++; if(mission<=puzzleImgPro.length){ that.setCanvas(); that.gamestartcall(); } break; case "gameOver": mission++; if(mission<=puzzleImgPro.length){ $("#canvas").show(); that.gamestartcall(); }else{ alert("gameover"); } break; }; }); }, gamestartcall:function(){ stauts="gameStart"; timer=setInterval(that.timeread, 1000) var _str=mission; if(mission<10){ _str="0"+_str; } $("#game .guanka").text("关卡:"+_str); $("#game .shijian").text("00"+" : "+"00"); $("#game .gameOff").hide(); $("#game .gameOn").show(); that.initPuzzle(); $("#game .bg").attr({ "src":"img/bg.jpg" }); }, timeread:function(){ tindex++; //console.log(tindex); var time=tindex; var minute = 0; var second =0; if(time >=60){ minute = parseInt(time / 60); time = parseFloat(time % 60); } second = time; if(minute <10){ minute ='0'+minute; }else{ minute=minute+'' } if(second <10){ second ='0'+second; }else{ second=second+'' } //console.log(minute+" : "+second); tstrme=minute+" : "+second; $("#game .shijian").text(tstrme); }, onImage:function(e) { SUPPORTS_TOUCH = ("ontouchstart" in window) || window.DocumentTouch && document instanceof DocumentTouch; START_EV = (SUPPORTS_TOUCH) ? "touchstart" : "mousedown"; MOVE_EV = (SUPPORTS_TOUCH) ? "touchmove" : "mousemove"; END_EV = (SUPPORTS_TOUCH) ? "touchend" : "mouseup"; pieceWidth = Math.floor(_img.width / puzzle_difficultyX); pieceHeight = Math.floor(_img.height / puzzle_difficultyY); puzzleWidth = pieceWidth * puzzle_difficultyX; puzzleHeight = pieceHeight * puzzle_difficultyY; /*that.setCanvas(); that.initPuzzle();*/ }, setCanvas:function(){ _canvas = document.getElementById('canvas'); _stage = _canvas.getContext('2d'); _canvas.width = puzzleWidth; _canvas.height =puzzleHeight; _canvas.style.border = "1px solid black"; $("#canvas").css({ 'marginLeft':mainWidth/2-350, 'marginTop':(mainHeight-362*mainScale)/2-puzzleHeight/2+362*mainScale }) }, initPuzzle:function(){ _pieces = []; _mouse = {x:0,y:0}; currentPiece = null; currentDropPiece = null; _stage.drawImage(_img, 0, 0, puzzleWidth, puzzleHeight); that.createTitle("Click to Start Puzzle"); that.buildPieces(); }, createTitle:function(msg){ _stage.fillStyle = "#000000"; _stage.globalAlpha = .4; //_stage.fillRect(100,puzzleHeight - 40,puzzleWidth - 200,40); _stage.fillStyle = "#FFFFFF"; _stage.globalAlpha = 1; //_stage.textAlign = "center"; //_stage.textBaseline = "middle"; //_stage.font = "20px Arial"; //_stage.fillText(msg,puzzleWidth / 2,puzzleHeight - 20); }, buildPieces:function(){ var i; var piece; var xPos = 0; var yPos = 0; for(i = 0;i < puzzle_difficultyX * puzzle_difficultyY;i++){ piece = {}; piece.sx = xPos; piece.sy = yPos; _pieces.push(piece); xPos += pieceWidth; if(xPos >= puzzleWidth){ xPos = 0; yPos += pieceHeight; } } that.shufflePuzzle(); }, shufflePuzzle:function(){ _pieces = that.shuffleArray(_pieces); _stage.clearRect(0,0,puzzleWidth,puzzleHeight); var i; var piece; var xPos = 0; var yPos = 0; for(i = 0;i < _pieces.length;i++){ piece = _pieces[i]; piece.xPos = xPos; piece.yPos = yPos; _stage.drawImage(_img, piece.sx, piece.sy, pieceWidth, pieceHeight, xPos, yPos, pieceWidth, pieceHeight); _stage.strokeRect(xPos, yPos, pieceWidth,pieceHeight); xPos += pieceWidth; if(xPos >= puzzleWidth){ xPos = 0; yPos += pieceHeight; } } _canvas.addEventListener(START_EV,that.onPuzzleClick); // document.onmousedown = that.onPuzzleClick; }, onPuzzleClick:function (e){ var point = that.getMousePoint(e); var layerX = point.x; var layerY = point.y; if( layerX || layerX == 0){ _mouse.x = layerX - _canvas.offsetLeft; _mouse.y = layerY - _canvas.offsetTop; } currentPiece = that.checkPieceClicked(); if(currentPiece != null){ _stage.clearRect(currentPiece.xPos,currentPiece.yPos,pieceWidth,pieceHeight); _stage.save(); _stage.globalAlpha = .9; _stage.drawImage(_img, currentPiece.sx, currentPiece.sy, pieceWidth, pieceHeight, _mouse.x - (pieceWidth / 2), _mouse.y - (pieceHeight / 2), pieceWidth, pieceHeight); _stage.restore(); _canvas.addEventListener(MOVE_EV,that.updatePuzzle); _canvas.addEventListener(END_EV,that.pieceDropped); } }, checkPieceClicked:function(){ var i; var piece; for(i = 0;i < _pieces.length;i++){ piece = _pieces[i]; if(_mouse.x < piece.xPos || _mouse.x > (piece.xPos + pieceWidth) || _mouse.y < piece.yPos || _mouse.y > (piece.yPos + pieceHeight)){ } else{ return piece; } } return null; }, getMousePoint:function(e) { var x,y if(SUPPORTS_TOUCH) { if(e.touches.length>1)return var evt = e.touches[0]; x = evt.clientX; y = evt.clientY; }else { x = e.layerX; y = e.layerY; } var point = {}; point.x = x; point.y = y; return point; }, updatePuzzle:function(e){ currentDropPiece = null; var point = that.getMousePoint(e); var layerX = point.x; var layerY = point.y; if(layerX || layerX == 0){ _mouse.x = layerX - _canvas.offsetLeft; _mouse.y = layerY - _canvas.offsetTop; } _stage.clearRect(0,0,puzzleWidth,puzzleHeight); var i; var piece; for(i = 0;i < _pieces.length;i++){ piece = _pieces[i]; if(piece == currentPiece){ continue; } _stage.drawImage(_img, piece.sx, piece.sy, pieceWidth, pieceHeight, piece.xPos, piece.yPos, pieceWidth, pieceHeight); _stage.strokeRect(piece.xPos, piece.yPos, pieceWidth,pieceHeight); if(currentDropPiece == null){ if(_mouse.x < piece.xPos || _mouse.x > (piece.xPos + pieceWidth) || _mouse.y < piece.yPos || _mouse.y > (piece.yPos + pieceHeight)){ } else{ currentDropPiece = piece; _stage.save(); _stage.globalAlpha = .4; _stage.fillStyle = puzzle_hover_tint; _stage.fillRect(currentDropPiece.xPos,currentDropPiece.yPos,pieceWidth, pieceHeight); _stage.restore(); } } } _stage.save(); _stage.globalAlpha = .6; _stage.drawImage(_img, currentPiece.sx, currentPiece.sy, pieceWidth, pieceHeight, _mouse.x - (pieceWidth / 2), _mouse.y - (pieceHeight / 2), pieceWidth, pieceHeight); _stage.restore(); _stage.strokeRect( _mouse.x - (pieceWidth / 2), _mouse.y - (pieceHeight / 2), pieceWidth,pieceHeight); }, pieceDropped:function(e){ _canvas.removeEventListener(MOVE_EV,that.updatePuzzle); _canvas.removeEventListener(END_EV,that.pieceDropped); if(currentDropPiece != null){ var tmp = {xPos:currentPiece.xPos,yPos:currentPiece.yPos}; currentPiece.xPos = currentDropPiece.xPos; currentPiece.yPos = currentDropPiece.yPos; currentDropPiece.xPos = tmp.xPos; currentDropPiece.yPos = tmp.yPos; } that.resetPuzzleAndCheckWin(); }, resetPuzzleAndCheckWin:function(){ _stage.clearRect(0,0,puzzleWidth,puzzleHeight); var gameWin = true; var i; var piece; for(i = 0;i < _pieces.length;i++){ piece = _pieces[i]; _stage.drawImage(_img, piece.sx, piece.sy, pieceWidth, pieceHeight, piece.xPos, piece.yPos, pieceWidth, pieceHeight); _stage.strokeRect(piece.xPos, piece.yPos, pieceWidth,pieceHeight); if(piece.xPos != piece.sx || piece.yPos != piece.sy){ gameWin = false; } } if(gameWin){ setTimeout(that.gameOver,300); } }, gameOver:function(){ _canvas.removeEventListener(START_EV,that.onPuzzleClick); _canvas.removeEventListener(MOVE_EV,that.updatePuzzle); _canvas.removeEventListener(END_EV,that.pieceDropped); //alert('游戏结束') $("#canvas").hide(); $("#game .bg").attr({ "src":"img/bg2.jpg" }); $("#game .gameOn").hide(); $("#game .gameOff").show(); $("#game .yongshi").text(tstrme); stauts="gameOver"; tindex=0; window.clearInterval(timer); }, shuffleArray:function(o){ for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); return o; } }
其他两个都用createjs,除了一些倒计时啊画面的入场出场以外,movieclip和算法都在这里:
(function($) { $.factory_puzzle = function() { var $factory = {}; $factory.createPuzzle = function(obj) { var _pdtObj = {}; var data = { images: [obj.img.src], frames: { obj.img.width, height: obj.img.height, regX: 0, regY: 0 }, animations: {} }; data.images.crossOrigin = 'Anonymous'; var spriteSheet = new createjs.SpriteSheet(data); var shape = new createjs.Shape(); shape.graphics.beginFill("#fff").drawRect(0, 0, obj.img.width, obj.img.height); sprite = new createjs.Sprite(spriteSheet, "puzzle"); var puzzleCon = new createjs.Container(); puzzleCon.addChild(sprite); puzzleCon.addChild(shape); //创建具体拼图 var imgPieces = [], selectBool = true, //单个移动开关 moveSwitch = true, //整体事件大开关 bitmap = new createjs.Bitmap(obj.img.src), range = [], imgId = 0, pWidth = obj.img.width, pHeight = obj.img.height, row = obj.widthCut, col = obj.heightCut, width = pWidth / row, height = pHeight / col; for (var o = 0; o < row; o++) { //竖向切 for (var i = 0; i < col; i++) { //横向切 var clone = bitmap.clone(); var rect = new createjs.Rectangle(width * i, height * o, width, height); clone.alpha = 0; clone.sourceRect = rect; range.push({ x: (width) * i, y: (height) * o }); imgPieces.push({ obj: clone, id: imgId++ }); } } //重新排列x,y数据 imgPieces.sort(function() { return 0.5 - Math.random(); }); for (var j = 0; j < range.length; j++) { imgPieces[j].x = range[j].x; imgPieces[j].y = range[j].y; createjs.Tween.get(imgPieces[j].obj).to({ alpha: 1, x: range[j].x, y: range[j].y }, 400, createjs.Ease.bounceOut); } for (var k = 0; k < imgPieces.length; k++) { puzzleCon.addChild(imgPieces[k].obj); moveImages({ obj: imgPieces[k].obj, id: imgPieces[k].id }); //绑定移动图片事件 } //移动拼图 function moveImages(parameter) { if (!parameter.obj) return false; //按下事件 parameter.obj.addEventListener("mousedown", function(event) { if (!selectBool) return false; var _self = event.target; selectBool = false; //点击的时候开启移动模式 puzzleCon.setChildIndex(_self, puzzleCon.numChildren - 1); //点击的时候设置当前图片的层级为最高 //记录点击时候的起始位置 sx = event.stageX; //鼠标x点触发的位置 sy = event.stageY; //鼠标y点触发的位置 ox = _self.x; //记录原始位置 oy = _self.y; //记录原始位置 fzmx = event.stageX - event.target.x; fzmy = event.stageY - event.target.y; //绑定事件 event.target.addEventListener('pressup', pressUp); event.target.addEventListener('pressmove', pressMove, false); }); } //松开事件 function pressUp(event) { var _self = event.target, xSpace = Math.floor(pWidth / col / 2) - 10, ySpace = Math.floor(pHeight / row / 2) - 10; shadowUr(_self, false); //关闭阴影 //当位移大于键值的时候交换顺序 var exIndex = 0, flag = null; for (var i = 0; i < imgPieces.length; i++) { for (var j = 0; j < imgPieces.length; j++) { if (_self == imgPieces[j].obj) { exIndex = j; exX = imgPieces[j].x; exY = imgPieces[j].y; } } if (_self.id !== imgPieces[i].obj.id) { var objX = imgPieces[i].x, objY = imgPieces[i].y; if (Math.abs(objX - _self.x) < xSpace && Math.abs(objY - _self.y) < ySpace) { flag = { oldIndex: exIndex, newIndex: i, x: Math.abs(objX - exX), y: Math.abs(objY - exY) }; break; } else { flag = { oldIndex: exIndex, newIndex: exIndex, x: Math.abs(objX - exX), y: Math.abs(objY - exY) }; } } } //实行交换 exchange(flag); //松开之后解除绑定事件 event.target.removeEventListener('pressup', pressUp); event.target.removeEventListener('pressmove', pressMove); } //拖动图片 function pressMove(event) { if (!moveSwitch) return false; var _self = event.target; //移动的时候加上阴影 shadowUr(_self, true); //x轴方向 if (event.stageX - fzmx < 0) { _self.x = 0; } else if (event.stageX - fzmx + _self.getBounds().width > pWidth) { _self.x = pWidth - _self.getBounds().width; } else { _self.x = event.stageX - fzmx; } //y轴移动方向 if (event.stageY - fzmy < 0) { _self.y = 0; } else if (event.stageY - fzmy + _self.getBounds().height > pHeight) { _self.y = pHeight - _self.getBounds().height; } else { _self.y = event.stageY - fzmy; } } //交换顺序 function exchange(obj) { //这边阐述了变量和对象之间的区别,变量赋值之后不会随着赋值点而改变,但是对象会!!! var oldObj = imgPieces[obj.oldIndex]; var newObj = imgPieces[obj.newIndex]; var x = oldObj.x, y = oldObj.y, _x = newObj.x, _y = newObj.y; imgPieces.splice(obj.oldIndex, 1, newObj); imgPieces.splice(obj.newIndex, 1, oldObj); tween({ el: imgPieces[obj.oldIndex].obj, x: imgPieces[obj.newIndex].x, y: imgPieces[obj.newIndex].y }); tween({ el: imgPieces[obj.newIndex].obj, x: imgPieces[obj.oldIndex].x, y: imgPieces[obj.oldIndex].y }); imgPieces[obj.oldIndex].x = x; imgPieces[obj.oldIndex].y = y; imgPieces[obj.newIndex].x = _x; imgPieces[obj.newIndex].y = _y; //每次调换之后检测是否拼正确了,然后判断是否去下一页 var pass = checkPass(); if (pass) { complete(); } } function tween(parameter) { if (!parameter.el) return false; var _self = parameter.el, _selfX = parameter.x || 0, _selfY = parameter.y || 0; createjs.Tween.get(_self).to({ x: _selfX, y: _selfY }, 300).call(function() { selectBool = true; //关闭拖动开关 }); } function shadowUr(el, bool) { if (bool) { el.shadow = new createjs.Shadow("rgba(0, 0, 0, .5)", 0, 0, 20); } else { el.shadow = null; } } function checkPass() { var pass = true; for (var i = 0; i < imgPieces.length; i++) { if (i !== imgPieces[i].id) { pass = false; break; } else { pass = true; } } return pass; } function complete() { obj.callback(); } _pdtObj.mc = puzzleCon; _pdtObj.moveImages = moveImages; _pdtObj.pressUp = pressUp; _pdtObj.pressMove = pressMove; _pdtObj.exchange = exchange; _pdtObj.tween = tween; _pdtObj.shadowUr = shadowUr; _pdtObj.checkPass = checkPass; _pdtObj.complete = complete; return _pdtObj; }; return $factory; }; })(jQuery);
data:
{x:(759-320)/2, y:(1334-348)/4, ox:0, order:"createPuzzle", img:{src:"images/puzzle.jpg",320,height:348},widthCut:3,heightCut:3,callback:function(){alert(1)}}
纯粹的movieclip(mc)通常只会用到最基础的EASELJS
下面看看整个游戏的逻辑:
/images /style /js /data
data.js common.js controller.js main.js pageManager.js index.html
common.js 加载进度条、素材、创建舞台、监听窗口resize。
controller.js 封装了各种出场入场的方式,比如easeIn、rotate、scale等等,作createjs.Tween动画,
也是creagejs的精华TWEENJS
处理timer,响应viewport,集成createjs各种组件的构造,比如Sprite,Shape,ShapeFill、Bitmap,Container,DOMElement
main.js 核心的部分,游戏的算法,内部逻辑。
pageManager 根据每个画面的生命周期处理跳转路由。
一开始就需要配置好data.js中的数据,否则各种load失败报错都是很难懂的(比如getContext失败,type错误)
1 Data=(function(){ 2 var $data={}; 3 //素材根路径 4 $data.file="images/"; 5 //拼图宽度配置 6 $data.puzzle=[{686,height:746,thuTime:5,gameTime:30,base:0.5}]; 7 //页面所用到的素材 8 $data.loading=[{src:"loading_img.png",id:"loading"}]; 9 $data.material=[ 10 {src:"logo.png",id:"logo"}, 11 {src:"puzzle01.jpg",id:"puzzle01"},{src:"puzzle02.jpg",id:"puzzle02"},{src:"puzzle03.jpg",id:"puzzle03"},{src:"puzzle04.jpg",id:"puzzle04"}, 12 {src:"puzzle/puzzle01.jpg",id:"Bpuzzle01"},{src:"puzzle/puzzle02.jpg",id:"Bpuzzle02"},{src:"puzzle/puzzle03.jpg",id:"Bpuzzle03"},{src:"puzzle/puzzle04.jpg",id:"Bpuzzle04"}, 13 {src:"bg_puzzle.png",id:"bg_puzzle"},{src:"bg_yellow.jpg",id:"bg_yellow"}, 14 {src:"bottom_puzzle.png",id:"bottom_puzzle"}, 15 {src:"static.png",id:"static"}, 16 {src:"button.png",id:"button"}, 17 {src:"popup/rulesText.png",id:"rulesText"},{src:"popup/arrow.png",id:"arrow"},{src:"popup/share_text.png",id:"share_text"}, 18 {src:"bg.mp3",id:"bgSound"} 19 ]; 20 //初始化素材数据 21 $data.static={ 22 id:"static", 23 point: 24 [{x:0,y:0,oY:-100,delayIn:0}, 25 {x:73,y:228,oY:-100,delayIn:300,easeIn:createjs.Ease.bounceOut}, 26 {x:50,y:23,oY:-100,delayIn:0,easeIn:createjs.Ease.bounceOut}, 27 {x:677,y:30,oY:-100,delayIn:100}, 28 {x:677,y:30,oY:0,delayIn:0}, 29 {x:240,y:195,oY:0,delayIn:500}, 30 {x:50,y:194,oY:-100,delayIn:0}, 31 {x:319,y:162,oY:-100,delayIn:500}, 32 {x:276,y:64,oY:0,delayIn:0}, 33 {x:51,y:118,oY:0,delayIn:0}, 34 {x:154,y:220,oY:0,delayIn:0}, 35 {x:191,y:162,oY:0,delayIn:0}, 36 {x:191,y:162,oY:0,delayIn:0}], 37 frames:[ 38 [0,277,750,263],[0,0,595,274],[626,0,125,59],[626,82,45,45],[690,82,45,45],[0,560,271,38],[0,608,502,37],[310,560,113,37],[443,560,128,30],[0,669,598,57],[0,746,373,357],[443,746,304,67],[443,826,304,67] 39 ], 40 animations:{bg_entrance:0,slogan:1,logo:2,openMusic:3,closeMusic:4,text_choseTit:5,text_countdown:6,text_count:7,text_instruc:8,text_introd:9,img_instruc:10,text_success:11,text_fail:12} 41 }; 42 $data.button={ 43 id:"button", 44 point: 45 [{x:175,y:575,oX:-100,delayIn:500}, 46 {x:175,y:683,oX:850,delayIn:600}, 47 {x:175,y:1050,oY:1334+100,delayIn:1500}, 48 {x:182,y:616,oY:0,delayIn:0}, 49 {x:144,y:356,oY:0,delayIn:0}, 50 {x:144,y:463,oY:0,delayIn:0}, 51 {x:255,y:62,oY:-100,delayIn:500}], 52 frames:[ 53 [0,0,400,85],[0,95,400,95],[0,190,400,85],[40,552,320,85],[0,285,400,85],[0,380,400,85],[80,475,240,67] 54 ], 55 animations:{startGame:0,viewPrizes:1,nextGame:2,beginGame:3,btnInvite:4,btnView:5,backGame:6} 56 }; 57 return $data; 58 })();
比如上面$data.material = [ ...{...}...,{src:"static.png",id:"static"},...]这个数据是在
$sheet.init 方法里面调用Loader.getResult(option.data.id)的时候要读取的,
说到这个Loader在本例中等于:new createjs.LoadQueue(false);
属于 PRELOADJS 的功能
PreloadJS是一个用来管理和协调相关资源加载的类库,它可以方便的帮助你预先加载相关资源。
LoadQueue类介绍
- 预加载音频文件
//初始化插件
preload.installPlugin(createjs.Sound);
- 设置加载路径
preload = new createjs.LoadQueue(true, "../_assets/art/");
- 获取预加载资源
preload.getResult(‘id’);
installPlugin, getResult这些都是极常用的方法,进度条可以通过fileload
和complete
来实现。
背景音乐mp3的控制就要用到 SOUNDJS
一个音频播放引擎,能够根据浏览器性能选择音频播放方式。将音频文件作为模块,可随时加载和卸载。
继续回到使用controller加载素材产出sheet
this.movieClip = $common.Control.create("sheet",
{ framerate: 30, images: [Loader.getResult(option.data.id)],
frames: option.data.frames, animations: option.data.animations });
此处根据material数组的长度进行遍历,想要加载什么素材只要增加数组元素,
此处的option.data就是$data.material数组第index个元素static
create方法会走到createjs框架内部:
972 b._parseData = function(a) { 973 var b, c, d, e; 974 if (null != a) { 975 if (this.framerate = a.framerate || 0, 976 a.images && (c = a.images.length) > 0) 977 for (e = this._images = [], 978 b = 0; c > b; b++) { 979 var f = a.images[b]; 981 if ("string" == typeof f) { 981 var g = f; 982 f = document.createElement("img"), 983 f.src = g 984 } 985 e.push(f),
如果找不到id为static的sprite png图片,a.images数组的第0个元素会显示为null,否则会是img
而那些point记录的都是每个元素在画面中的位置,
x是横坐标,y是纵坐标,oY是做动画之前的位置,delayIn是延迟进场时间。
入口:
$(function(){$common = new $.createNew(); $common.methods.init();});
在init中首先会加载进度条,将它放入舞台后下一步就是$common.methods.loadMain();
LoadMain()会执行$common.methods.loadFile({... 首先用controller加载背景图片。
进度条是靠读取Data(dev数据或者后台的真实数据)来显示进度,
//进度加载完成后利用controller中的$common.Control.ani.hideAlpha方法清除loading还stage一个清白
myStage.removeChild(myLoading.movieClip);
//初始化完成,进入pageManager
$common.Page.methods.init(myStage);
//初始化弹层
$common.PopupClass=new $.popup({stage:myStage});
在pageManager中,就可以为所欲为了。
$.pageManager = function() { var $page = {}; var curPage, tarPage; var pageArr = [
在pageArr里定义的每一个画面的生命周期函数。
上面都是一些准备工作,写在init属性中(数组中一个元素对象的一个属性,它被定义成一个函数)中,加载这些addChild, this.childArr.push()
this.childArr.push(new $.pageManager().sheet({ data: Data.button, frame: "startGame" }));
进入画面后要做什么事,就应该写在checkIn里面,此处会获取到 this.childObj.startGame.movieClip 对象
this.childObj.startGame.movieClip.addEventListener("click", function(evt) { //点击”开始挑战“按钮 $common.dev.getNum(function(data){ //判断还有几次机会 if(data.num>=1) JumpToLocal(1); }); evt.remove(); });
这个startGame就是上面init的frame名称,直接获取它的movieClip绑定事件。
remove
Causes the active listener to be removed via removeEventListener();
myBtn.addEventListener("click", function(evt) {
// do stuff...
evt.remove(); // removes this listener.
});
及时删除已经响应的事件。
本例中有一个接口,用来模拟服务器传来的剩余游戏机会:
$createNew.dev={ //获取玩游戏次数 getNum:function(callback){ try{getNum(callback);}catch(e){callback({num:Math.ceil(Math.random()*2)});}; } };
如果后端重写getNum方法,就会执行它传来的callback,否则就走catch中的假数据。
记得在checkOut中清除本画面,否则进入了下一个画面也看不出什么区别。。
checkOut有一个回调函数_intoBack,每次都在最后执行它,或者判断if(_intoBack)_intoBack()
//此处问了大大,说这个_intoBack没啥用,从前是为了在调用checkOut的时候让它执行自己,现在他写新框架中已被废弃。
这些生命周期函数也纯粹是通过数组的遍历来实现的,完全取决于pageArr的结构:
$page.methods = { init: function(_stage) { //生成页面容器 if (pageArr.length > 0) { for (var i = 0; i < pageArr.length; i++) { pageArr[i].container = $common.Control.create("container"); pageArr[i].childArr = []; pageArr[i].childObj = {}; pageArr[i].container.visible = false; pageArr[i].init(); AddChildPage(pageArr[i]); _stage.addChild(pageArr[i].container); } }
是pageMaker的精髓所在,所以