文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

原生js实现简单贪吃蛇小游戏

2024-04-02 19:55

关注

本文实例为大家分享了js实现贪吃蛇小游戏的具体代码,供大家参考,具体内容如下

先上图

话不多说,代码奉上,喜欢的请留下你的小星星♥(ˆ◡ˆԅ)


<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
 
        .l {
            float: left;
        }
 
        .r {
            float: right;
        }
 
        .clear_fix::after {
            content: '';
            height: 0;
            width: 100%;
            display: block;
            clear: both;
            overflow: hidden;
            visibility: hidden;
        }
 
        .body {
            margin: 50px 0 0 50px;
            width: 700px;
        }
 
        .cont {
            width: 500px;
            height: 500px;
            border: 1px solid green;
            margin-right: 8px;
            position: relative;
        }
 
        .cont div {
            position: absolute;
            width: 10px;
            height: 10px;
            background-color: orange;
            border: 1px solid #000;
            box-sizing: border-box;
        }
 
        .cont .snakeHead {
            border-radius: 50%;
        }
 
        .cont span {
            position: absolute;
            display: inline-block;
            width: 10px;
            height: 10px;
            border: 1px solid #000;
            box-sizing: border-box;
            border-radius: 50%;
            background: green;
 
        }
 
        .score {
            width: 188px;
            height: 500px;
            border: 1px solid red;
 
        }
 
        .score p {
            text-align: center;
            height: 50px;
            line-height: 50px;
            font-size: 30px;
            margin: 20px 0;
            color: brown
        }
        .score .time{
            color: chartreuse;
            font-size: 20px;
        }
        .btn {
            margin-left: 50px
        }
 
        .btn .active {
            background-color: green;
        }
 
        button {
            width: 100px;
            height: 30px;
            font-size: 24px;
        }
    </style>
</head>
 
<body>
    <div id="wrap">
        <div class="body clear_fix">
            <div class="cont l">
            </div>
            <div class="score l">分数:
                </br>
                <p>0分</p>
                <hr>
                时间:
                <p class="time"></p>
            </div>
        </div>
        <div class="btn">
            <button>开始</button>
            <button class="active">普通</button>
            <button>困难</button>
            <button>地狱</button>
        </div>
    </div>
    <script>
        var snake = {
            
            init: function () {
                this.btns = document.querySelectorAll('button');
                this.score = document.querySelector('p');
                this.cont = document.querySelector('.cont');
                //时间显示的容器
                this.time = document.querySelector('.time');
                //蛇的方向,'r'表示向右
                this.dir = 'r';
 
                
                this.timer = '';
                
                this.head = {
                    l: 30,
                    t: 10
                }
                //蛇尾
                this.ender = {
                    l: '',
                    t: ''
                };
                this.foodItem = {
                    l: '',
                    t: ''
                };
                //为开始的状态
                this.isStart = false;
                
                this.counter = 0;
                //简单status为1,困难为2,地狱为3
                this.status = 1;
                this.speed = 10
                this.btns[0].onclick = this.startFn //开始或者暂停
                this.btns[1].onclick = this.simpleFn //简单模式监听
                this.btns[2].onclick = this.difcultFn //困难模式监听
                this.btns[3].onclick = this.hardFn //地狱模式监听
                this.initCreate();
                this.getTime()
                //随机一个食物
                this.getfood()
            },
            initCreate() {
                //创建一个初始蛇头和蛇身3块
 
                for (let i = 0; i <= 3; i++) {
                    let item = document.createElement('div');
                    Object.assign(item.style, {
                        left: this.head.l - 10 * i + 'px',
                        top: this.head.t + 'px',
                        
                    })
                    if (i == 0) {
                        item.className = 'snakeHead'
                    }
                    snake.cont.appendChild(item);
                }
            },
            
            createSnake: function (obj) {
                clearInterval(snake.timer)
                var div = document.createElement('div');
                div.style.left = snake.ender.l;
                div.style.top = snake.ender.t;
                snake.cont.appendChild(div);
                console.log(snake.cont.children);
                snake.move();
                
            },
            
            startFn: function () {
                if (!snake.isStart) {
                    snake.move();
                    snake.btns[0].innerHTML = '暂停';
                    snake.isStart = true;
                } else {
                    snake.stop();
                    snake.btns[0].innerHTML = '开始';
                    snake.isStart = false;
                }
 
            },
            
            move: function () {
                document.onkeydown = snake.controlFn;
                var itemsAll = snake.cont.children;
                
                
                var items = [];
                var span;
                
                
                
                for (var j = 0; j < itemsAll.length; j++) {
                    if (itemsAll[j].nodeName == 'DIV') {
                        items.push(itemsAll[j])
                    } else {
                        span = itemsAll[j]
                    }
                }
                
                var l = snake.head.l;
                var t = snake.head.t;
                console.log(l, t);
                console.log(items)
                clearInterval(snake.timer)
                
                document.onkeydown = snake.controlFn
                
                snake.timer = setInterval(function () {
                    
                    snake.ender.l = items[items.length - 1].style.left;
                    snake.ender.t = items[items.length - 1].style.top;
                    
                    for (var i = items.length - 1; i > 0; i--) {
                        items[i].style.left = items[i - 1].style.left;
                        items[i].style.top = items[i - 1].style.top;
                    }
 
                    
                    if (snake.dir == 'l') {
                        l -= snake.speed;
                    }
                    if (snake.dir == 'r') {
                        l += snake.speed;
                    }
                    if (snake.dir == 't') {
                        t -= snake.speed;
                    }
                    if (snake.dir == 'b') {
                        t += snake.speed;
                    }
                    
                    if (l < 0 || l > 490 || t < 0 || t > 490) {
                        clearInterval(snake.timer)
                        snake.reStart(confirm('蛇皮怪你撞墙了!!是否重新来过?'))
                    }
 
                    items[0].style.left = l + 'px';
                    items[0].style.top = t + 'px';
                    
                    snake.head.l = l
                    snake.head.t = t
                    
                    
                    snake.cont.appendChild(items[0])
                    for (var k = 1; k < items.length; k++) {
                        
                        if (items[0].style.left == items[k].style.left && items[0].style.top == items[k]
                            .style.top) {
                            snake.reStart(confirm('蛇皮怪你咬死自己了,是否重新来过?'))
                            
                            clearInterval(snake.timer)
                            
                            return
                        }
                        
                        snake.cont.appendChild(items[k])
                    }
                    
                    console.log(span.style.left, span.style.top);
                    
                    if (l == parseInt(span.style.left) && t == parseInt(span.style.top)) {
                        snake.eat()
                    }
                }, parseInt(300 / snake.status))
            },
            eat() {
                snake.createSnake()
                snake.getfood()
                snake.counter++;
                snake.score.innerHTML = `${snake.counter*100}分`
            },
            
            reStart: function (value) {
                if (value) {
                    window.location.reload(true)
                }
            },
            
            getfood: function () {
                if (document.querySelector('span')) {
                    console.log('进来了');
                    document.querySelector('span').remove();
                }
 
                var span = document.createElement('span');
                var l = snake.randM(0, 49) * 10
                var t = snake.randM(0, 49) * 10
                console.log('得到食物', l, t);
 
                span.style.left = l + 'px';
                span.style.top = t + 'px';
 
                snake.cont.appendChild(span);
                if (snake.isStart) {
                    snake.move()
                }
            },
            
            getTime() {
                let time,h,m,s
                
                setInterval(function () {
                    time = new Date()
                    h = time.getHours()
                    m = time.getMinutes();
                    s = time.getSeconds();
                     if (h < 10) {
                         h = '0' + h
                     }
                     if (m < 10) {
                         m = '0' + m
                     }
                     if (s < 10) {
                         s = '0' + s
                     }
                    snake.time.innerHTML = `${h}: ${m}: ${s}`
                }, 1000)
            },
            randM: function (min, max) {
                return Math.round(Math.random() * (max - min) + min)
            },
            
            stop: function () {
                clearInterval(snake.timer)
            },
            
            simpleFn: function () {
                snake.status = 1;
                snake.btnFn()
                snake.btns[1].className = 'active'
            },
            
            difcultFn: function () {
                snake.status = 3;
                snake.btnFn()
                snake.btns[2].className = 'active'
            },
            
            hardFn: function () {
                snake.status = 5;
                snake.btnFn()
                snake.btns[3].className = 'active'
            },
            btnFn: function () {
                snake.btns.forEach(function (v, k) {
                    v.className = ''
                });
                if (snake.isStart) {
                    snake.move();
                }
            },
            
            controlFn: function (el) {
                var el = el || window.event;
                var code = el.keycode || el.which;
                console.log(code);
                if ((code == 40 || code == 83)&&snake.dir !='t') {
                    snake.dir = 'b'
                }
                if ((code == 39 || code == 68)&&snake.dir !='l') {
                    snake.dir = 'r'
                }
                if ((code == 38 || code == 87)&&snake.dir !='b') {
                    snake.dir = 't'
                }
                if ((code == 37 || code == 65)&&snake.dir !='r') {
                    snake.dir = 'l'
                }
            }
        }
        snake.init();
    </script>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-前端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯