如何利用uniapp开发一个贪吃蛇小游戏?下面本篇文章就手把手带大家在uniapp中实现贪吃蛇小游戏,希望对大家有所帮助!
第一次玩贪吃蛇还隐约记得是?️后父亲给我玩的第一个游戏
该小游戏使用uniapp开发
前置详细内容就不细说了详细看:https://juejin.cn/post/7085727363547283469#heading-14
游戏演示
代码结构
详细代码结构如果需要请到github查看
主要分为:开始游戏、地块、蛇身、虫子、污染地块,游戏音效
<template><viewref="body"class="content"><view>蛇蛇目前:{{snakes.length}}米长</view><viewclass="game-field"><!–地面板块–><viewclass="block"v-for="(x,i)inblocks":key="i"></view></view><viewv-show="!started||ended"class="game-board-wrap"><viewv-show="!started"class="game-board"><viewclass="title">选择游戏难度</view><radio-groupname="radio"@change="bindLevelChange"><labelclass="label"><radiovalue="1":checked="level==1"/><text>简单模式</text></label><labelclass="label"><radiovalue="2":checked="level==2"/><text>正常模式</text></label><labelclass="label"><radiovalue="3":checked="level==3"/><text>困难模式</text></label><labelclass="label"><radiovalue="4":checked="level==4"/><text>地狱模式</text></label></radio-group><buttontype="primary"@click="start">开始游戏</button></view><viewv-show="ended"class="settle-board"><viewclass="title">游戏结束</view><viewclass="result">您的蛇蛇达到了{{snakes.length}}米</view><viewclass="btns"><buttontype="primary"@click="reStart">再次挑战</button><buttontype="primary"plain@click="rePick">重选难度</button></view></view></view></view></template><script>exportdefault{data(){return{blocks:[],//板块worms:[],//虫子snakes:[0,1,2,3],//蛇身direction:"right",//蛇移动方向};},onLoad(){this.initGame();},methods:{initGame(){this.blocks=newArray(100).fill(0);//生成100个地面板块this.worms=[Math.floor(Math.random()*96)+4];//随机生成虫子this.snakes=[0,1,2,3];//初始化蛇身位置}}}</script>
渲染蛇身
给我们的蛇穿上他的外衣 蛇身的渲染根据snakes(里边放着蛇的身体)来匹配地面板块的索引 从而找到对应的格格并修改背景图来渲染蛇身 蛇头和蛇尾就是取snakes第0位和最后一位 并找到对应的格格修改当前背景图
<template><viewclass="game-field"><viewclass="block":style="`background-image:${bg(x,i)}"v-for="(x,i)inblocks":key="i"></view></view></template><script>importwormfrom"worm.png";importsnakeBodyfrom"snake_body.png";importsnakeHeadfrom"snake_head.png";importsnakeTailfrom"snake_tail.png";importpolluteBlockfrom"pollute.png";importwormBoomfrom"worm_4.png";exportdefault{methods:{bg(type,index){letbg="";switch(type){case0://地板bg="unset";break;case1://虫子if(this.boom){bg=`url(${wormBoom})`;}else{bg=`url(${worm})`;}break;case2://蛇lethead=this.snakes[this.snakes.length-1];lettail=this.snakes[0];if(index===head){bg=`url(${snakeHead})`;}elseif(index===tail){bg=`url(${snakeTail})`;}else{bg=`url(${snakeBody})`;}break;case3://污染的地块bg=`url(${polluteBlock})`;break;}returnbg;},}}</scipt>
控制蛇的方向
控制蛇的方向pc端我们通过监听键盘事件找到对应的键盘键的编码上下左右来改变蛇的方向 而手机端我们通过touch时间手指触摸点及滑动点的XY轴值来判断蛇的方向
<template><viewref="body"class="content"@keyup.left="bindLeft"@keyup.right="bindRight"@keyup.down="bindDown"@keyup.up="bindUp"@touchstart="handleTouchStart"@touchmove="handleTouchMove"><view>蛇蛇目前:{{snakes.length}}米长</view><viewclass="game-field"><viewclass="block":style="`background-image:${bg(x,i)};v-for="(x,i)inblocks":key="i"></view></view></view></template><script>exportdefault{data(){return{direction:"right",started:false,//游戏开始了ended:false,//游戏结束了level:1,//游戏难度lastX:0,lastY:0,}},onLoad(){this.initGame();},methods:{initGame(){this.blocks=newArray(100).fill(0);//生成100个地面板块this.worms=[Math.floor(Math.random()*96)+4];//随机生成虫子this.snakes=[0,1,2,3];//初始化蛇身位置document.onkeydown=(e)=>{switch(e.keyCode){//获取当前按下键盘键的编码case37://按下左箭头键this.bindLeft();break;case39://按下右箭头键this.bindRight();break;case38://按下上箭头键if(!this.started){this.level–;}else{this.bindUp();}break;case40://按下下箭头键if(!this.started){this.level++;}else{this.bindDown();}break;}}},handleTouchStart(e){//手指开始位置this.lastX=e.touches[0].pageX;this.lastY=e.touches[0].pageY;},handleTouchMove(e){letlastX=e.touches[0].pageX;//移动的x轴坐标letlastY=e.touches[0].pageY;//移动的y轴坐标lettouchX=lastX-this.lastX;lettouchY=lastY-this.lastYif(Math.abs(touchX)>Math.abs(touchY)){if(touchX<0){if(this.direction==="right")return;this.direction='left'}elseif(touchX>0){if(this.direction==="left")return;this.direction='right'}}else{if(touchY<0){if(this.direction==="down")return;this.direction='up'}elseif(touchY>0){if(this.direction==="up")return;this.direction='down'}}this.lastX=lastX;this.lastY=lastY;},bindUp(){if(this.direction==="down")return;this.direction="up";},bindDown(){if(this.direction==="up")return;this.direction="down";},bindLeft(){if(this.direction==="right")return;this.direction="left";},bindRight(){if(this.direction==="left")return;this.direction="right";},}}</script>
给贪吃蛇添加音效
添加游戏音效游戏代入感就强了很多 现在我们要给蛇加上背景音乐、点击交互音乐、蛇隔儿屁的音乐、蛇吃掉食物的音乐、虫子爆炸倒计时的音乐和虫子爆炸的音乐
先给添加上背景音乐 总有刁民可以玩到地图满为止 背景音乐的话要loop播放 我们只需要 使用uni.createInnerAudioContext来创建并返回内部 audio 上下文innerAudioContext对象 拿到音乐的路径并且设置自动播放
<script>importbgmfrom'bgm.mp3';exportdefault{data(){return{bgmInnerAudioContext:null,}},methods:{start(){//开始游戏this.initGame();this.handleBgmVoice()},handleBgmVoice(){//背景音乐this.bgmInnerAudioContext=uni.createInnerAudioContext()//创建上下文this.bgmInnerAudioContext.autoplay=true;//自动播放this.bgmInnerAudioContext.src=bgm;//音频地址this.bgmInnerAudioContext.loop=true;//循环播放}}}<script>
背景音乐确实响起来了 蛇gameover后还一直响 顿时我听着就不耐烦 这时我们在蛇gameover后暂停背景音乐pause音乐会暂停而不会清楚
<script>importbgmfrom'bgm.mp3';exportdefault{data(){return{bgmInnerAudioContext:null,}},methods:{start(){//开始游戏this.initGame();this.handleBgmVoice()},handleBgmVoice(){//背景音乐this.bgmInnerAudioContext=uni.createInnerAudioContext()//创建上下文this.bgmInnerAudioContext.autoplay=true;//自动播放this.bgmInnerAudioContext.src=bgm;//音频地址this.bgmInnerAudioContext.loop=true;//循环播放}checkGame(direction,next){letgameover=false;letisSnake=this.snakes.indexOf(next)>-1;letisPollute=this.pollutes.indexOf(next)>-1;//撞到蛇和被污染的地块游戏结束if(isSnake||isPollute){gameover=true;}//撞到边界游戏结束switch(direction){case"up":if(next<0){gameover=true;}break;case"down":if(next>=100){gameover=true;}break;case"left":if(next%10===9){gameover=true;}break;case"right":if(next%10===0){gameover=true;}break;}returngameover;},toWards(direction){letgameover=this.checkGame(direction,next);if(gameover){this.ended=true;this.handleDieVoice()this.bgmInnerAudioContext.pause()//游戏结束暂停背景音乐clearInterval(this.timer);clearInterval(this.boomTimer);}else{//游戏没结束this.snakes.push(next);letnextType=this.blocks[next];this.blocks[next]=2;//如果是空白格if(nextType===0){this.snakes.shift();}else{//如果是虫子格this.handleEatVoice()//吃掉虫子后的音乐this.worms=this.worms.filter((x)=>x!==next);letnextWorm=this.createWorm();this.worms.push(nextWorm);}this.blocks[tail]=0;this.paint();}},}}<script>
首个音乐添加成功其他的也就简单多了 虫子爆炸倒计时也需要爆炸或者gameover后需要清楚倒计时音效stop(下次播放会从头开始) 剩余的不需要清楚音效和循环播放 下面附上剩余的代码
<script>exportdefault{data(){return{bgmInnerAudioContext:null,clockInnerAudioContext:null,}},watch:{boomCount(val){if(val===0){//超过爆炸时间还没吃到,则将虫子格子变成被污染的土地,并且重置爆炸状态,同时生成一只新的虫子:this.handleExplodeVoice()//爆炸的音乐this.clockInnerAudioContext.stop()//清楚倒计时音乐constboomWorm=this.worms.pop();this.pollutes.push(boomWorm);this.blocks[boomWorm]=3;//被污染的地方我们用3表示this.boom=false;this.worms.push(this.createWorm());}}},methods:{//蛇吃到食物后的声音handleEatVoice(){constinnerAudioContext=uni.createInnerAudioContext();innerAudioContext.autoplay=true;innerAudioContext.src=eatVoice;},//虫子污染爆炸后的声音handleExplodeVoice(){constinnerAudioContext=uni.createInnerAudioContext();innerAudioContext.autoplay=true;innerAudioContext.src=explodeVoice;},//游戏背景音乐handleBgmVoice(){this.bgmInnerAudioContext=uni.createInnerAudioContext()this.bgmInnerAudioContext.autoplay=true;this.bgmInnerAudioContext.src=bgm;this.bgmInnerAudioContext.loop=true;},//按钮点击的声音handleClickVoice(){constinnerAudioContext=uni.createInnerAudioContext()innerAudioContext.autoplay=true;innerAudioContext.src=click;},//爆炸倒计时的声音handleClockVoice(){this.clockInnerAudioContext=uni.createInnerAudioContext()this.clockInnerAudioContext.autoplay=true;this.clockInnerAudioContext.src=clock;},//蛇gameover后的声音handleDieVoice(){constinnerAudioContext=uni.createInnerAudioContext()innerAudioContext.autoplay=true;innerAudioContext.src=die;},checkGame(direction,next){letgameover=false;letisSnake=this.snakes.indexOf(next)>-1;letisPollute=this.pollutes.indexOf(next)>-1;//撞到蛇和被污染的地块游戏结束if(isSnake||isPollute){gameover=true;}//撞到边界游戏结束switch(direction){case"up":if(next<0){gameover=true;}break;case"down":if(next>=100){gameover=true;}break;case"left":if(next%10===9){gameover=true;}break;case"right":if(next%10===0){gameover=true;}break;}returngameover;},paint(){this.worms.forEach((x)=>{this.blocks[x]=1;});this.snakes.forEach((x)=>{this.blocks[x]=2;});this.$forceUpdate();},toWards(direction){letgameover=this.checkGame(direction,next);if(gameover){this.ended=true;this.handleDieVoice()this.bgmInnerAudioContext.pause()//游戏结束暂停背景音乐this.clockInnerAudioContext&&this.clockInnerAudioContext.stop()//清楚倒计时音乐clearInterval(this.timer);clearInterval(this.boomTimer);}else{//游戏没结束this.snakes.push(next);letnextType=this.blocks[next];this.blocks[next]=2;//如果是空白格if(nextType===0){this.snakes.shift();}else{//如果是虫子格this.handleEatVoice()//吃掉虫子后的音乐this.worms=this.worms.filter((x)=>x!==next);letnextWorm=this.createWorm();this.worms.push(nextWorm);}this.blocks[tail]=0;this.paint();}},//生成下一只虫子createWorm(){this.boom=false;letblocks=Array.from({length:100},(v,k)=>k);//在不是蛇和被污染的地方生成虫子letrestBlocks=blocks.filter(x=>this.snakes.indexOf(x)<0&&this.pollutes.indexOf(x)<0);letworm=restBlocks[Math.floor(Math.random()*restBlocks.length)];//根据游戏难度,概率产出会爆炸的虫子:this.boom=Math.random()/this.level<0.05;//生成了新虫子说明吃到了那个爆炸的虫子,重置下爆炸if(this.boom){this.boomCount=10;this.boomTimer&&clearInterval(this.boomTimer);this.handleClockVoice()this.boomTimer=setInterval(()=>{this.boomCount–;},1000)}else{this.clockInnerAudioContext&&this.clockInnerAudioContext.stop()clearInterval(this.boomTimer);}returnworm;},}}<script>
源码地址:https://github.com/MothWillion/snake_eat_worm
原文地址:https://juejin.cn/post/7087525655478272008
作者:Sophora
产品猿社区致力收录更多优质的商业产品,给服务商以及软件采购客户提供更多优质的软件产品,帮助开发者变现来实现多方共赢;
日常运营的过程中我们难免会遇到各种版权纠纷等问题,如果您在社区内发现有您的产品未经您授权而被用户提供下载或使用,您可按照我们投诉流程处理,点我投诉;
本文来自用户发布投稿,不代表产品猿立场 ;若对此文有疑问或内容有严重错误,可联系平台客服反馈;
部分产品是用户投稿,可能本文没有提供官方下下载地址或教程,若您看到的内容没有下载入口,您可以在我们产品园商城搜索看开发者是否有发布商品;若您是开发者,也诚邀您入驻商城平台发布的产品,地址:点我进入;
如若转载,请注明出处:https://www.chanpinyuan.cn/28065.html;