聊聊如何利用uniapp开发一个贪吃蛇小游戏!

 3299

如何利用uniapp开发一个贪吃蛇小游戏?下面本篇文章就手把手带大家在uniapp中实现贪吃蛇小游戏,希望对大家有所帮助!


聊聊如何利用uniapp开发一个贪吃蛇小游戏!


第一次玩贪吃蛇还隐约记得是?️后父亲给我玩的第一个游戏

该小游戏使用uniapp开发

前置详细内容就不细说了详细看:https://juejin.cn/post/7085727363547283469#heading-14


游戏演示


聊聊如何利用uniapp开发一个贪吃蛇小游戏!


代码结构

详细代码结构如果需要请到github查看

主要分为:开始游戏、地块、蛇身、虫子、污染地块,游戏音效

  1. <template>
  2.     <view ref="body" class="content">
  3.         <view>蛇蛇目前:{{snakes.length}}米长</view>
  4.         <view class="game-field">
  5.                 <!-- 地面板块 -->
  6.           <view class="block"  v-for="(x, i) in blocks" :key="i"></view>
  7.         </view>
  8.                     <view v-show="!started || ended" class="game-board-wrap">
  9.                         <view v-show="!started" class="game-board">
  10.                             <view class="title">选择游戏难度</view>
  11.                             <radio-group name="radio" @change="bindLevelChange">
  12.                                 <label class="label">
  13.                                     <radio value="1" :checked="level==1" /><text>简单模式</text>
  14.                                 </label>
  15.                                 <label class="label">
  16.                                     <radio value="2" :checked="level==2" /><text>正常模式</text>
  17.                                 </label>
  18.                                 <label class="label">
  19.                                     <radio value="3" :checked="level==3" /><text>困难模式</text>
  20.                                 </label>
  21.                                 <label class="label">
  22.                                     <radio value="4" :checked="level==4" /><text>地狱模式</text>
  23.                                 </label>
  24.                             </radio-group>
  25.                             <button type="primary" @click="start">开始游戏</button>
  26.                         </view>
  27.             <view v-show="ended" class="settle-board">
  28.                             <view class="title">游戏结束</view>
  29.                             <view class="result">您的蛇蛇达到了{{snakes.length}}米</view>
  30.                             <view class="btns">
  31.                                 <button type="primary" @click="reStart">再次挑战</button>
  32.                                 <button type="primary" plain @click="rePick">重选难度</button>
  33.                             </view>
  34.             </view>
  35.         </view>
  36.     </view>
  37. </template>
  38. <script>
  39. export default {
  40.     data() {
  41.             return {
  42.                 blocks: [], // 板块
  43.                 worms: [], // 虫子
  44.                 snakes: [0, 1, 2, 3], // 蛇身
  45.                 direction: "right", // 蛇移动方向
  46.             };
  47.     },
  48.     onLoad() {
  49.         this.initGame();
  50.     },
  51.     methods: {
  52.         initGame() {
  53.             this.blocks = new Array(100).fill(0); // 生成100个地面板块
  54.             this.worms = [Math.floor(Math.random() * 96) + 4]; // 随机生成虫子
  55.             this.snakes = [0, 1, 2, 3]; // 初始化蛇身位置
  56.         }
  57.     }
  58. }
  59. </script>


渲染蛇身

给我们的蛇穿上他的外衣 蛇身的渲染根据snakes(里边放着蛇的身体)来匹配地面板块的索引 从而找到对应的格格并修改背景图来渲染蛇身 蛇头和蛇尾就是取snakes第0位和最后一位 并找到对应的格格修改当前背景图

  1. <template>
  2.     <view class="game-field">
  3.         <view class="block" :style="`background-image: ${bg(x, i)}" v-for="(x, i) in blocks" :key="i">
  4.         </view>
  5.     </view>
  6. </template>
  7. <script>
  8. import worm from "worm.png";
  9. import snakeBody from "snake_body.png";
  10. import snakeHead from "snake_head.png";
  11. import snakeTail from "snake_tail.png";
  12. import polluteBlock from "pollute.png";
  13. import wormBoom from "worm_4.png";
  14. export default {
  15.     methods: {
  16.         bg(type, index) {
  17.             let bg = "";
  18.             switch (type) {
  19.                 case 0: // 地板
  20.                     bg = "unset";
  21.                     break;
  22.                 case 1: // 虫子
  23.                     if (this.boom) {
  24.                             bg = `url(${wormBoom})`;
  25.                     } else {
  26.                             bg = `url(${worm})`;
  27.                     }
  28.                     break;
  29.                 case 2: // 蛇
  30.                     let head = this.snakes[this.snakes.length - 1];
  31.                     let tail = this.snakes[0];
  32.                     if (index === head) {
  33.                             bg = `url(${snakeHead})`;
  34.                     } else if (index === tail) {
  35.                             bg = `url(${snakeTail})`;
  36.                     } else {
  37.                             bg = `url(${snakeBody})`;
  38.                     }
  39.                     break;
  40.                 case 3: // 污染的地块
  41.                     bg = `url(${polluteBlock})`;
  42.                     break;
  43.             }
  44.             return bg;
  45.         },
  46.     }
  47. }
  48. </scipt>


控制蛇的方向

控制蛇的方向pc端我们通过监听键盘事件找到对应的键盘键的编码上下左右来改变蛇的方向 而手机端我们通过touch时间手指触摸点及滑动点的XY轴值来判断蛇的方向

  1. <template>
  2. <view ref="body" class="content" @keyup.left="bindLeft" @keyup.right="bindRight" @keyup.down="bindDown"
  3. @keyup.up="bindUp" @touchstart="handleTouchStart" @touchmove="handleTouchMove">
  4.     <view>蛇蛇目前:{{snakes.length}}米长</view>
  5.     <view class="game-field">
  6.         <view class="block" :style="`background-image: ${bg(x, i)}; v-for="(xiin blocks" :key="i"></view>
  7.     </view>
  8. </view>
  9. </template>
  10. <script>
  11.     export default {
  12.         data(){
  13.             return {
  14.                 direction: "right",
  15.                 started: false, // 游戏开始了
  16.                 ended: false, // 游戏结束了
  17.                 level: 1, // 游戏难度
  18.                 lastX: 0,
  19.                 lastY: 0,
  20.             }
  21.         },
  22.         onLoad() {
  23.             this.initGame();
  24.         },
  25.         methods:{
  26.             initGame() {
  27.                 this.blocks = new Array(100).fill(0); // 生成100个地面板块
  28.                 this.worms = [Math.floor(Math.random() * 96) + 4]; // 随机生成虫子
  29.                 this.snakes = [0, 1, 2, 3]; // 初始化蛇身位置
  30.                 document.onkeydown = (e) => {
  31.                     switch (e.keyCode) { // 获取当前按下键盘键的编码
  32.                         case 37: // 按下左箭头键
  33.                             this.bindLeft();
  34.                             break;
  35.                         case 39: // 按下右箭头键
  36.                             this.bindRight();
  37.                             break;
  38.                         case 38: // 按下上箭头键
  39.                             if (!this.started) {
  40.                                     this.level--;
  41.                             } else {
  42.                                     this.bindUp();
  43.                             }
  44.                             break;
  45.                         case 40: // 按下下箭头键
  46.                             if (!this.started) {
  47.                                     this.level++;
  48.                             } else {
  49.                                     this.bindDown();
  50.                             }
  51.                             break;
  52.                     }
  53.                 }
  54.             },
  55.             handleTouchStart(e) {
  56.                 // 手指开始位置
  57.                 this.lastX = e.touches[0].pageX;
  58.                 this.lastY = e.touches[0].pageY;
  59.             },
  60.             handleTouchMove(e) {
  61.                 let lastX = e.touches[0].pageX; // 移动的x轴坐标
  62.                 let lastY = e.touches[0].pageY; // 移动的y轴坐标
  63.  
  64.                 let touchX = lastX - this.lastX;
  65.                 let touchY = lastY - this.lastY
  66.                 if (Math.abs(touchX) > Math.abs(touchY)) {
  67.                 if (touchX < 0) {
  68.                     if(this.direction === "right") return;
  69.                     this.direction = 'left'
  70.                     } else if (touchX > 0) {
  71.                         if(this.direction === "left") return;
  72.                         this.direction = 'right'
  73.                     }
  74.                 } else {
  75.                     if (touchY < 0) {
  76.                         if(this.direction === "down") return;
  77.                         this.direction = 'up'
  78.                     } else if (touchY > 0) {
  79.                         if(this.direction === "up") return;
  80.                         this.direction = 'down'
  81.                     }
  82.                 }
  83.                 this.lastX = lastX;
  84.                 this.lastY = lastY;
  85.             },
  86.             bindUp() {
  87.                 if (this.direction === "down") return;
  88.                 this.direction = "up";
  89.             },
  90.             bindDown() {
  91.                 if (this.direction === "up") return;
  92.                 this.direction = "down";
  93.             },
  94.             bindLeft() {
  95.                 if (this.direction === "right") return;
  96.                 this.direction = "left";
  97.             },
  98.             bindRight() {
  99.                 if (this.direction === "left") return;
  100.                 this.direction = "right";
  101.             },
  102.         }
  103.     }
  104. </script>


给贪吃蛇添加音效

添加游戏音效游戏代入感就强了很多 现在我们要给蛇加上背景音乐、点击交互音乐、蛇隔儿屁的音乐、蛇吃掉食物的音乐、虫子爆炸倒计时的音乐和虫子爆炸的音乐

先给添加上背景音乐 总有刁民可以玩到地图满为止 背景音乐的话要loop播放 我们只需要 使用uni.createInnerAudioContext来创建并返回内部 audio 上下文 innerAudioContext 对象 拿到音乐的路径并且设置自动播放

  1. <script>
  2. import bgm from 'bgm.mp3';
  3. export default {
  4.     data(){
  5.         return {
  6.             bgmInnerAudioContext:null,
  7.         }
  8.     },
  9.     methods:{
  10.         start() { // 开始游戏
  11.             this.initGame();
  12.             this.handleBgmVoice()
  13.         },
  14.         handleBgmVoice() {
  15.             // 背景音乐
  16.             this.bgmInnerAudioContext = uni.createInnerAudioContext() // 创建上下文
  17.             this.bgmInnerAudioContext.autoplay = true; // 自动播放
  18.             this.bgmInnerAudioContext.src= bgm; // 音频地址
  19.             this.bgmInnerAudioContext.loop = true; // 循环播放
  20.         }
  21.     }
  22. }
  23. <script>

背景音乐确实响起来了 蛇gameover后还一直响 顿时我听着就不耐烦 这时我们在蛇gameover后暂停背景音乐pause音乐会暂停而不会清楚

  1. <script>
  2. import bgm from 'bgm.mp3';
  3. export default {
  4.     data(){
  5.         return {
  6.             bgmInnerAudioContext:null,
  7.         }
  8.     },
  9.     methods:{
  10.         start() { // 开始游戏
  11.             this.initGame();
  12.             this.handleBgmVoice()
  13.         },
  14.         handleBgmVoice() {
  15.             // 背景音乐
  16.             this.bgmInnerAudioContext = uni.createInnerAudioContext() // 创建上下文
  17.             this.bgmInnerAudioContext.autoplay = true; // 自动播放
  18.             this.bgmInnerAudioContext.src= bgm; // 音频地址
  19.             this.bgmInnerAudioContext.loop = true; // 循环播放
  20.         }
  21.         checkGame(direction, next) {
  22.             let gameover = false;
  23.             let isSnake = this.snakes.indexOf(next) > -1;
  24.             let isPollute = this.pollutes.indexOf(next) > -1;
  25.             // 撞到蛇和被污染的地块游戏结束
  26.             if (isSnake || isPollute) {
  27.                 gameover = true;
  28.             }
  29.             // 撞到边界游戏结束
  30.             switch (direction) {
  31.                 case "up":
  32.                     if (next < 0) {
  33.                             gameover = true;
  34.                     }
  35.                     break;
  36.                 case "down":
  37.                     if (next >= 100) {
  38.                             gameover = true;
  39.                     }
  40.                     break;
  41.                 case "left":
  42.                     if (next % 10 === 9) {
  43.                             gameover = true;
  44.                     }
  45.                     break;
  46.                 case "right":
  47.                     if (next % 10 === 0) {
  48.                             gameover = true;
  49.                     }
  50.                     break;
  51.             }
  52.             return gameover;
  53.         },
  54.         toWards(direction) {
  55.             let gameover = this.checkGame(direction, next);
  56.             if (gameover) {
  57.                 this.ended = true;
  58.                 this.handleDieVoice()
  59.                 this.bgmInnerAudioContext.pause() // 游戏结束 暂停背景音乐
  60.                 clearInterval(this.timer);
  61.                 clearInterval(this.boomTimer);
  62.             } else {
  63.                 // 游戏没结束
  64.                 this.snakes.push(next);
  65.                 let nextType = this.blocks[next];
  66.                 this.blocks[next] = 2;
  67.                 // 如果是空白格
  68.                 if (nextType === 0) {
  69.                     this.snakes.shift();
  70.                 } else {
  71.                     // 如果是虫子格
  72.                     this.handleEatVoice() // 吃掉虫子后的音乐
  73.                     this.worms = this.worms.filter((x) => x !== next);
  74.                     let nextWorm = this.createWorm();
  75.                     this.worms.push(nextWorm);
  76.                 }
  77.                 this.blocks[tail] = 0;
  78.                 this.paint();
  79.             }
  80.         },
  81.     }
  82. }
  83. <script>

首个音乐添加成功其他的也就简单多了 虫子爆炸倒计时也需要爆炸或者gameover后需要清楚倒计时音效stop(下次播放会从头开始) 剩余的不需要清楚音效和循环播放 下面附上剩余的代码

  1. <script>
  2. export default {
  3.     data() {
  4.         return {
  5.              bgmInnerAudioContext:null,
  6.              clockInnerAudioContext:null,
  7.         }
  8.     },
  9.     watch: {
  10.         boomCount(val) {
  11.             if (val === 0) {
  12.                 // 超过爆炸时间还没吃到,则将虫子格子变成被污染的土地,并且重置爆炸状态,同时生成一只新的虫子:
  13.                 this.handleExplodeVoice() // 爆炸的音乐
  14.                 this.clockInnerAudioContext.stop() // 清楚倒计时音乐
  15.                 const boomWorm = this.worms.pop();
  16.                 this.pollutes.push(boomWorm);
  17.                 this.blocks[boomWorm] = 3; // 被污染的地方我们用3表示
  18.                 this.boom = false;
  19.                 this.worms.push(this.createWorm());
  20.             }
  21.         }
  22.     },
  23.     methods:{
  24.         // 蛇吃到食物后的声音
  25.         handleEatVoice() {
  26.             const innerAudioContext = uni.createInnerAudioContext();
  27.             innerAudioContext.autoplay = true;
  28.             innerAudioContext.src = eatVoice;
  29.         },
  30.         // 虫子污染爆炸后的声音
  31.         handleExplodeVoice(){
  32.             const innerAudioContext = uni.createInnerAudioContext();
  33.             innerAudioContext.autoplay = true;
  34.             innerAudioContext.src = explodeVoice;
  35.         },
  36.         // 游戏背景音乐
  37.         handleBgmVoice() {
  38.             this.bgmInnerAudioContext = uni.createInnerAudioContext()
  39.             this.bgmInnerAudioContext.autoplay = true;
  40.             this.bgmInnerAudioContext.src= bgm;
  41.             this.bgmInnerAudioContext.loop = true;
  42.         },
  43.         // 按钮点击的声音
  44.         handleClickVoice() {
  45.             const innerAudioContext = uni.createInnerAudioContext()
  46.             innerAudioContext.autoplay = true;
  47.             innerAudioContext.src= click;
  48.         },
  49.         // 爆炸倒计时的声音
  50.         handleClockVoice() {
  51.             this.clockInnerAudioContext = uni.createInnerAudioContext()
  52.             this.clockInnerAudioContext.autoplay = true;
  53.             this.clockInnerAudioContext.src= clock;
  54.         },
  55.         // 蛇gameover后的声音
  56.         handleDieVoice() {
  57.             const innerAudioContext = uni.createInnerAudioContext()
  58.             innerAudioContext.autoplay = true;
  59.             innerAudioContext.src= die;
  60.         },
  61.         checkGame(direction, next) {
  62.             let gameover = false;
  63.             let isSnake = this.snakes.indexOf(next) > -1;
  64.             let isPollute = this.pollutes.indexOf(next) > -1;
  65.             // 撞到蛇和被污染的地块游戏结束
  66.             if (isSnake || isPollute) {
  67.                 gameover = true;
  68.             }
  69.             // 撞到边界游戏结束
  70.             switch (direction) {
  71.                 case "up":
  72.                     if (next < 0) {
  73.                             gameover = true;
  74.                     }
  75.                     break;
  76.                 case "down":
  77.                     if (next >= 100) {
  78.                             gameover = true;
  79.                     }
  80.                     break;
  81.                 case "left":
  82.                     if (next % 10 === 9) {
  83.                             gameover = true;
  84.                     }
  85.                     break;
  86.                 case "right":
  87.                     if (next % 10 === 0) {
  88.                             gameover = true;
  89.                     }
  90.                     break;
  91.             }
  92.             return gameover;
  93.         },
  94.         paint() {
  95.             this.worms.forEach((x) => {
  96.                 this.blocks[x] = 1;
  97.             });
  98.             this.snakes.forEach((x) => {
  99.                 this.blocks[x] = 2;
  100.             });
  101.             this.$forceUpdate();
  102.         },
  103.         toWards(direction) {
  104.             let gameover = this.checkGame(direction, next);
  105.             if (gameover) {
  106.                 this.ended = true;
  107.                 this.handleDieVoice()
  108.                 this.bgmInnerAudioContext.pause() // 游戏结束 暂停背景音乐
  109.                 this.clockInnerAudioContext && this.clockInnerAudioContext.stop() // 清楚倒计时音乐
  110.                 clearInterval(this.timer);
  111.                 clearInterval(this.boomTimer);
  112.             } else {
  113.                 // 游戏没结束
  114.                 this.snakes.push(next);
  115.                 let nextType = this.blocks[next];
  116.                 this.blocks[next] = 2;
  117.                 // 如果是空白格
  118.                 if (nextType === 0) {
  119.                     this.snakes.shift();
  120.                 } else {
  121.                     // 如果是虫子格
  122.                     this.handleEatVoice() // 吃掉虫子后的音乐
  123.                     this.worms = this.worms.filter((x) => x !== next);
  124.                     let nextWorm = this.createWorm();
  125.                     this.worms.push(nextWorm);
  126.                 }
  127.                 this.blocks[tail] = 0;
  128.                 this.paint();
  129.             }
  130.         },
  131.         // 生成下一只虫子
  132.         createWorm() {
  133.             this.boom = false;
  134.             let blocks = Array.from({
  135.                     length: 100
  136.             }, (v, k) => k);
  137.             // 在不是蛇和被污染的地方生成虫子
  138.             let restBlocks = blocks.filter(=> this.snakes.indexOf(x) < 0 && this.pollutes.indexOf(x) < 0);
  139.             let worm = restBlocks[Math.floor(Math.random() * restBlocks.length)];
  140.             // 根据游戏难度,概率产出会爆炸的虫子:
  141.             this.boom = Math.random() / this.level < 0.05;
  142.             // 生成了新虫子说明吃到了那个爆炸的虫子,重置下爆炸
  143.             if (this.boom) {
  144.                 this.boomCount = 10;
  145.                 this.boomTimer && clearInterval(this.boomTimer);
  146.                 this.handleClockVoice()
  147.                 this.boomTimer = setInterval(() => {
  148.                         this.boomCount--;
  149.                 }, 1000)
  150.             } else {
  151.                 this.clockInnerAudioContext && this.clockInnerAudioContext.stop()
  152.                 clearInterval(this.boomTimer);
  153.             }
  154.             return worm;
  155.         },
  156.     }
  157. }
  158. <script>

源码地址:https://github.com/MothWillion/snake_eat_worm

原文地址:https://juejin.cn/post/7087525655478272008

作者:Sophora


本文网址:https://www.zztuku.com/index.php/detail-12061.html
站长图库 - 聊聊如何利用uniapp开发一个贪吃蛇小游戏!
申明:本文转载于《掘金社区》,如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐