闲着没事,自己做贪吃蛇耍耍?

前言

相信大家都玩过贪吃蛇这个游戏, 那你们想不想自己也做一做呢?可能会有人说很难把,不,其实不难,因为博主也是JS的入门小白,但是博主今天把贪吃蛇做出来了,做这个项目的时候,有一个小门槛给我卡住了,就是用哪种方式实现蛇的移动,如果这个你们都想出来了,那这个项目对你们来说 so easy! 先来讲讲我的做法。

 前提准备:

  1. 蛇:属性有宽、高、方向、节数、方法:显示、移动

  2. 食物:属性宽、高、位置

  3.  显示蛇:根据状态向 container(相当于地图)里添加元素 

  4. 蛇跑动(重点!):通过for循环,让蛇的下一节到前一节的位置,但是蛇头另外设置,根据蛇  头的方向改变,每次都要删除原来的蛇,创建新蛇;当出界时,死亡,初始化;当蛇头吃到自己的时候,死亡,初始化

  5. 食物被吃掉,蛇加一节,去掉原来的食物,生成新的食物

  6. 添加定时器,绑定按键 

效果呈现:  

 

实际代码: 

1. html+css部分

<!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>
    <script src="index2.js"></script>
    <style>
        * {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
            list-style: none;
        }
        .container {
            position: relative;
            width: 640px;
            height: 640px; 
            background-color: #fce4ec;
            margin: 20px auto;
            border: 20px solid #f8bbd0;
        }

        .center {
            width: 200px;
            height: 150px;
            margin-left: 50%;
            margin-top: 50%;
            transform: translate(-50%,-50%);
          
        }

        .center img {
            width: 100%;
            height: 100%;
            cursor: pointer;
        }
        /*点击暂停时的按钮显示*/
        .img {
            display: none;
            position: absolute;
            top: 0;
            left: 0;
            margin-left: 50%;
            margin-top: 50%;
            transform: translate(-50%,-50%);
            width: 50px;
            height: 50px;
            background-image: url(./btn4.png);
            background-size: 100% 100%;
        } 

 </style>
</head>
<body>
   <div class="container">
      <div class="center">
          <img src="btn1.gif" alt="">
      </div>
  <div class="img"> </div>
   </div>
</body>
</html>

2. JS部分 

window.addEventListener('load', function () {
    var btn = document.querySelector('.center');
    var container = document.querySelector('.container');
    function Snake() {
        //设置蛇的宽、高、默认走的方向
        this.width = 20;
        this.height = 20;
        this.direction = 'right';
        //蛇的初始状态为一个头加两个身体
        this.body = [
            { x: 2, y: 0 }, //蛇头,第一个点
            { x: 1, y: 0 }, //蛇身
            { x: 0, y: 0 } //蛇身
        ];
        //显示蛇
        this.display = function () {
            for (var i = 0; i < this.body.length; i++) {
                if (this.body[i].x != null) {
                    var s = document.createElement('div');
                    this.body[i].flag = s;
                    s.style.height = this.height + 'px';
                    s.style.width = this.width + 'px';
                    s.style.borderRadius = '10px';
                    //通过蛇头的方向,对蛇头进行旋转,确保蛇头和移动方向一致
                    if (i == 0) {
                        if (this.direction == 'up') {
                            s.style.transform = 'rotate(-90deg)';
                        }
                        if (this.direction == 'down') {
                            s.style.transform = 'rotate(90deg)';
                        }
                        if (this.direction == 'left') {
                            s.style.transform = 'rotate(-180deg)';
                        }
                        if (this.direction == 'right') {
                            s.style.transform = 'rotate(0)';
                        }
                      
                        s.style.backgroundImage = 'url(./snake.png)';
                        s.style.backgroundSize = '25px 20px';
                        s.style.backgroundPosition = 'center center';
                    } else {
                        s.style.backgroundColor = '#9ccc65';
                    }
                    s.style.position = 'absolute';
                    s.style.left = this.body[i].x * this.width + 'px';
                    s.style.top = this.body[i].y * this.height + 'px';
                    container.appendChild(s);
                }
            }
        }
        //蛇移动,后一个元素到前一个元素的位置
        //蛇头另外根据方向处理,所以 i 不等于0
        this.run = function () {
            for (var i = this.body.length - 1; i > 0; i--) {
                this.body[i].x = this.body[i - 1].x;
                this.body[i].y = this.body[i - 1].y;
            }
            //根据方向处理蛇头
            switch (this.direction) {
                case "left": this.body[0].x -= 1;
                    break;
                case "right": this.body[0].x += 1;
                    break;
                case "up": this.body[0].y -= 1;
                    break;
                case "down": this.body[0].y += 1;
            }
            //判断是否出界
            if (this.body[0].x < 0 || this.body[0].x > 29 || this.body[0].y < 0 || this.body[0].y > 29) {
                clearInterval(timer);
                alert('你的得分是' + score);
                //删除旧的
                for (var i = 0; i < this.body.length; i++) {
                    if (this.body[i].flag != null) {
                        container.removeChild(this.body[i].flag);
                    }
                }
                //初始化
                this.body = [
                    { x: 2, y: 0 }, //蛇头,第一个点
                    { x: 1, y: 0 }, //蛇身
                    { x: 0, y: 0 } //蛇身
                ];
                this.direction = 'right';
                score = 0;
                btn.style.display = 'block'; //结束显示开始按键
                container.removeChild(food.flag);
                // this.display();
                return false;
            }
            //判断蛇头吃到食物,xy坐标重合
            if (this.body[0].x == food.x && this.body[0].y == food.y) {
                //蛇加一节,因为根据最后节点定,下面 display时,会自动赋值的
                this.body.push({ x: null, y: null, flag: null });
                score++;
                //清除食物,重新生成食物
                container.removeChild(food.flag);
                food.display();
            }
            // 吃到自己死亡,从第五个开始与头判断,因为前四个永远撞不到
            for (var i = 4; i < this.body.length; i++) {
                if (this.body[0].x == this.body[i].x && this.body[0].y == this.body[i].y) {
                    clearInterval(timer);
                    alert('你的得分是' + score);
                    //删除旧的
                    for (var i = 0; i < this.body.length; i++) {
                        if (this.body[i].flag != null) {
                            container.removeChild(this.body[i].flag);
                        }
                    }
                    //回到初始状态
                    this.body = [
                        { x: 2, y: 0 }, //蛇头,第一个点
                        { x: 1, y: 0 }, //蛇身
                        { x: 0, y: 0 } //蛇身
                    ];
                    this.direction = 'right';
                    score = 0;
                    btn.style.display = 'block'; //结束显示开始按键
                    container.removeChild(food.flag);
                    // this.display();
                    return false; //结束
                }
            }
            //先删除掉初始的蛇,再显示新蛇
            for (var i = 0; i < this.body.length; i++) {
                if (this.body[i].flag != null) { //当吃到食物时, flag等于 null,且不能删除
                    container.removeChild(this.body[i].flag);
                }
            }
            this.display();
        }
    }

    //构造食物
    function Food() {
        this.width = 20;
        this.height = 20;
        this.display = function () {
            var f = document.createElement('div');
            this.flag = f;
            f.style.width = this.width + 'px';
            f.style.height = this.height + 'px';
            f.style.backgroundImage = 'url(./food2.png)';
            f.style.backgroundSize = '100% 100%';
            f.style.position = 'absolute';
            this.x = Math.floor(Math.random() * 30);
            this.y = Math.floor(Math.random() * 30);
            f.style.left = this.x * this.width + 'px';
            f.style.top = this.y * this.height + 'px';
            container.appendChild(f);
        }

    }
     var timer = null;
    var score = 0;
    var snake = new Snake();
    var food = new Food();
    var flag1 = false;
    var flag = false;
    var stop = document.querySelector('.img');
   
    btn.addEventListener('click', function (e) {
        clearInterval(timer);
        btn.style.display = 'none';
        snake.display();
        food.display();
        //加按键事件 , 上下左右
        document.addEventListener('keydown', function (e) {
            switch (e.keyCode) {
                case 38:
                    if (snake.direction != 'down') {
                        snake.direction = 'up';
                      
                    }
                    break;
                case 40:
                    if (snake.direction != 'up') {
                        snake.direction = 'down';
                       
                    }
                    break;
                case 37:
                    if (snake.direction != 'right') {
                        snake.direction = 'left';
                
                    }
                    break;
                case 39:
                    if (snake.direction != 'left') {
                        snake.direction = 'right';
                   
                    }
                    break;
            }
        });

        flag1 = true;
        
    })
    //开始后,点击游戏界面会暂停,再点击就继续
    
    container.addEventListener('click', function () {
        if (flag1) {
            if (flag) {
                clearInterval(timer);
                stop.style.display = 'block';
                flag = false;
            } else {
                clearInterval(timer);
                timer = setInterval(function () {
                    snake.run();
                }, 500)
                stop.style.display = 'none';
                flag = true;
            }
        }
        })
})

3. 用到的图片 

  


以上就是这个项目的全部啦,有兴趣又还没看懂的同学,可以留言评论哟~

  • 14
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值