溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么用JavaScript寫一個貪吃蛇游戲

發(fā)布時間:2021-09-07 13:45:12 來源:億速云 閱讀:141 作者:chen 欄目:開發(fā)技術(shù)

本篇內(nèi)容介紹了“怎么用JavaScript寫一個貪吃蛇游戲”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!

首先我們要確定貪吃蛇應(yīng)有的功能

1.通過鍵盤的上下左右控制蛇的移動方向

2.邊界判定,即蛇頭超出邊界則游戲結(jié)束

3.碰撞判定,即蛇頭和食物塊發(fā)生觸碰

4.吃到食物積分加1

具體實現(xiàn)

一.html代碼

<div class="container">
        <!--小蛇移動的操場-->
        <div id="playground">
            <!--小蛇-->
            <div id="snake"></div>
            <!--食物-->
            <div id="food"></div>
        </div>
        <!--記錄得分-->
        <div id="menu">
            <div>得分<span id="score"></span></div>
        </div>
</div>

二.css代碼

<style>
        * {
            padding: 0;
            margin: 0;
        }
 
        .container {
            width: 800px;
            height: 600px;
            margin: 0 auto;
        }
 
        #playground {
            width: 650px;
            height: 100%;
            background-color: cadetblue;
            float: left;
            position: relative;
        }
 
        #menu {
            width: 150px;
            height: 100%;
            background-color: darkcyan;
            float: left;
        }
 
        #snake {
            width: 20px;
            height: 20px;
            background-color: #d3e0d7;
            position: absolute;
            left: 0;
            top: 0;
        }
 
        #food {
            width: 20px;
            height: 20px;
            background-color: #027766;
            position: absolute;
        }
 
        .body {
            width: 20px;
            height: 20px;
            background-color: #178b9a;
            position: absolute;
            ;
            top: 0;
            left: 0;
        }
 
        #score {
            font-size: 30px;
            font-weight: bold;
            color: black;
        }
 
        #menu div {
            font-size: 20px;
            font-weight: bold;
            margin-left: 20px;
        }
 
        #hqx {
            width: 100px;
            height: 50px;
            margin: 0 auto;
 
        }
 
        #inp {
            border: 0;
            width: 100px;
            height: 50px;
            background-color: coral;
        }
</style>

三.開始實現(xiàn)具體功能

1.先獲取節(jié)點,設(shè)置全局變量

//獲取節(jié)點
        var snake = document.getElementById("snake");
        var food = document.getElementById("food");
        var playground = document.getElementById("playground");
        var score = document.getElementById('score');
        // var inp = document.getElementById('inp')
        /*設(shè)置全局變量*/
        var timer;
        var arr = []; //存放蛇的位置的數(shù)組
        var num = 0; //數(shù)組的長度
        var snakeBody; //每次吃調(diào)一個食物,增加的身體

2.設(shè)置按鍵事件,并判斷邊界碰撞,碰撞時游戲結(jié)束。這一塊代碼我遇到了一個問題,就是當(dāng)我用if(){return}跳出事件,會結(jié)束所有代碼,后面的代碼就不會執(zhí)行了,然后我換成了switch(){ case:     break;}就實現(xiàn)效果了

 //設(shè)置按鍵事件
        document.onkeydown = function (e) {
            var evt = window.evnet || e;
            switch (evt.keyCode) {
                case 37: //左
                    clearInterval(timer);
                    timer = window.setInterval(runLeft, 10); //向左移動的時間器
                    function runLeft() {
                        if (snake.offsetLeft > 0) {
                            snake.style.left = snake.offsetLeft - 1 + 'px'; //實現(xiàn)自己動
                            snake.style.top = snake.offsetTop + 'px'; //高度不變
                            arr.push([snake.offsetLeft, snake.offsetTop]); //每移動1px,就將位置存進數(shù)組中
                            num++; //相應(yīng)的數(shù)組長度加1
                        } else {
                            clearInterval(timer); //清除定時器
                            alert('you die') //彈出失敗信息
                            document.onkeydown = null //結(jié)束按鍵
                        }
                    }
                    break; //結(jié)束當(dāng)前按鍵
                case 38: //上
                    clearInterval(timer);
                    timer = window.setInterval(runTop, 10);
 
                    function runTop() {
                        if (snake.offsetTop > 0) {
                            snake.style.top = snake.offsetTop - 1 + 'px';
                            snake.style.left = snake.offsetLeft + 'px';
                            arr.push([snake.offsetLeft, snake.offsetTop]);
                            num++;
                        } else {
                            clearInterval(timer);
                            alert('you die')
                            document.onkeydown = null
                        }
                    }
                    break;
                case 39: //右
                    clearInterval(timer);
                    timer = window.setInterval(runRight, 10);
 
                    function runRight() {
                        if (snake.offsetLeft < 630) {
                            snake.style.left = snake.offsetLeft + 1 + 'px';
                            snake.style.top = snake.offsetTop + 'px';
                            arr.push([snake.offsetLeft, snake.offsetTop]);
                            num++;
                        } else {
                            clearInterval(timer);
                            alert('you die')
                            document.onkeydown = null
                        }
                    }
                    break;
                case 40: //下
                    clearInterval(timer);
                    timer = window.setInterval(runBottom, 10);
 
                    function runBottom() {
                        if (snake.offsetTop < 580) {
                            snake.style.top = snake.offsetTop + 1 + 'px';
                            snake.style.left = snake.offsetLeft + 'px';
                            arr.push([snake.offsetLeft, snake.offsetTop]);
                            num++;
                        } else {
                            clearInterval(timer);
                            alert('you die')
                            document.onkeydown = null
                        }
                    }
                    break;
 
}

3.封裝一個函數(shù),隨機生成食物位置,第一次粗心忘記加單位,看網(wǎng)頁沒效果,才知道忘記加單位了

function pos() {
                food.style.left = parseInt(Math.random() * 630) + 'px';
                food.style.top = parseInt(Math.random() * 580) + 'px';
            }

4.封裝一個碰撞判定函數(shù),使其碰撞時,食物消失,蛇的身體增加一塊。這里遇到一個定時器問題,第一次寫的時候,我的定時器清除標識和之前的定時器標識一致,導(dǎo)致蛇會上下左右抖動,經(jīng)過后面不停的修改,最終找到錯誤。

var timer1 = setInterval(eat, 10); //設(shè)置一個碰撞的時間器
            function eat() {
                snakeCrashFood(snake, food); //傳入?yún)?shù)
 
                function snakeCrashFood(obj1, obj2) {
                    var obj1Left = obj1.offsetLeft;
                    var obj1Width = obj1.offsetWidth + obj1.offsetLeft;
                    var obj1Top = obj1.offsetTop;
                    var obj1Height = obj1.offsetHeight + obj1.offsetTop;
                    var obj2Left = obj2.offsetLeft;
                    var obj2Width = obj2.offsetWidth + obj2.offsetLeft;
                    var obj2Top = obj2.offsetTop;
                    var obj2Height = obj2.offsetHeight + obj2.offsetTop;
                    if (!((obj1Width < obj2Left) || (obj2Width < obj1Left) || (obj1Height < obj2Top) || (
                            obj2Height < obj1Top))) {
                        snakeBody = document.createElement("div"); //生成新的div
                        snakeBody.setAttribute("class", "body"); //給新的div添加類名
                        playground.appendChild(snakeBody); //添加一節(jié)新的身體
                        pos(); //讓食物重新隨機出現(xiàn)
                        setInterval(follow, 10); //動態(tài)地改變新的身體的位置
                    }
                }
            }

5.設(shè)置蛇的身體跟隨,獲得蛇身體的數(shù)組,新的身體相對于上一個身體的第20個數(shù)組的位置。這里我遇到了一個數(shù)組越界問題。最開始初始num值為0,place=20,所以第一次身體的增加arr[num-place][0]前面的索引是從負數(shù)開始,在通過老師的指導(dǎo),增加一個判定,解決了這個問題。

function follow() {
                /*獲得增加的身體的數(shù)組*/
                var bodyNum = document.getElementsByClassName("body");
                score.innerHTML = bodyNum.length;
                var place = 0;
                /*數(shù)組每移動1px,新的身體的位置就是相對于前一個身體的第20個數(shù)組的位置,后面依次加等*/
                // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1")
                // console.log("arr   :  ==" + arr)
                // console.log("num : ==" + num)  //2
                for (var i = 0; i < bodyNum.length; i++) {
                    // console.log("bodyNum.length :  ==" + bodyNum.length)
                    place += 20;
                    // console.log("place :  ==" + place)//20
                    // console.log("num - place :  ==" + (num - place))//-18
                    // bodyNum[i].style.left = arr[num - place][0] + 'px';
                    // bodyNum[i].style.top = arr[num - place][1] + 'px';
                    if (num - place > 0) {
                        bodyNum[i].style.left = arr[num - place][0] + 'px';
                        bodyNum[i].style.top = arr[num - place][1] + 'px';
                    }
 
                }
                // console.log("num555 : ==" + num)
                // console.log("===========================================")
            }

“怎么用JavaScript寫一個貪吃蛇游戲”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI