贪吃蛇js游戏

 

1.定义变量保存sHead,sBody

    2.定义变量保存 bgBox背景盒子

    3.定义变量保存移动方向fx[1,-1,10,-10]

    4.生成界面

    5.随机生成食物  var food =

    6.启动定时器

        清空所有盒子背景

        移动蛇身

        显示食物

        吃食物动作

        边界的检测

        自身碰撞检测

    7.给document绑定onkeydown事件

        监听e.keyCode

        上:先判断当前的方向,如果不是向下的,就设置成-10

        左:先判断当前方向,如果不是向右的,就设置成-1

        下:先判断当前方向,如果不是向上的,就设置成10

        右:先判断当前方向,如果不是向左的,就设置成1

//蛇身移动原理

    //1.将蛇头坐标sHead,从前面插入到蛇身中sBody

    // 2.将蛇身数组的最后一个数删掉

    // 3.给蛇头sHead += fx

    // 4.根据sHead,sBody的数据,修改bgBoxs中对应标签的className


 

    //生成食物下标动作

    // 1.随机一个bgBoxs的下标,但是要求与sBody,sHead中的数据不重复

    //吃到食物

    //1.判断 蛇头 数据sHead + fx == food

    // 2.将蛇头sHead从前插入到sBody中

    // 3.将设置位置设置成food的位置

    // 4.重新生成新的食物

    // 5.为了防止在吃掉食物后,多移动一次。设置一个开关量值

   

    //clearInterval 只能停定时器,但是不能停本轮中代码的执行

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .wrap{
            width: 500px;
            height: 500px;
            margin: auto;
            display: flex;
            flex-wrap: wrap;
            position: relative;
        }
        .item{
            width: 50px;
            height: 50px;
            border-radius: 100%;
            box-sizing: border-box;
            background-color: #ccc;
            border: 1px solid #fff;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .snakeHead{
            background-image: url(https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.51yuansu.com%2Fpic3%2Fcover%2F01%2F49%2F87%2F593ae7f99ca2d_610.jpg&refer=http%3A%2F%2Fpic.51yuansu.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1660213565&t=c0c9b53de2f2d46b0c938d6624f2456e);
            background-size: 100% 100%;
        }
        .snakeBody{
            background-color: palegreen;
        }
        .food{
            border-radius: 100%;
            background-color: palegoldenrod;
        }
        #over{
            position: absolute;
            top: 0;
            right: 0;
            left: 0;
            bottom: 0;
            margin: auto;
            font-size: 50px;
            width: 300px;
            height: 100px;
            line-height: 100px;
            text-align: center;
            border: 2px solid #ccc;
            font-weight: bolder;
        }
    </style>
</head>
<body>
    <!-- 容器 -->
    <div class="wrap"></div>
    <div id="over" style="display: none;">gameover</div>
</body>
<script>
    !function(){
        //创建界面
        function createInit(){
            //获取父级容器
            var oWrap = document.querySelector(".wrap");
            //framegment =>虚拟容器,用来装JS生成的标签对象
            var  fg = document.createDocumentFragment();
            //循环创建
            for(var i = 0; i < 100; i++){
                //创建盒子
                var oItem = document.createElement("div");
                //设置类型名
                oItem.className = "item";
                //设置内容
                // oItem.innerHTML = i;
                //自定义属性
                // oItem.index = i;
                // 给bgBoxs中加入新创建的标签
                bgBoxs.push(oItem);
                //装入虚拟容器中
                fg.appendChild(oItem);
            }
            //将界面盒子装入父级
            oWrap.appendChild(fg);
        }

        //移动蛇
        function moveSnake(){
            if(isNotEat){
                //处理蛇身数据
                console.log(sHead)
                sBody.unshift(sHead);//蛇头装入蛇身
                sBody.pop();//删除蛇尾
                //移动蛇头
                sHead += fx;
            }
            //开锁
            isNotEat = true;
            //修改蛇头位置的样式
            // bgBoxs[sHead].classList.add("snakeHead");
            bgBoxs[sHead].className = 'item  snakeHead';
            // console.log(bgBoxs[sHead].classList);
            //设置蛇身的样式
            sBody.map((item) =>{
                bgBoxs[item].classList.add('snakeBody');
            })
        }

        //随机数
        function randNum(min,max){
            return parseInt(Math.random() * (max - min + 1) + min);
        }

        //创建食物位置
        function randFood(){
            //生成食物 重复次数不确定
            while(1){
                //随机位置
                var r = randNum(0,bgBoxs.length-1);
                //如果该位置不与蛇头蛇身重合就跳出
                if(r != sHead && sBody.indexOf(r) == -1)  break;
            }
            //将该位置返回出去
            return r;
        }

        //吃食物
        function eatFood(){
            //监测是否碰到食物
            if(sHead + fx == food){
                //将蛇身加长
                sBody.unshift(sHead);
                //蛇头位置设置成food
                sHead = food;
                //随机生成下一个food位置
                food = randFood();
                //吃到食物设置状态
                isNotEat = false;
            }
        }
        
        //边界监测
        function isOnBorder(){
            //右
            if((sHead + 1) % 10 == 0 && fx == 1) return true;
            //下
            if(sHead >= 90 && sHead <= 99 && fx == 10) return true;
            //左
            if(sHead % 10 == 0 && fx == -1) return true;
            //上
            if(sHead >= 0 && sHead <= 9 && fx == -10) return true;
        }
        //变量存储蛇头位置
        var sHead = randNum(0,99);
        //定义变量(数组)保存蛇身
        var sBody = [];
        // 定义变量保存所有的背景盒子
        var bgBoxs = [];
        //定义开关(假设没有吃到食物)
        var isNotEat = true;
        //定义变量保存移动方向
        var fx = randNum(1,2) == 1 ? 1 : 10;
            fx *= randNum(1,2) == 1 ? 1 : -1;
        // 初始化界面
        createInit();
        //定义变量保存食物位置
        var food = randFood();
        //给document绑定keydown事件
        document.onkeydown = function(e){
            // switch(e.keyCode){
            //     //上
            //     case 38 :
            //         fx = fx != 10 ? -10 : fx;
            //     break;
            //     //右
            //     case 39 :
            //         fx = fx != -1 ? 1 : fx ;
            //     break;
            //     //下
            //     case 40 :
            //         fx = fx != -10? 10 : fx;
            //     break;
            //     //左
            //     case 37 : 
            //         fx = fx != 1 ? -1 : 1;
            //     break;
            // }
            var fxObj = {}
                fxObj[38] = function(){ fx = fx != 10 ? -10 : fx; }
                fxObj[39] = function(){ fx = fx != -1 ? 1 : fx ; }
                fxObj[40] = function(){ fx = fx != -10? 10 : fx; }
                fxObj[37] = function(){ fx = fx != 1 ? -1 : 1; }

                fxObj[e.keyCode]();
        }

        //开启定时器进行游戏
        var timer = setInterval(()=>{
            //1.边界监测
            if(isOnBorder()) {
                over.style.display = 'block';
                //clearInterval只能停止定时器,但是不能停本轮中代码的执行
                clearInterval(timer);
                return; //后面代码不在执行
            };
            //2将所有的背景先清空为原始状态
            bgBoxs.map((item)=>{
                item.className = 'item';
            })
            //3显示食物
            bgBoxs[food].classList.add('food');
            //4吃到食物
            eatFood();
            //5移动蛇
            moveSnake();
        },300)

    }()
</script>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值