本文实例讲述了微信小程序实现的贪吃蛇游戏。分享给大家供大家参考,具体如下:
先来看看运行效果:
具体代码如下:
界面布局 pages/snake/snake/snake.wxml:
snake 得分 {{score}} 历史最高 {{maxscore}} 游戏结束,重新开始吗?
逻辑功能 pages/snake/snake/snake.js:
//snake.js var app = getApp(); Page({ data:{ score: 0,//比分 maxscore: 0,//最高分 startx: 0, starty: 0, endx:0, endy:0,//以上四个做方向判断来用 ground:[],//存储操场每个方块 rows:28, cols:22,//操场大小 snake:[],//存蛇 food:[],//存食物 direction:'',//方向 modalHidden: true, timer:'' } , onLoad:function(){ var maxscore = wx.getStorageSync('maxscore'); if(!maxscore) maxscore = 0 this.setData({ maxscore:maxscore }); this.initGround(this.data.rows,this.data.cols);//初始化操场 this.initSnake(3);//初始化蛇 this.creatFood();//初始化食物 this.move();//蛇移动 }, //计分器 storeScore:function(){ if(this.data.maxscore < this.data.score){ this.setData({ maxscore:this.data.score }) wx.setStorageSync('maxscore', this.data.maxscore) } }, //操场 initGround:function(rows,cols){ for(var i=0;i5 || Math.abs(shu) > 5){ var direction = (Math.abs(heng) > Math.abs(shu)) ? this.computeDir(1, heng):this.computeDir(0, shu); switch(direction){ case 'left': if(this.data.direction=='right')return; break; case 'right': if(this.data.direction=='left')return; break; case 'top': if(this.data.direction=='bottom')return; break; case 'bottom': if(this.data.direction=='top')return; break; default: } this.setData({ startx:0, starty:0, endx:0, endy:0, direction:direction }) } }, computeDir: function(heng, num){ if(heng) return (num > 0) ? 'right' : 'left'; return (num > 0) ? 'bottom' : 'top'; }, creatFood:function(){ var x=Math.floor(Math.random()*this.data.rows); var y=Math.floor(Math.random()*this.data.cols); var ground= this.data.ground; ground[x][y]=2; this.setData({ ground:ground, food:[x,y] }); }, changeDirection:function(dir){ switch(dir){ case 'left': return this.changeLeft(); break; case 'right': return this.changeRight(); break; case 'top': return this.changeTop(); break; case 'bottom': return this.changeBottom(); break; default: } }, changeLeft:function(){ var arr=this.data.snake; var len=this.data.snake.length; var snakeHEAD=arr[len-1][1]; var snakeTAIL=arr[0]; var ground=this.data.ground; ground[snakeTAIL[0]][snakeTAIL[1]]=0; for(var i=0;i =this.data.rows||snakeHEAD[1]>=this.data.cols||snakeHEAD[1]<0){ clearInterval(this.data.timer); this.setData({ modalHidden: false, }) } for(var i=0;i
附:完整实例源码点击此处本站下载。
希望本文所述对大家微信小程序开发有所帮助。