横屏小游戏-连连看egret实战
追求全栈,还是挺累的,一直要补充知识。小游戏技能不能不会啊,于是egret撸代码,做个小游戏练练上吧,每天地铁上下班能打发一下时间,关键自己的游戏没广告啊。
其实前面也尝试学习过小游戏开发,但是没有找到感觉。主要原因是egret文档太乱了,根本看不懂。这次本来是去LAYABOX学习的,文档看起来挺舒服,但是LAYABOX到处收费,于是我还是继续去啃egret,原先看不懂的egret文档,在有了layabox文档后居然看懂了,你说神奇不神奇。然后顿时来了感觉,居然敢上来直接撸代码了。
自创了一个写法,把游戏场景想象成html的page了,手写一个page.ts
class Page extends eui.UILayer { protected main; protected page=''; protected page_key=''; protected listen_obj={}; protected time_obj={}; protected sound_obj={}; protected close_action=[]; public constructor(main,page){ super(); this.main=main; this.page=page; this.page_key=main.fun.randtime(); main.page_data.page=this.page; main.page_data.page_key=this.page_key; this.check_inpage(); } public page_init(){ console.log("init"); } public close_page() { for(var i in this.time_obj) { this.time_obj[i].stop(); } console.log('close_action'); console.log(this.close_action); try{ for(var m in this.close_action) { this.close_action[m](); } }catch(e){console.log(e);} for(var n in this) { try{ this[n]=null; delete this[n]; }catch(e){} } } public check_inpage() { if(this.main.page_data.page_key!=this.page_key) { console.error(`当前的game_room是 ${this.main.page_data.page_key},不是${this.page_key}`); this.close_page(); }else{ setTimeout(()=>{ this.check_inpage(); },300); } } public check_ingame() { //-1 异常错误 1正确,0 不在游戏中,暂停中 if(this.main.pause==true) { console.error('暂停中'); return 0; } if(this.main.page_data.page_key!=this.page_key) { console.error(`当前的game_room是 ${this.main.page_data.page_key},不是${this.page_key}`); return -1; } return 1; } //如果页面被关闭了,需要销毁当前页面上所有的事件 public page_close() { console.log('close_action'); console.log(this.close_action); for(var m in this.close_action) { this.close_action[m](); } for(var n in this) { this[n]=null; } } //定时检测页面是否被关闭 public check_page_close() { if(this.check_ingame()==-1) { console.error('页面已被关闭'); this.page_close(); }else{ setTimeout(()=>{ this.check_page_close(); },300); } } } window["Page"]=Page;
为什么要page呢?就是为了让场景独立。否则场景里绑定的事件要一个个清除,太麻烦了。官方文档不太友好,也不知道有没专门的方法,在没找到之前,自己来想办法吧
思路是这样的,初始化的时候,给这个page设置一个唯一id(page_key),然后listen_obj 用于存放当前页面所有监听,time_obj存放当前页面所有定时,sound_obj存放当前页面所有声音,close_action存放页面关闭时执行的方法。
通过唯一id变化判断是否关闭,如果关闭了把监听、定时、声音结束掉,并执行close_action。可以自己加入一些生命周期,因为第一次尝试,就没做那么复杂,主要是为了尝试可行性。
方法虽然野生,但是效果其实很好。关键开发就像开发vue或微信小程序了,简化了游戏开发。但是缺陷还是有的,代码美观度不够,后面有机会整理一下,美观一点看得才舒服。