原生js實現簡單貪吃蛇小遊戲

本文實例為大傢分享瞭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',
                        /* borderRaduis: '50%' */
                    })
                    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();
                /* console.log(snake.cont); */
            },
            /* 判斷是否為開始 */
            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;
                /* console.log(itemsAll);
                console.log(itemsAll,itemsAll[0].nodeName); */
                /* 存儲蛇身每一節的數組 */
                var items = [];
                var span;
                /* var items = Array.from(itemsAll).filter(function (v, k) {
                    return v.nodeName === 'DIV'
                }); */
                /* console.log(items); */
                /* 過濾篩選div(蛇身)與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;
                    }
                    /* 出邊界y */
                    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
                    /* console.log(items[0].style); */
                    /* 插入蛇頭 */
                    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('蛇皮怪你咬死自己瞭,是否重新來過?'))
                            /* console.log(items[0].style.left,items[0].style.top);
                            console.log(items[0].style.left,items[0].style.top); */
                            clearInterval(snake.timer)
                            /* alert('Game Over!');
                            window.location.reload(true) */
                            return
                        }
                        /* 插入蛇身 */
                        snake.cont.appendChild(items[k])
                    }
                    /* 吃到瞭食物 */
                    console.log(span.style.left, span.style.top);
                    /* console.log(l, '吃到瞭食物'); */
                    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>

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: