我儿时的小梦想-开发贪食蛇小游戏

前言

记得读书的年代,有一款手机游戏叫贪食蛇,之前的手机就几款游戏,同窗们都废寝忘餐地玩,就像如今玩王者荣耀同样火。只不过穷人的孩子没有手机,看着人家玩得不亦乐乎o(╥﹏╥)o,就立志之后直接搞一个出来本身玩,哈哈 笔者以前用原生JavaScript也写过一次贪食蛇,,虽然就几个动做,但原生JavaScript能够写出一百多行代码, 如今笔者用vue再从新写一次,vue是数据驱动的因此编程思惟要转变一下,但代码量减小不少。javascript

需求分析

  • 建立场景 - 游戏场景让小蛇在这活动
  • 建立蛇 - 建立蛇的坐标位置信息
  • 移动蛇 - 蛇上下左右方向自动移动
  • 食物 - 建立食物随机坐标位置信息、判断蛇是否吃到食物
  • 食本身 - 判断蛇是否吃到本身后游戏结束
  • 出界处理 - 判断蛇撞墙后游戏结束

建立场景

  1. html和css很简单就几行东西就建立了游戏的场景
<template>
    <div class="snakebox" :style="{width:boxWidth+'px',height: boxheight + 'px'}"> <div class="snake"></div> <div class="shiwu"></div> </div>
</template>
<script> export default { name: 'snake', data() { return { boxWidth: 500, //场景宽度 boxheight: 500,//场景高度 } } } </script>
<style scoped> .snakebox { position: relative; margin: 0 auto; background: black; transition-duration: 500ms; transition-timing-function: ease-out; overflow: hidden; } .snake { background: red; position: absolute; } .shiwu { position: absolute; background: #0099FF; } </style>

复制代码

建立蛇和食物

  1. 建立蛇 snakeAry变量表明蛇坐标信息,将变量绑定到模板上
  2. 建立食物 foodInfo变量表明食物随机的坐标信息,将食物坐标信息绑定到模板上
<template>
    <div class="snakebox" :style="{width:boxWidth+'px',height: boxheight + 'px'}"> <div class="snake":style="{left : item.x*snakeWidth +'px' , top:item.y*snakeHeight +'px', width:snakeWidth+ 'px' , height: snakeHeight+'px'}" v-for="(item,index) in snakeAry" :key="index"></div> <div class="shiwu"></div> </div>
</template>
<script> export default { name: 'snake', data() { return { boxWidth: 500, //场景宽度 boxheight: 500,//场景高度 snakeAry: [ {x: 2, y: 1}, //蛇头 {x: 3, y: 1}, //蛇身 {x: 4, y: 1}], // 蛇尾 foodInfo: null, // 食物坐标信息 } }, created() { this.randomFood() }, methods:{ randomFood() { this.foodInfo = { x: Math.floor(Math.random() * this.boxWidth / this.snakeWidth), y: Math.floor(Math.random() * this.boxheight / this.snakeHeight) } }, } } </script>

复制代码

移动蛇、食本身、碰到食物 、出界

  1. 变量 direction 是肯定蛇移动的方向,默认向右移动
  2. 监听上下左右键盘事件改变direction的值
  3. 建立蛇身移动函数 moveSnake(),蛇移动函数无非改变蛇的坐标值,食本身、碰到食、出界处理也一一加上注释
  4. 增长定时器让蛇本身动起来
export default {
        name: 'snake',
        data() {
            return {
                boxWidth: 500, //场景宽度
                boxheight: 500,//场景高度
                snakeWidth: 20, //蛇身宽度
                snakeHeight: 20,//蛇身宽度
                direction: 'right',//蛇移动方向
                snakeAry: [
                    {x: 2, y: 1}, //蛇头
                    {x: 3, y: 1}, //蛇身
                    {x: 4, y: 1}], // 蛇尾
                foodInfo: null, // 食物坐标信息
                timer: null,//小蛇本身动起来定时器
            }
        },
        created() {
            this.randomFood()
            this.timerfun()
        },
        mounted() {
            document.body.addEventListener('keydown', (ev) => {
                ev.preventDefault()
                switch (ev.key) {
                    case  'ArrowUp':
                        this.direction = 'up'
                        break
                    case  'ArrowDown':
                        this.direction = 'down'
                        break
                    case  'ArrowLeft':
                        this.direction = 'left'
                        break
                    case  'ArrowRight':
                        this.direction = 'right'
                        break
                }
            })
        },

        methods: {
            timerfun() {
                this.timer = setInterval(() => {
                    this.moveSnake()
                }, 100)
            },
            randomFood() {
                this.foodInfo = {
                    x: Math.floor(Math.random() * this.boxWidth / this.snakeWidth),
                    y: Math.floor(Math.random() * this.boxheight / this.snakeHeight)
                }
            },
            moveSnake() {
                const {x: sx, y: sy} = this.foodInfo
                let body = this.snakeAry
                //蛇身 蛇尾用逆向循环改变一下位置
                for (let i = body.length - 1; i > 0; i--) {
                    body[i].x = body[i - 1].x
                    body[i].y = body[i - 1].y
                }
                //改变蛇头坐标信息
                if (this.direction === 'right') body[0].x += 1
                if (this.direction === 'down') body[0].y += 1
                if (this.direction === 'up') body[0].y -= 1
                if (this.direction === 'left') body[0].x -= 1


                // 处理碰到本身的状况
                if (body.length >= 4) {
                    for (let index = 4; index < body.length; index++) {
                        if (body[0].x === body[index].x && body[0].y === body[index].y) {
                            alert('不能碰到本身啊')
                            clearInterval(this.timer)
                        }
                    }
                }
                //判断碰到食物
                if (body[0].x === sx && body[0].y === sy) {
                    this.snakeAry.push({
                        x: sx,
                        y: sy
                    })
                    this.randomFood()
                }

                //处理边界游戏结束
                if (body[0].x < 0 || body[0].x * this.snakeWidth > this.boxWidth - this.snakeWidth
                    || body[0].y < 0 || body[0].y * this.snakeWidth > this.boxheight - this.snakeHeight) {
                    alert('game over')
                    clearInterval(this.timer)
                }


            }

        }
    }
复制代码

最后贴上效果和完整代码

屏幕录制2021-06-25 下午11.04.30.gif

<template>
    <div class="snakebox" :style="{width:boxWidth+'px',height: boxheight + 'px'}"> <div class="snake" :style="{left : item.x*snakeWidth +'px' , top:item.y*snakeHeight +'px', width:snakeWidth+ 'px' , height: snakeHeight+'px'}" v-for="(item,index) in snakeAry" :key="index"></div> <div class="shiwu" :style="{width:snakeWidth+'px',height:snakeHeight+'px',left: foodInfo.x* snakeWidth+ 'px',top : foodInfo.y*snakeWidth+'px'}"></div> </div>
</template>

<script> export default { name: 'snake', data() { return { boxWidth: 500, //场景宽度 boxheight: 500,//场景高度 snakeWidth: 20, //蛇身宽度 snakeHeight: 20,//蛇身宽度 direction: 'right',//蛇移动方向 snakeAry: [ {x: 2, y: 1}, //蛇头 {x: 3, y: 1}, //蛇身 {x: 4, y: 1}], // 蛇尾 foodInfo: null, // 食物坐标信息 timer: null, } }, created() { this.randomFood() this.timerfun() }, mounted() { document.body.addEventListener('keydown', (ev) => { ev.preventDefault() switch (ev.key) { case 'ArrowUp': this.direction = 'up' break case 'ArrowDown': this.direction = 'down' break case 'ArrowLeft': this.direction = 'left' break case 'ArrowRight': this.direction = 'right' break } }) }, methods: { timerfun() { this.timer = setInterval(() => { this.moveSnake() }, 100) }, randomFood() { this.foodInfo = { x: Math.floor(Math.random() * this.boxWidth / this.snakeWidth), y: Math.floor(Math.random() * this.boxheight / this.snakeHeight) } }, moveSnake() { const {x: sx, y: sy} = this.foodInfo let body = this.snakeAry //蛇身 蛇尾用逆向循环改变一下位置 for (let i = body.length - 1; i > 0; i--) { body[i].x = body[i - 1].x body[i].y = body[i - 1].y } //改变蛇头坐标信息 if (this.direction === 'right') body[0].x += 1 if (this.direction === 'down') body[0].y += 1 if (this.direction === 'up') body[0].y -= 1 if (this.direction === 'left') body[0].x -= 1 // 处理碰到本身的状况 if (body.length >= 4) { for (let index = 4; index < body.length; index++) { if (body[0].x === body[index].x && body[0].y === body[index].y) { alert('不能碰到本身啊') clearInterval(this.timer) } } } //判断碰到食物 if (body[0].x === sx && body[0].y === sy) { this.snakeAry.push({ x: sx, y: sy }) this.randomFood() } //处理边界游戏结束 if (body[0].x < 0 || body[0].x * this.snakeWidth > this.boxWidth - this.snakeWidth || body[0].y < 0 || body[0].y * this.snakeWidth > this.boxheight - this.snakeHeight) { alert('game over') clearInterval(this.timer) } } } } </script>

<style scoped> .snakebox { position: relative; margin: 0 auto; background: black; transition-duration: 500ms; transition-timing-function: ease-out; overflow: hidden; } .snake { background: red; position: absolute; } .shiwu { position: absolute; background: #0099FF; } </style>

复制代码
相关文章
相关标签/搜索