游戏演示

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LO1iCMQ9-1655362014052)(https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/ff97fe3fec99448896e1b4175fa96e9d~tplv-k3u1fbpfcp-zoom-in-crop-mark:1956:0:0:0.image?)]

代码结构

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

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

<template><view ref="body" class="content"><view>蛇蛇目前:{{snakes.length}}米长</view><view class="game-field"><!-- 地面板块 --><view class="block"  v-for="(x, i) in blocks" :key="i"></view></view><view v-show="!started || ended" class="game-board-wrap"><view v-show="!started" class="game-board"><view class="title">选择游戏难度</view><radio-group name="radio" @change="bindLevelChange"><label class="label"><radio value="1" :checked="level==1" /><text>简单模式</text></label><label class="label"><radio value="2" :checked="level==2" /><text>正常模式</text></label><label class="label"><radio value="3" :checked="level==3" /><text>困难模式</text></label><label class="label"><radio value="4" :checked="level==4" /><text>地狱模式</text></label></radio-group><button type="primary" @click="start">开始游戏</button></view><view v-show="ended" class="settle-board"><view class="title">游戏结束</view><view class="result">您的蛇蛇达到了{{snakes.length}}米</view><view class="btns"><button type="primary" @click="reStart">再次挑战</button><button type="primary" plain @click="rePick">重选难度</button></view></view></view></view>
</template>
<script>
export default {data() {return {blocks: [], // 板块worms: [], // 虫子snakes: [0, 1, 2, 3], // 蛇身direction: "right", // 蛇移动方向};},onLoad() {this.initGame();},methods: {initGame() {this.blocks = new Array(100).fill(0); // 生成100个地面板块this.worms = [Math.floor(Math.random() * 96) + 4]; // 随机生成虫子this.snakes = [0, 1, 2, 3]; // 初始化蛇身位置}}
}
</script>

渲染蛇身

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

<template><view class="game-field"><view class="block" :style="`background-image: ${bg(x, i)}" v-for="(x, i) in blocks" :key="i"></view></view>
</template>
<script>
import worm from "worm.png";
import snakeBody from "snake_body.png";
import snakeHead from "snake_head.png";
import snakeTail from "snake_tail.png";
import polluteBlock from "pollute.png";
import wormBoom from "worm_4.png";
export default {methods: {bg(type, index) {let bg = "";switch (type) {case 0: // 地板bg = "unset";break;case 1: // 虫子if (this.boom) {bg = `url(${wormBoom})`;} else {bg = `url(${worm})`;}break;case 2: // 蛇let head = this.snakes[this.snakes.length - 1];let tail = this.snakes[0];if (index === head) {bg = `url(${snakeHead})`;} else if (index === tail) {bg = `url(${snakeTail})`;} else {bg = `url(${snakeBody})`;}break;case 3: // 污染的地块bg = `url(${polluteBlock})`;break;}return bg;},}
}
</scipt>

控制蛇的方向

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

<template>
<view ref="body" class="content" @keyup.left="bindLeft" @keyup.right="bindRight" @keyup.down="bindDown"
@keyup.up="bindUp" @touchstart="handleTouchStart" @touchmove="handleTouchMove"><view>蛇蛇目前:{{snakes.length}}米长</view><view class="game-field"><view class="block" :style="`background-image: ${bg(x, i)}; v-for="(x, i) in blocks" :key="i"></view></view>
</view>
</template>
<script>export default {data(){return {direction: "right",started: false, // 游戏开始了ended: false, // 游戏结束了level: 1, // 游戏难度lastX: 0,lastY: 0,}},onLoad() {this.initGame();},methods:{initGame() {this.blocks = new Array(100).fill(0); // 生成100个地面板块this.worms = [Math.floor(Math.random() * 96) + 4]; // 随机生成虫子this.snakes = [0, 1, 2, 3]; // 初始化蛇身位置document.onkeydown = (e) => {switch (e.keyCode) { // 获取当前按下键盘键的编码case 37: // 按下左箭头键this.bindLeft();break;case 39: // 按下右箭头键this.bindRight();break;case 38: // 按下上箭头键if (!this.started) {this.level--;} else {this.bindUp();}break;case 40: // 按下下箭头键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) {let lastX = e.touches[0].pageX; // 移动的x轴坐标let lastY = e.touches[0].pageY; // 移动的y轴坐标let touchX = lastX - this.lastX;let touchY = lastY - this.lastYif (Math.abs(touchX) > Math.abs(touchY)) {if (touchX < 0) {if(this.direction === "right") return;this.direction = 'left'} else if (touchX > 0) {if(this.direction === "left") return;this.direction = 'right'}} else {if (touchY < 0) {if(this.direction === "down") return;this.direction = 'up'} else if (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>
import bgm from 'bgm.mp3';
export default {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>
import bgm from 'bgm.mp3';
export default {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) {let gameover = false;let isSnake = this.snakes.indexOf(next) > -1;let isPollute = 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;}return gameover;},toWards(direction) {let gameover = 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);let nextType = this.blocks[next];this.blocks[next] = 2;// 如果是空白格if (nextType === 0) {this.snakes.shift();} else {// 如果是虫子格this.handleEatVoice() // 吃掉虫子后的音乐this.worms = this.worms.filter((x) => x !== next);let nextWorm = this.createWorm();this.worms.push(nextWorm);}this.blocks[tail] = 0;this.paint();}},}
}
<script>

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

<script>
export default {data() {return {bgmInnerAudioContext:null,clockInnerAudioContext:null,}},watch: {boomCount(val) {if (val === 0) {// 超过爆炸时间还没吃到,则将虫子格子变成被污染的土地,并且重置爆炸状态,同时生成一只新的虫子:this.handleExplodeVoice() // 爆炸的音乐this.clockInnerAudioContext.stop() // 清楚倒计时音乐const boomWorm = this.worms.pop();this.pollutes.push(boomWorm);this.blocks[boomWorm] = 3; // 被污染的地方我们用3表示this.boom = false;this.worms.push(this.createWorm());}}},methods:{// 蛇吃到食物后的声音handleEatVoice() {const innerAudioContext = uni.createInnerAudioContext();innerAudioContext.autoplay = true;innerAudioContext.src = eatVoice;},// 虫子污染爆炸后的声音handleExplodeVoice(){const innerAudioContext = 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() {const innerAudioContext = uni.createInnerAudioContext()innerAudioContext.autoplay = true;innerAudioContext.src= click;},// 爆炸倒计时的声音handleClockVoice() {this.clockInnerAudioContext = uni.createInnerAudioContext()this.clockInnerAudioContext.autoplay = true;this.clockInnerAudioContext.src= clock;},// 蛇gameover后的声音handleDieVoice() {const innerAudioContext = uni.createInnerAudioContext()innerAudioContext.autoplay = true;innerAudioContext.src= die;},checkGame(direction, next) {let gameover = false;let isSnake = this.snakes.indexOf(next) > -1;let isPollute = 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;}return gameover;},paint() {this.worms.forEach((x) => {this.blocks[x] = 1;});this.snakes.forEach((x) => {this.blocks[x] = 2;});this.$forceUpdate();},toWards(direction) {let gameover = 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);let nextType = this.blocks[next];this.blocks[next] = 2;// 如果是空白格if (nextType === 0) {this.snakes.shift();} else {// 如果是虫子格this.handleEatVoice() // 吃掉虫子后的音乐this.worms = this.worms.filter((x) => x !== next);let nextWorm = this.createWorm();this.worms.push(nextWorm);}this.blocks[tail] = 0;this.paint();}},// 生成下一只虫子createWorm() {this.boom = false;let blocks = Array.from({length: 100}, (v, k) => k);// 在不是蛇和被污染的地方生成虫子let restBlocks = blocks.filter(x => this.snakes.indexOf(x) < 0 && this.pollutes.indexOf(x) < 0);let worm = 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);}return worm;},}
}
<script>

uniapp实现贪吃蛇小游戏相关推荐

  1. 100行代码,使用 Pygame 制作一个贪吃蛇小游戏!

    作者 | 周萝卜 来源 | 萝卜大杂烩 相信我们大家都玩过贪吃蛇游戏,今天我们就从头一起来写一个贪吃蛇小游戏,只需要100多行的代码就完成了. 用到的 Pygame 函数 贪吃蛇小游戏用到的函数 功能 ...

  2. Python实现贪吃蛇小游戏(双人模式)

    这篇文章主要为大家详细介绍了Python实现双人模式的贪吃蛇小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 简单用py写了一个贪吃蛇游戏,有单人.双人模式,比较简 ...

  3. GUI编程---贪吃蛇小游戏开发

    学习链接:狂神说Java–1小时开发贪吃蛇小游戏 ①初识理论 帧:时间片足够小=>就是动画,1秒30帧.连起来是动画,拆开就是静态的图片! 键盘监听 定时器Timer 游戏图片素材:GUI之贪吃 ...

  4. python 贪吃蛇小游戏代码_10分钟再用Python编写贪吃蛇小游戏

    Python编写贪吃蛇 前不久我们公众号发布了一篇C++编写贪吃蛇小游戏的推文,反响空前.看来大家对这类简单易上手小游戏还是很喜爱的. 恰逢2018年IEEE Spectrum编程语言排行榜新鲜出炉, ...

  5. python100行代码程序-100行python代码,轻松完成贪吃蛇小游戏

    大家小时候都玩过贪吃蛇吧?小编小时候可喜欢拿爸妈的手机玩了,厉害着呢!今天,小编就来用100行代码实现一个简易版的贪吃蛇.在网上,贪吃蛇教程蛮多的,但要安装蛮多库的,而且也不够清晰,今天的代码比较短, ...

  6. python小游戏编程实例-10分钟教你用Python写一个贪吃蛇小游戏,适合练手项目

    另外要注意:光理论是不够的.这里顺便总大家一套2020最新python入门到高级项目实战视频教程,可以去小编的Python交流.裙 :七衣衣九七七巴而五(数字的谐音)转换下可以找到了,还可以跟老司机交 ...

  7. python100行代码-怎样写贪吃蛇小游戏?用100行python代码轻松解决!

    大家小时候都玩过贪吃蛇吧?小编小时候可喜欢拿爸妈的手机玩了,厉害着呢!今天,小编就来用100行代码实现一个简易版的贪吃蛇.在网上,贪吃蛇教程蛮多的,但要安装蛮多库的,而且也不够清晰,今天的代码比较短, ...

  8. python编程小游戏-10分钟用Python编写一个贪吃蛇小游戏,简单

    贪吃蛇,大家应该都玩过.小编当初第一次接触贪吃蛇的时候 ,还是能砸核桃的诺基亚上,当时玩的不亦乐乎.今天,我们用Python编程一个贪吃蛇游戏,下面我们先看看效果: 好了,先介绍一个思路 所有的游戏最 ...

  9. 再来一次的C语言贪吃蛇小游戏(三)

    8.游戏的不同界面 为了便于实现主要功能,之前我们所有的状态控制都是放在游戏中,但实际上我们应该把这些状态控制抽离出来,通过菜单来控制,以便在不同游戏界面间切换. 菜单界面 游戏界面 排行榜 游戏结束 ...

  10. 基于stm32、0.96寸OLED实现的贪吃蛇小游戏(详细源码注释)

    简介:本实验基于stm32最小系统.0.96寸OLED(68*128)和摇杆实现一个经典的贪吃蛇小游戏.项目源码地址:点击下载. 硬件设计: 普通摇杆,0.96寸OLED 单色屏幕(SPI协议通讯), ...

最新文章

  1. C/MFC如何获得应用程序当前路径(整理)
  2. AlwaysUp使用方法
  3. 「PowerBI」分析服务多维数据结构重回关系数据库的一大绝招
  4. 【2018.4.21】模拟赛之四-ssl2405 巧克力【实际上是模拟】
  5. 开源软件加密授权方案_身份验证和授权作为开源解决方案服务
  6. oracle之数据处理之约束1
  7. 遇到网络问题你是怎么解决的?
  8. 动力环境监控系统论文_机房动力环境监控系统方案
  9. telnet命令 date命令
  10. bzoj1975 [Sdoi2010]魔法猪学院 a*+堆
  11. 和整数相乘_人教版五年级上册第1单元《小数乘整数》课件及同步练习
  12. ViewPager——PagerTitleStrip和PagerTabStrip
  13. python 数据比对 函数_用python比对csv文件中的数据
  14. Amazon S3 API
  15. 算法学习--二叉查找树
  16. 第1节 flume:15、flume案例二,通过自定义拦截器实现数据的脱敏
  17. IntelliJ Idea14 创建Maven多模块项目,多继承,热部署配置总结(一)
  18. windows下php mongodb 安装配置使用查询
  19. FutureTask 源码解析
  20. cesium导入kml文件

热门文章

  1. 禅道bin目录没有php,/opt/zbox/zbox:行3: /opt/zbox/bin/php: 没有那个文件或目录
  2. 命令查看计算机出厂时间,Check cosmetics or perfume production date and shelf life by the batch code....
  3. 【转载】JavaWeb之ssm框架搭建中遇到的问题
  4. 光纤激光器输出激光参数的一些概念及运算
  5. 旧瓶装新酒——memcache作为DRDOS反射放大器
  6. Python常见问题 - pip报错 ValueError: Unable to find resource t32.exe in package pip._vendor.distlib
  7. 基于微信小程序的图书馆管理系统设计与实现(论文+程序设计源码+数据库文件)
  8. 计算机行业的薪资真的有那么高吗?讲真,有的一毕业就失业,有的一毕业就拿 20k+
  9. Reactor(反应器)模式
  10. 北京师范大学远程教育计算机考试时间,北京师范大学网络教育2020年报名截止时间...