game.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. $(function(){
  2. window.Util = {};
  3. ;~function(Util){
  4. ;~function(){
  5. var lastTime = 0;
  6. var prefixes = 'webkit moz ms o'.split(' '); //各浏览器前缀
  7. var requestAnimationFrame = window.requestAnimationFrame;
  8. var cancelAnimationFrame = window.cancelAnimationFrame;
  9. var prefix;
  10. //通过遍历各浏览器前缀,来得到requestAnimationFrame和cancelAnimationFrame在当前浏览器的实现形式
  11. for( var i = 0; i < prefixes.length; i++ ) {
  12. if ( requestAnimationFrame && cancelAnimationFrame ) {
  13. break;
  14. }
  15. prefix = prefixes[i];
  16. requestAnimationFrame = requestAnimationFrame || window[ prefix + 'RequestAnimationFrame' ];
  17. cancelAnimationFrame = cancelAnimationFrame || window[ prefix + 'CancelAnimationFrame' ] || window[ prefix + 'CancelRequestAnimationFrame' ];
  18. }
  19. //如果当前浏览器不支持requestAnimationFrame和cancelAnimationFrame,则会退到setTimeout
  20. if ( !requestAnimationFrame || !cancelAnimationFrame ) {
  21. requestAnimationFrame = function( callback, element ) {
  22. var currTime = new Date().getTime();
  23. //为了使setTimteout的尽可能的接近每秒60帧的效果
  24. // var timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  25. var timeToCall = 30;
  26. var id = window.setTimeout( function() {
  27. callback( currTime + timeToCall );
  28. }, timeToCall );
  29. lastTime = currTime + timeToCall;
  30. return id;
  31. };
  32. cancelAnimationFrame = function( id ) {
  33. window.clearTimeout( id );
  34. };
  35. }
  36. //得到兼容各浏览器的API
  37. window.requestAnimationFrame = requestAnimationFrame;
  38. window.cancelAnimationFrame = cancelAnimationFrame;
  39. }();
  40. var intervals = [];
  41. var intervalIds = 0;
  42. Util.setIntervalWithTimeout = function(callback, interval, needImmediately) {
  43. var id = intervalIds++;
  44. var loop = function() {
  45. intervals[id] = setTimeout(loop, interval);
  46. callback();
  47. }
  48. if (needImmediately) {
  49. loop();
  50. } else {
  51. intervals[id] = setTimeout(loop, interval);
  52. }
  53. return id;
  54. }
  55. Util.clearIntervalWithTimeout = function(intervalId) {
  56. clearTimeout(intervals[intervalId]);
  57. }
  58. var fr = 1000/30;
  59. Util.animation = function($object, duration, options){
  60. var step = {}
  61. ,start = {}
  62. ,end = {}
  63. var totalStep = duration*60;
  64. for(var i in options){
  65. if(typeof options[i] == "number"){
  66. step[i] = 0;
  67. end[i] = options[i];
  68. start[i] = parseInt($object.css(i));
  69. (function(key){
  70. var interval = Util.setIntervalWithTimeout(function(){
  71. step[key]++;
  72. $object.css(key, ((step[key]/totalStep)*(end[key]-start[key])+start[key])+"px");
  73. if(step[key] == totalStep){
  74. $object.css(key, (end[key])+"px");
  75. Util.clearIntervalWithTimeout(interval);
  76. if(typeof options["onComplete"] == "function"){
  77. options["onComplete"]();
  78. }
  79. }
  80. }, 1000/30, false);
  81. })(i);
  82. }
  83. }
  84. }
  85. var hasTouch = (/mobile|Mobile/g).test(navigator.userAgent) && (("createTouch" in document) || ("ontouchstart" in window)),
  86. startEvent = hasTouch ? "touchstart" : "mousedown",
  87. moveEvent = hasTouch ? "touchmove" : "mousemove",
  88. endEvent = hasTouch ? "touchend touchcancel" : "mouseup";
  89. Util.eventTouchStart = startEvent;
  90. Util.eventTouchMove = moveEvent;
  91. Util.eventTouchEnd = endEvent;
  92. Util.preloadImg = (function(){
  93. var imgList = [];
  94. return function(imgs){
  95. for(var i = 0; i < imgs.length; i++){
  96. var img = new Image();
  97. img.src = imgs[i];
  98. imgList.push(img);
  99. }
  100. }
  101. })();
  102. Util.randomN = function(n) {
  103. return Math.floor(Math.random()*n);
  104. }
  105. Util.rotateOut = function($target){
  106. $target.addClass("rotateout");
  107. setTimeout(function(){
  108. $target.hide();
  109. $target.removeClass("rotateout");
  110. }, 1000);
  111. }
  112. Util.rotateIn = function($target, delay){
  113. $target.addClass("rotatein");
  114. $target.show();
  115. setTimeout(function(){
  116. $target.addClass("rotatein1");
  117. setTimeout(function(){
  118. $target.removeClass("rotatein");
  119. $target.removeClass("rotatein1");
  120. }, 1000);
  121. }, delay);
  122. }
  123. Util.isIphone = !!(navigator.userAgent.toLowerCase().indexOf("iphone") > -1);
  124. Util.isSafari = !!(navigator.userAgent.toLowerCase().indexOf("safari") > -1);
  125. Util.LSound = (function() {
  126. var LSound = {}
  127. if(!!Audio){
  128. var UNDEFINED="undefined";
  129. function base(d,b,a){var p=null,o=d.constructor.prototype,h={};if(d.constructor.name=="Object"){console.warn("When you use the extends. You must make a method like 'XX.prototype.xxx=function(){}'. but not 'XX.prototype={xxx:function(){}}'.");}d.__ll__parent__=d.__ll__parent__||[];d.__ll__parent__.push(b.prototype);for(p in o){h[p]=1;}for(p in b.prototype){if(!h[p]){o[p]=b.prototype[p];}}if(o.toString==Object.prototype.toString){o.toString=LObject.prototype.toString;}b.apply(d,a);}var LExtends=base;
  130. function LEvent(type){this.eventType=type;this._ll_preventDefault=false;}LEvent.prototype.preventDefault=function(){this._ll_preventDefault=true;};LEvent.INIT="init";LEvent.COMPLETE="complete";LEvent.ENTER_FRAME="enter_frame";LEvent.WINDOW_RESIZE="resize";LEvent.SOUND_COMPLETE="sound_complete";LEvent.END_CONTACT="endContact";LEvent.PRE_SOLVE="preSolve";LEvent.POST_SOLVE="postSolve";LEvent.BEGIN_CONTACT="beginContact";LEvent.addEventListener=function(n,t,f,b){if(b==null){b=false;}if(n.addEventListener){n.addEventListener(t,f,b);}else if(n.attachEvent){n["e"+t+f]=f;n[t+f]=function(){n["e"+t+f]();};n.attachEvent("on"+t,n[t+f]);}};LEvent.removeEventListener=function(n,t,f,b){if(b==null){b=false;}if(n.removeEventListener){n.removeEventListener(t,f,b);}else if(n.detachEvent){n["e"+t+f]=f;n[t+f]=function(){n["e"+t+f]();};n.detachEvent("on"+t,n[t+f]);}};
  131. var LObject=(function(){function LObject(){this.type="LObject";this.objectIndex=++LGlobal.objectIndex;this.objectindex=this.objectIndex;}LObject.prototype={callParent:function(f_n,args){if(!f_n||!args){return;}var s=this,init=false,r;if(typeof s.__ll__parent_call=="undefined"){init=true;s.__ll__parent_call=0;}else{s.__ll__parent_call++;}if(s.__ll__parent_call>=s.__ll__parent__.length){return false;}if(!s.__ll__parent__[s.__ll__parent_call][f_n]){r=s.callParent(f_n,args);}else{r=s.__ll__parent__[s.__ll__parent_call][f_n].apply(s,args);}if(init){delete s.__ll__parent_call;}return r;},toString:function(){return "[object "+this.type+"]";}};return LObject;})();
  132. var LAjax=(function(){function LAjax(){this.responseType=null;}LAjax.prototype={TEXT:"text",ARRAY_BUFFER:"arraybuffer",BLOB:"blob",get:function(url,data,oncomplete,onerror){this.getRequest("GET",url,data,oncomplete,onerror);},post:function(url,data,oncomplete,onerror){this.getRequest("POST",url,data,oncomplete,onerror);},getRequest:function(t,url,d,oncomplete,err){var s=this,k,data="",a="";s.err=err;var ajax=s.getHttp();if(!ajax){return;}if(d){for(k in d){data+=(a+k+"="+d[k]);a="&";}}if(t.toLowerCase()=="get"){url+=((url.indexOf('?')>=0?'&':'?')+data);data=null;}ajax.open(t,url,true);if(s.responseType){ajax.responseType=s.responseType;s.responseType=s.TEXT;}ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");ajax.onreadystatechange=function(){if(ajax.readyState==4){if(ajax.status>=200&&ajax.status<300||ajax.status===304){if(oncomplete){if(ajax.responseType==s.ARRAY_BUFFER||ajax.responseType==s.BLOB){oncomplete(ajax.response);}else if(ajax.responseText.length>0){oncomplete(ajax.responseText);}else{oncomplete(null);}}}else{if(err){err(ajax);}}}};ajax.send(data);},getHttp:function(){if(typeof XMLHttpRequest!=UNDEFINED){return new XMLHttpRequest();}try{return new ActiveXObject("Msxml2.XMLHTTP");}catch(e){try{return new ActiveXObject("Microsoft.XMLHTTP");}catch(e){if(!this.err){this.err(e);}}}return false;}};return new LAjax();})();
  133. var LEventDispatcher=(function(){function LEventDispatcher(){var s=this;LExtends(s,LObject,[]);s._eventList=new Array();}var p={addEventListener:function(type,listener){this._eventList.push({listener:listener,type:type});},removeEventListener:function(type,listener){var s=this,i,length;length=s._eventList.length;for(i=0; i<length; i++){if(!s._eventList[i]){continue;}if(type==s._eventList[i].type&&s._eventList[i].listener==listener){s._eventList.splice(i,1);return;}}},removeAllEventListener:function(){this._eventList=[];},dispatchEvent:function(event){var s=this,i,length=s._eventList.length,ctype=(typeof event=="string")?event:event.eventType;for(i=0; i<length; i++){if(!s._eventList[i]){continue;}if(ctype==s._eventList[i].type){if(typeof event=="string"){s.currentTarget=s.target=s;s.eventType=s.event_type=ctype;s._eventList[i].listener(s);}else{if(!event.target){event.target=s;}if(!event.currentTarget){event.currentTarget=event.target;}event._ll_preventDefault=false;s._eventList[i].listener(event);if(event._ll_preventDefault){return false;}}return true;}}return false;},hasEventListener:function(type,listener){var s=this,i,length=s._eventList.length;for(i=0; i<length; i++){if(!s._eventList[i]){continue;}if(type==s._eventList[i].type){if(typeof listener==UNDEFINED||listener==s._eventList[i].listener){return true;}}}return false;}};for(var k in p){LEventDispatcher.prototype[k]=p[k];}return LEventDispatcher;})();
  134. var LWebAudio=(function(){function LWebAudio(){var s=this;LExtends(s,LEventDispatcher,[]);s.currentTime=0;s.currentStart=0;s.currentSave=0;s.length=0;s.loopStart=0;s.loopEnd=0;s.loopIndex=0;s.loopLength=1;s.playing=false;s.volume=1;}LWebAudio.container=[];LWebAudio.containerCount=0;LWebAudio.audioTag=new Audio();LWebAudio._context=null;var p={getWebAudio:function(){var data;if(LWebAudio.containerCount>0){data=LWebAudio.container.shift();}else{if(typeof webkitAudioContext!==UNDEFINED){try{data=new webkitAudioContext();}catch(e){LWebAudio.containerCount=LWebAudio.container.length;data=LWebAudio.container.shift();}}else if(typeof AudioContext!==UNDEFINED){try{data=new AudioContext();}catch(e){LWebAudio.containerCount=LWebAudio.container.length;data=LWebAudio.container.shift();}}else{throw "AudioContext not supported.:(";}}if(!data.createGainNode){data.createGainNode=data.createGain;}LWebAudio.container.push(data);return data;},onload:function(data){var s=this;if(Object.prototype.toString.apply(data)!=='[object AudioBuffer]'){s.load(data);return;};if(!s.data){s.data=s.getWebAudio();}s.buffer=data;s.length=s.buffer.duration;var e=new LEvent(LEvent.COMPLETE);e.currentTarget=s;e.target=s.buffer;s.dispatchEvent(e);},_onended:function(){var s=this;s.dispatchEvent(LEvent.SOUND_COMPLETE);if(++s.loopIndex<s.loopLength){s.play(s.currentStart,undefined,s.currentTimeTo);}else{s.close();}},load:function(u){var s=this;if(typeof u!=="string"){if(Object.prototype.toString.apply(u)=='[object AudioBuffer]'){s.onload(u);}else if(Object.prototype.toString.apply(u)=='[object ArrayBuffer]'){if(!s.data){s.data=s.getWebAudio();}s.data.decodeAudioData(u,s.onload.bind(s),function(error){throw "AudioContext decodeAudioData error:"+error.toString();});}return;}var a,b,k,d,q={"mov":"quicktime","3gp":"3gpp","ogv":"ogg","m4a":"mpeg","mp3":"mpeg","wave":"wav","aac":"mp4"};a=u.split(',');for(k in a){b=a[k].split('.');d=b[b.length-1];if(q[d]){d=q[d];}if(LWebAudio.audioTag.canPlayType(s._type+"/"+d)){LAjax.responseType=LAjax.ARRAY_BUFFER;LAjax.get(a[k],{},s.onload.bind(s));return;}}},getCurrentTime:function(){var s=this;if(s.playing){return s.data.currentTime-s.currentSave+s.currentTime;}else{return s.currentSave;}},setVolume:function(v){var s=this;s.volume=v;if(s.playing){s.volumeNode.gain.value=v;}},getVolume:function(){return this.volume;},play:function(c,l,to){var s=this;if(s.length==0){return;}if(typeof l!==UNDEFINED){s.loopIndex=0;s.loopLength=l;}if(typeof c!==UNDEFINED){s.currentTime=c;s.currentStart=c;}if(typeof to!==UNDEFINED){s.currentTimeTo=to>s.length?s.length:to;}else{s.currentTimeTo=s.length;}s.data.loop=false;s.playing=true;if(s.timeout){clearTimeout(s.timeout);delete s.timeout;}s.timeout=setTimeout(s._onended.bind(s),(s.currentTimeTo-s.currentTime)*1000);s.bufferSource=s.data.createBufferSource();s.bufferSource.buffer=s.buffer;s.volumeNode=s.data.createGainNode();s.volumeNode.gain.value=s.volume;s.volumeNode.connect(s.data.destination);s.bufferSource.connect(s.volumeNode);s.currentSave=s.data.currentTime;if(s.bufferSource.start){s.bufferSource.start(0,s.currentTime,s.length-s.currentTime);}else{s.bufferSource.noteGrainOn(0,s.currentTime,s.length-s.currentTime);}},playSegment:function(c,seg,l){this.playTo(c,c+seg,l);},playTo:function(c,to,l){this.play(c,l,to);},stop:function(){var s=this;if(!s.playing){return;}clearTimeout(s.timeout);delete s.timeout;if(s.bufferSource.stop){s.bufferSource.stop(0);}else{s.bufferSource.noteOff(0);}s.currentSave=s.getCurrentTime();s.currentTime=s.currentSave;s.playing=false;},close:function(){var s=this;if(!s.playing){return;}clearTimeout(s.timeout);delete s.timeout;if(s.bufferSource.stop){s.bufferSource.stop(0);}else{s.bufferSource.noteOff(0);}s.playing=false;s.currentTime=0;s.currentSave=0;}};for(var k in p){LWebAudio.prototype[k]=p[k];}return LWebAudio;})();
  135. var LDisplayObject=(function(){function LDisplayObject(){var s=this;LExtends(s,LEventDispatcher,[]);s.name="instance"+s.objectIndex;s.x=0;s.y=0;s.width=0;s.height=0;s.scaleX=1;s.scaleY=1;s.alpha=1;s.visible=true;s.rotate=0;s.mask=null;s.blendMode=null;s.filters=null;}var p={_createCanvas:function(){var s=this;if(!s._canvas){s._canvas=document.createElement("canvas");s._context=s._canvas.getContext("2d");}},ll_show:function(){var s=this,c=LGlobal.canvas;if(!s._canShow()){return;}if(!LGlobal.box2d&&typeof s._ll_loopframe=="function"){s._ll_loopframe();}c.save();s._showReady(c);if(s.blendMode){c.globalCompositeOperation=s.blendMode;}if(s.filters){s._ll_setShadow();}s._rotateReady();if(s.mask!=null&&s.mask.ll_show){s.mask.ll_show();c.clip();}s._transformRotate();s._transformScale();s._coordinate(c);if(s.alpha<1){c.globalAlpha=s.alpha;}s._ll_show(c);c.restore();if(LGlobal.box2d!=null&&typeof s._ll_loopframe=="function"){s._ll_loopframe();}},_canShow:function(){return this.visible;},_coordinate:function(c){var s=this;if(s.x!=0||s.y!=0){c.transform(1,0,0,1,s.x,s.y);}},_rotateReady:function(){},_showReady:function(c){},_ll_show:function(c){},_ll_setShadow:function(){var s=this,f=s.filters,i,l;if(!f){return;}for(i=0,l=f.length; i<l; i++){f[i].ll_show();}},_transformRotate:function(){var s=this,c;if(s.rotate==0){return;}c=LGlobal.canvas,rotateFlag=Math.PI/180,rotateObj=new LMatrix();if((typeof s.rotatex)==UNDEFINED){s.rotatex=0;s.rotatey=0;}if(s.box2dBody){rotateFlag=1;}rotateObj.a=Math.cos(s.rotate*rotateFlag);rotateObj.b=Math.sin(s.rotate*rotateFlag);rotateObj.c=-rotateObj.b;rotateObj.d=rotateObj.a;rotateObj.tx=s.x+s.rotatex;rotateObj.ty=s.y+s.rotatey;rotateObj.transform(c).setTo(1,0,0,1,-rotateObj.tx,-rotateObj.ty).transform(c);},_transformScale:function(){var s=this,c=LGlobal.canvas,scaleObj;if(s.scaleX==1&&s.scaleY==1){return;}scaleObj=new LMatrix();if(s.scaleX!=1){scaleObj.tx=s.x;}if(s.scaleY!=1){scaleObj.ty=s.y;}scaleObj.a=s.scaleX;scaleObj.d=s.scaleY;scaleObj.transform(c).setTo(1,0,0,1,-scaleObj.tx,-scaleObj.ty).transform(c);},copyProperty:function(a){var s=this,k;for(k in a){if(typeof a[k]=="number"||typeof a[k]=="string"||typeof a[k]=="boolean"){if(k=="objectindex"||k=="objectIndex"){continue;}s[k]=a[k];}else if(Array.isArray(a[k])){s[k]=a[k].slice();}}if(a.mask){s.mask=a.mask.clone();}},getAbsoluteScale:function(){var s=this,sX,sY,p;sX=s.scaleX;sY=s.scaleY;p=s.parent;while(p&&p!="root"){sX*=p.scaleX;sY*=p.scaleY;p=p.parent;}return{scaleX:sX,scaleY:sY};},getRootCoordinate:function(){var s=this,sx,sy,p;sx=s.x;sy=s.y;p=s.parent;while(p&&p!="root"){sx*=p.scaleX;sy*=p.scaleY;sx+=p.x;sy+=p.y;p=p.parent;}return new LPoint(sx,sy);},getBounds:function(d){if(typeof d==UNDEFINED){return new LRectangle(0,0,0,0);}var s=this,x=0,y=0,w=0,h=0,sp,dp;if(s.objectIndex!=d.objectIndex){sp=s.getRootCoordinate();dp=d.getRootCoordinate();x=sp.x-dp.x;y=sp.y-dp.y;}if(d.getWidth){w=d.getWidth();}if(d.getHeight){h=d.getHeight();}return new LRectangle(x,y,w,h);},getDataCanvas:function(){var s=this,_o,o,_c,c;s._createCanvas();o=LGlobal.canvasObj;c=LGlobal.canvas;_o=s._canvas;_c=s._context;s.width=s.getWidth();s.height=s.getHeight();_o.width=s.width;_o.height=s.height;_c.clearRect(0,0,s.width,s.height);LGlobal.canvasObj=s._canvas;LGlobal.canvas=s._context;s.ll_show();s._canvas=_o;s._context=_c;LGlobal.canvasObj=o;LGlobal.canvas=c;return s._canvas;},getDataURL:function(){var s=this,r=s.getDataCanvas();return r.toDataURL();},ismouseonShapes:function(shapes,mx,my){var s=this,parent=s,m,child,j,v,arg;if(typeof shapes==UNDEFINED){shapes=s.shapes;}m=s.getRootMatrix();for(j=shapes.length-1; j>=0; j--){child=shapes[j];arg=child.arg;v=s._changeShape(child.type,arg,m);if(child.type==LShape.VERTICES){if(LGlobal.hitPolygon(v,mx,my)){return true;}}else if(child.type==LShape.RECT){if(LGlobal.hitPolygon(v,mx,my)){return true;}}else if(child.type==LShape.ARC){if((v[0]-mx)*(v[0]-mx)+(v[1]-my)*(v[1]-my)<v[3]){return true;}}}return false;},_changeShape:function(type,arg,m){var v,arg=arg,r2,i,l,v1,v2;if(type==LShape.VERTICES){v=[];for(i=0,l=arg.length; i<l; i++){v[i]=m.toArray([arg[i][0],arg[i][1],1]);}}else if(type==LShape.RECT){v=[[arg[0],arg[1]],[arg[0]+arg[2],arg[1]],[arg[0]+arg[2],arg[1]+arg[3]],[arg[0],arg[1]+arg[3]]];for(i=0,l=v.length; i<l; i++){v[i]=m.toArray([v[i][0],v[i][1],1]);}}else if(type==LShape.ARC){v1=m.toArray([arg[0],arg[1],1]);v2=m.toArray([arg[0]+arg[2],arg[1],1]);r2=(v1[0]-v2[0])*(v1[0]-v2[0])+(v1[1]-v2[1])*(v1[1]-v2[1]);v=[v1[0],v1[1],Math.sqrt(r2),r2];}return v;},getRootMatrix:function(){var parent=this,m=new LMatrix();while(parent&&parent!="root"){if(parent.scaleX!=1||parent.scaleY!=1){m.scale(parent.scaleX,parent.scaleY);}if(parent.rotate!=0){m.rotate(parent.rotate);}if(parent.x!=0||parent.y!=0){m.translate(parent.x,parent.y);}parent=parent.parent;}return m;},remove:function(){var s=this,p=s.parent;if(!p||p=="root"){return;}p.removeChild(s);}};for(var k in p){LDisplayObject.prototype[k]=p[k];}return LDisplayObject;})();
  136. var LMedia=(function(){function LMedia(){var s=this;LExtends(s,LDisplayObject,[]);s.length=0;s.loopIndex=0;s.loopLength=1;s.playing=false;s.oncomplete=null;s.onsoundcomplete=null;s.currentStart=0;}var p={onload:function(){var s=this;if(s.data.readyState){s.length=s.data.duration;var e=new LEvent(LEvent.COMPLETE);e.currentTarget=s;e.target=s.data;s.dispatchEvent(e);return;}s.data.addEventListener("canplaythrough",function(){s.onload();},false);},_onended:function(){var s=this;if(s.data.ended){s.dispatchEvent(LEvent.SOUND_COMPLETE);}if(++s.loopIndex<s.loopLength){s.data.currentTime=s.currentStart;if(s.timeout){clearTimeout(s.timeout);s.timeout=setTimeout(s._onended.bind(s),(s.currentTimeTo-s.data.currentTime)*1000);}s.data.play();}else{s.close();}},load:function(u){var s=this;if(Object.prototype.toString.apply(u)=="[object HTMLAudioElement]"){s.data=u;s.onload();return;}var a,b,k,d,q={"mov":"quicktime","3gp":"3gpp","ogv":"ogg","m4a":"mpeg","mp3":"mpeg","wave":"wav","aac":"mp4"};a=u.split(',');for(k in a){b=a[k].split('.');d=b[b.length-1];if(q[d]){d=q[d];}if(s.data.canPlayType(s._type+"/"+d)){s.data.src=a[k];s.onload();s.data.addEventListener("ended",function(){s._onended();},false);s.data.load();return;}}if(s.oncomplete){s.oncomplete({});}},getCurrentTime:function(){return this.data.currentTime;},setVolume:function(v){this.data.volume=v;},getVolume:function(){return this.data.volume;},play:function(c,l,to){var s=this;if(s.length==0){return;}if(typeof l==UNDEFINED){l=1;}if(typeof c==UNDEFINED){c=0;}if(c>0){s.data.currentTime=c;s.currentStart=c;}if(typeof to!==UNDEFINED){s.currentTimeTo=to>s.length?s.length:to;if(s.timeout){clearTimeout(s.timeout);delete s.timeout;}s.timeout=setTimeout(s._onended.bind(s),(s.currentTimeTo-s.data.currentTime)*1000);}s.data.loop=false;s.loopIndex=0;s.loopLength=l;s.playing=true;s.data.play();},playSegment:function(c,seg,l){this.playTo(c,c+seg,l);},playTo:function(c,to,l){this.play(c,l,to);},stop:function(){var s=this;if(!s.playing){return;}if(s.timeout){clearTimeout(s.timeout);delete s.timeout;}s.playing=false;s.data.pause();},close:function(){var s=this;if(!s.playing){return;}if(s.timeout){clearTimeout(s.timeout);delete s.timeout;}s.playing=false;s.data.pause();s.data.currentTime=0;s.currentSave=0;}};for(var k in p){LMedia.prototype[k]=p[k];}return LMedia;})();
  137. LSound = function(u) {
  138. var s = this;
  139. s.type = "LSound";
  140. s._type = "audio";
  141. LGlobal = {};
  142. LGlobal.webAudio=true;
  143. if (LSound.webAudioEnabled && LGlobal.webAudio) {
  144. LExtends(s, LWebAudio, []);
  145. } else {
  146. LExtends(s, LMedia, []);
  147. s.data = new Audio();
  148. s.data.loop = false;
  149. s.data.autoplay = false;
  150. } if (u) {
  151. s.load(u);
  152. }
  153. }
  154. LSound.TYPE_SOUND = "sound";
  155. LSound.webAudioEnabled = false;
  156. LSound.LEvent = LEvent;
  157. var protocol = location.protocol;
  158. if (protocol == "http:" || protocol == "https:") {
  159. if (typeof webkitAudioContext !== UNDEFINED) {
  160. try {
  161. LWebAudio._context = new webkitAudioContext();
  162. } catch (e) {}
  163. } else if (typeof AudioContext !== UNDEFINED) {
  164. try {
  165. LWebAudio._context = new AudioContext();
  166. } catch (e) {}
  167. }
  168. if (LWebAudio._context) {
  169. LWebAudio.container.push(LWebAudio._context);
  170. LSound.webAudioEnabled = true;
  171. }
  172. }
  173. }
  174. return LSound;
  175. })();
  176. Util.sound = {
  177. effect: {}
  178. ,createAudio: function(src, loop, map){
  179. var audio = document.createElement("audio");
  180. audio.src = src;
  181. audio.loop = loop;
  182. map && (map[src] = audio);
  183. return audio;
  184. }
  185. ,playEffect: function(src, loop){
  186. var self = this;
  187. if(Util.isIphone){
  188. if(!this.effect[src]){
  189. var au = this.createAudio(src, loop);
  190. self.effect[src] = {
  191. node: au,
  192. duration: au.duration || 2,
  193. list: [au],
  194. playCount: 0,
  195. current: 0,
  196. hasLoaded: false,
  197. playCountBeforeLoaded: 1
  198. };
  199. au.onloadeddata = function(){
  200. self.effect[src].hasLoaded = true;
  201. for(var i = 0; i < self.effect[src].playCountBeforeLoaded; i++){
  202. Util.sound.playEffect(src, 0);
  203. }
  204. }
  205. }else if(!this.effect[src].hasLoaded){
  206. this.effect[src].playCountBeforeLoaded++;
  207. }else{
  208. try{
  209. var effect = this.effect[src];
  210. // 缓存不足,就增加呗~
  211. if(effect.playCount >= effect.list.length){
  212. var max = effect.playCount - effect.list.length + 1;
  213. for(var i = 0; i < max; i++){
  214. var au = effect.node.cloneNode();
  215. effect.list.push(au);
  216. }
  217. effect.current = effect.list.length-1;
  218. }
  219. var sound = effect.list[effect.current];
  220. sound.play();
  221. effect.current++;
  222. if(effect.current >= effect.list.length){
  223. effect.current = 0;
  224. }
  225. effect.playCount++;
  226. setTimeout(function(){
  227. effect.playCount--;
  228. }, effect.duration * 1000);
  229. }catch(e){
  230. alert(e);
  231. }
  232. }
  233. }else{
  234. // var self = this;
  235. if(!this.effect[src]){
  236. this.effect[src] = new Util.LSound();
  237. self.effect[src].addEventListener(Util.LSound.LEvent.COMPLETE,function(){
  238. self.effect[src].play(0, 1);
  239. });
  240. this.effect[src].load(src);
  241. }else{
  242. this.effect[src].play(0, 1);
  243. }
  244. }
  245. }
  246. }
  247. Util.soundPreload = function(src){
  248. var hasLoaded = true;
  249. var audio = null;
  250. try{
  251. audio = document.createElement("audio");
  252. audio.addEventListener('onended', function(){
  253. // audio.play();
  254. hasLoaded = true;
  255. }, false);
  256. audio.src = src;
  257. }catch(e){}
  258. return {
  259. play: function(){
  260. try{
  261. if(hasLoaded){
  262. audio.currentTime = 0;
  263. audio.play();
  264. }
  265. }catch(e){}
  266. }
  267. }
  268. }
  269. }(Util);
  270. var DEGREE = {
  271. EASY: "easy"
  272. ,NORMAL: "normal"
  273. ,CRAZY: "crazy"
  274. }
  275. var MODE = {
  276. ODD: "odd"
  277. ,EVEN: "even"
  278. }
  279. var Frame = {
  280. $object: null
  281. ,start: function(){}
  282. ,end: function(){}
  283. }
  284. var PrefaceFrame = $.extend({}, Frame, {
  285. $object: $("#preface")
  286. ,start: function(){
  287. var self = this;
  288. var $tip0 = self.$object.find(".ptips0");
  289. var $tip1 = self.$object.find(".ptips1");
  290. $tip0.css("top", Game.height+"px");
  291. $tip1.css("top", Game.height+"px");
  292. Util.animation($tip0, 1, {top: Game.height/2-$tip0.height()*2, onComplete:function(){
  293. Util.animation($tip1, 1, {top: Game.height/2, onComplete:function(){
  294. setTimeout(function(){
  295. Game.switchTo(self, Start0Frame);
  296. }, 1000);
  297. }});
  298. }});
  299. // setTimeout(function(){
  300. // Game.switchTo(self, Start0Frame);
  301. // });
  302. }
  303. });
  304. var Start0Frame = $.extend({}, Frame, {
  305. $object: $("#start-0")
  306. ,isFirst: true
  307. ,start: function(){
  308. var self = this;
  309. self._bindUI();
  310. if(self.isFirst){
  311. self.isFirst = false;
  312. self._setDefault();
  313. self._bindEvent();
  314. }
  315. }
  316. ,_bindUI: function(){
  317. // $("html").css("background", "#49caae");
  318. }
  319. ,_setDefault: function(){
  320. this.$object.find(".seasy a").addClass("active");
  321. Game.degree = DEGREE.EASY;
  322. }
  323. ,_bindEvent: function(){
  324. var self = this;
  325. self.$object.on(Util.eventTouchStart, ".sdegree a", function(){
  326. var $aself = $(this);
  327. var $parent = $aself.closest(".degree");
  328. if($parent.hasClass("seasy")){
  329. Game.degree = DEGREE.EASY;
  330. }else if($parent.hasClass("snormal")){
  331. Game.degree = DEGREE.NORMAL;
  332. }else if($parent.hasClass("scrazy")){
  333. Game.degree = DEGREE.CRAZY;
  334. }
  335. self.$object.find("a").removeClass("active");
  336. $aself.addClass("active");
  337. }).on(Util.eventTouchStart, "#startgame", function(){
  338. Game.switchTo(self, Start1Frame);
  339. Game.initSound();
  340. }).on(Util.eventTouchStart, "#moregame", function(){
  341. //location.href = btGame.URL.getMoreGame();
  342. // Play68.goHome();
  343. });
  344. }
  345. });
  346. var Start1Frame = $.extend({}, Frame, {
  347. $object: $("#start-1")
  348. ,isFirst: true
  349. ,start: function(){
  350. var self = this;
  351. try{
  352. Game.bestScore[Game.degree] = localStorage["kdosBestScore_"+Game.degree] || 0;
  353. }catch(e){}
  354. self._bindUI();
  355. if(self.isFirst){
  356. self.isFirst = false;
  357. self._setDefault();
  358. self._bindEvent();
  359. }
  360. }
  361. ,_bindUI: function(){
  362. // $("html").css("background", "#636363");
  363. }
  364. ,_setDefault: function(){
  365. this.$object.find(".seven a").addClass("active");
  366. Game.mode = MODE.EVEN;
  367. }
  368. ,_bindEvent: function(){
  369. var self = this;
  370. self.$object.on(Util.eventTouchStart, ".smode a", function(){
  371. var $aself = $(this);
  372. var $parent = $aself.closest(".mode");
  373. if($parent.hasClass("seven")){
  374. Game.mode = MODE.EVEN;
  375. self.$object.find(".stips").removeClass("invert");
  376. }else if($parent.hasClass("sodd")){
  377. Game.mode = MODE.ODD;
  378. self.$object.find(".stips").addClass("invert");
  379. }
  380. self.$object.find("a").removeClass("active");
  381. $aself.addClass("active");
  382. }).on(Util.eventTouchStart, "#start", function(){
  383. Game.switchTo(self, MainFrame);
  384. });
  385. }
  386. });
  387. var MainFrame = $.extend({}, Frame, {
  388. $object: $("#main")
  389. ,$score: $("#main .score")
  390. ,isFirst: true
  391. ,startTime: null
  392. ,blocks:{
  393. width: 0
  394. ,height: 0
  395. ,speed: 1
  396. ,list: []
  397. ,createRow: function(top){
  398. var self = this;
  399. for(var i = 0; i < 3; i++){
  400. var block = {};
  401. block.number = Util.randomN(10)+1;
  402. block.top = top;
  403. var content = '<div class="block" onselectstart="return false;" ontouchstart="return false;" data-number="'+block.number+'"> </div>'
  404. block.$dom = $(content).appendTo(MainFrame.$object.find(".blocks"));
  405. block.$dom.css({"top": block.top+"px"
  406. ,"left": (i*self.width)+"px"
  407. ,"width": self.width+"px"
  408. ,"height": self.height+"px"
  409. ,"line-height": self.height+"px"
  410. ,"background-size": (self.width*5)+"px "+(self.height*2)+"px"
  411. ,"background-position": ((-(block.number-1)%5)*self.width)+"px "+(parseInt((block.number-1)/5)*(-self.height))+"px"
  412. });
  413. self.list.push(block);
  414. block.$dom.blockObject = block;
  415. }
  416. }
  417. ,moveDown: function(){
  418. var self = this;
  419. for(var i = 0; i < self.list.length; i++){
  420. self.list[i].top+=3*self.speed;
  421. if(self.list[i].top > Game.height+10){
  422. setTimeout(function(){
  423. self.list.shift();
  424. },0);
  425. }else{
  426. self.list[i].$dom.css("top", self.list[i].top+"px");
  427. }
  428. }
  429. var lastBlock = self.list[self.list.length-1];
  430. if(lastBlock.top > -2){
  431. self.createRow(lastBlock.top-self.height);
  432. }
  433. self._checkGameOver();
  434. }
  435. ,reset: function(){
  436. var self = this;
  437. self.list = [];
  438. MainFrame.$object.find(".blocks").html("");
  439. }
  440. ,_checkGameOver: function(){
  441. var self = this;
  442. var isGameOver = false;
  443. for(var i = 0; i < Math.min(3, self.list.length); i++){
  444. if(self.list[i].top+self.height>Game.height
  445. && ((self.list[i].number%2==0 && Game.mode==MODE.EVEN) || (self.list[i].number%2==1 && Game.mode==MODE.ODD))
  446. && !self.list[i].$dom.hasClass("right")){
  447. self.list[i].$dom.addClass("wrong");
  448. isGameOver = true;
  449. }
  450. }
  451. if(isGameOver){
  452. MainFrame.gameOver();
  453. }
  454. }
  455. }
  456. ,start: function(){
  457. var self = this;
  458. // if()
  459. // console.log("haha");
  460. self.blocks.height = self.blocks.width = Game.width/3;
  461. self.blocks.createRow(-self.blocks.height);
  462. self.blocks.speed = (Game.degree==DEGREE.EASY)?1:((Game.degree==DEGREE.NORMAL)?1.5:2);
  463. self._bindEvent();
  464. if(self.isFirst){
  465. self.isFirst = false;
  466. }
  467. self.startTime = new Date;
  468. // self.interval = Util.setIntervalWithTimeout(function(){
  469. // self._update();
  470. // }, 1000/30);
  471. // requestAnimationFrame($.proxy(self, self._update));
  472. function _update(){
  473. self._update = requestAnimationFrame(_update);
  474. self.blocks.moveDown();
  475. Game.currentScore = ((new Date()-self.startTime)/1000).toFixed(2);
  476. self.$score.html(Game.currentScore+"s");
  477. }
  478. _update();
  479. }
  480. ,end: function(){
  481. var self = this;
  482. self.blocks.reset();
  483. }
  484. ,gameOver: function(){
  485. var self = this;
  486. // Util.clearIntervalWithTimeout(self.interval);
  487. cancelAnimationFrame(self._update);
  488. setTimeout(function(){
  489. Game.switchTo(self, OverFrame);
  490. }, 500);
  491. self.$object.off(Util.eventTouchStart);
  492. Util.sound.playEffect("sound/gameover_sound.mp3", 0);
  493. }
  494. ,_bindEvent: function(){
  495. var self = this;
  496. self.$object.on(Util.eventTouchStart, ".block", function(){
  497. var $self = $(this);
  498. var val = parseInt($self.data("number"));
  499. if((val%2==0 && Game.mode==MODE.EVEN) || (val%2==1 && Game.mode==MODE.ODD)){
  500. $self.addClass("right");
  501. Util.sound.playEffect("sound/click_sound.mp3", 0);
  502. }else{
  503. $self.addClass("wrong");
  504. self.gameOver();
  505. }
  506. return false;
  507. });
  508. }
  509. });
  510. var OverFrame = $.extend({}, Frame, {
  511. $object: $("#over")
  512. ,isFirst: true
  513. ,start: function(){
  514. var self = this;
  515. if(parseFloat(Game.currentScore) > parseFloat(Game.bestScore[Game.degree])){
  516. Game.bestScore[Game.degree] = Game.currentScore;
  517. // Game.sounds["congradute"].play();
  518. Util.sound.playEffect("sound/congraduate_sound.mp3", 0);
  519. try{
  520. localStorage["kdosBestScore_"+Game.degree] = Game.bestScore[Game.degree];
  521. }catch(e){}
  522. }
  523. self._bindUI();
  524. if(self.isFirst){
  525. self._bindEvent();
  526. self.isFirst = false;
  527. }
  528. self._share();
  529. }
  530. ,_bindUI: function(){
  531. var self = this;
  532. // $("html").css("background", "#f46564");
  533. self.$object.find(".otitle").removeClass("degree-easy").removeClass("degree-normal").removeClass("degree-crazy").addClass("degree-"+Game.degree);
  534. self.$object.find(".oscore").html(Game.currentScore+"s");
  535. self.$object.find(".obestscore").html(Game.bestScore[Game.degree]+"s");
  536. }
  537. ,_bindEvent: function(){
  538. var self = this;
  539. self.$object.on(Util.eventTouchStart, ".btn", function(){
  540. var $self = $(this);
  541. if($self.hasClass("oback")){
  542. Game.switchTo(self, Start0Frame);
  543. }else if($self.hasClass("oretry")){
  544. Game.switchTo(self, MainFrame);
  545. }else if($self.hasClass("omore")){
  546. // Play68.goHome();
  547. }
  548. });
  549. }
  550. ,_share: function(){
  551. var self = this;
  552. var degree = (Game.degree==DEGREE.EASY)?"低能儿":((Game.degree==DEGREE.NORMAL)?"正常":"高智商");
  553. var myHead = "";
  554. if (Game.degree==DEGREE.EASY) {
  555. myHead =1;
  556. }
  557. else if (Game.degree==DEGREE.NORMAL) {
  558. myHead =2;
  559. }
  560. else{
  561. myHead =3;
  562. }
  563. // Play68.setRankingLevelScoreDesc(myHead,Game.currentScore);
  564. // updateShare(Game.currentScore,degree);
  565. }
  566. });
  567. window.Game = {
  568. currentScore: 0
  569. ,bestScore: {}
  570. ,degree: DEGREE.EASY
  571. ,mode: MODE.ODD
  572. ,width: $(window).width()
  573. ,height: $(window).height()
  574. ,baseFontSize: 1
  575. ,sounds: {}
  576. ,switchTo: function(sourceFrame, targetFrame, style){
  577. var self = this;
  578. setTimeout(function(){
  579. if(targetFrame == undefined){
  580. targetFrame = sourceFrame;
  581. }else{
  582. sourceFrame.$object.fadeOut(500);
  583. // Util.rotateOut(sourceFrame.$object);
  584. sourceFrame.end();
  585. }
  586. targetFrame.start();
  587. // targetFrame.$object.show();
  588. setTimeout(function(){
  589. targetFrame.$object.fadeIn(500);
  590. }, 500);
  591. // Util.rotateIn(targetFrame.$object, 1000);
  592. }, 0);
  593. }
  594. ,start: function(){
  595. var self = this;
  596. self._preload();
  597. $(".frame").hide();
  598. ;(function setSize(){
  599. $h = $("html");
  600. $f = $("#frames");
  601. $(window).resize(function(){
  602. (function setBaseFontSize(){
  603. var winW = $h.width();
  604. var isPC = navigator.userAgent.match(/(ipad|iphone|ipod|android|windows phone)/i) ? false : true;
  605. // winW = isPC ? 480 : winW;
  606. var fontSize = self.baseFontSize = ~~winW * 12 / 320;
  607. $h.css("font-size", fontSize);
  608. })();
  609. self.width = $(window).width();
  610. self.height = $(window).height();
  611. $f.css("width", self.width+"px");
  612. $f.css("height", self.height+"px");
  613. });
  614. $(window).resize();
  615. })();
  616. this.switchTo(PrefaceFrame);
  617. // this.switchTo(OverFrame);
  618. }
  619. ,initSound: function(){
  620. var self = this;
  621. if(!self._hasInitSound){
  622. self.sounds["click"] = Util.soundPreload("sound/click_sound.mp3");
  623. self.sounds["congradute"] = Util.soundPreload("sound/congraduate_sound.mp3");
  624. self.sounds["gameover"] = Util.soundPreload("sound/gameover_sound.mp3");
  625. self._hasInitSound = true;
  626. }
  627. }
  628. ,_preload: function(){
  629. var self = this;
  630. Util.preloadImg(["style/img_d/break_phone.png"
  631. ,"style/img_d/difficult_mode_checked.png"
  632. ,"style/img_d/difficult_mode_unchecked.png"
  633. ,"style/img_d/easy_mode_checked.png"
  634. ,"style/img_d/easy_mode_unchecked.png"
  635. ,"style/img_d/friendly_tip.png"
  636. ,"style/img_d/more_game_normal.png"
  637. ,"style/img_d/normal_mode_checked.png"
  638. ,"style/img_d/normal_mode_unchecked.png"
  639. ,"style/img_d/start_game_normal.png"
  640. ,"style/img_d/title.png"
  641. ,"style/img_d/introduce.png"
  642. ,"style/img_d/introduce_invert.png"
  643. ,"style/img_d/even_mode_unchecked.png"
  644. ,"style/img_d/odd_mode_unchecked.png"
  645. ,"style/img_d/even_mode_checked.png"
  646. ,"style/img_d/odd_mode_checked.png"
  647. ,"style/img_d/start_normal.png"
  648. ,"style/img_d/ending_moregame_normal.png"
  649. ,"style/img_d/normal_mode.png"
  650. ,"style/img_d/difficult_mode.png"
  651. ,"style/img_d/easy_mode.png"
  652. ,"style/img_d/restart_btn_normal.png"
  653. ,"style/img_d/share_text_normal.png"
  654. ,"style/img_d/logo.png"
  655. ,"style/img_d/back_btn_normal.png"
  656. ]);
  657. }
  658. }
  659. Game.start();
  660. });
  661. // window.onerror = function(e){
  662. // alert(e);
  663. // }