Javascript實現(xiàn)貪吃蛇小游戲(含詳細注釋)
更新時間:2020年10月23日 17:08:18 作者:是榆榆啊
這篇文章主要為大家詳細介紹了Javascript實現(xiàn)貪吃蛇小游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了Javascript實現(xiàn)貪吃蛇小游戲的具體代碼,供大家參考,具體內(nèi)容如下
前言
原生JavaScript實現(xiàn)貪吃蛇小游戲
直接復(fù)制可用
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>貪吃蛇</title> <link rel="stylesheet" href="CSS/index.css" > <link rel="icon" href="favicon.ico" /> </head> <body> <div class="content"> <div class="btn startBtn"><button></button></div> <div class="btn pauseBtn"><button></button></div> <div id="snakeWrap"> </div> </div> <script src="JS/index.js"></script> <script> // document.documentElement.style.overflow = 'hidden'; </script> </body> </html>
index.css
.content { width: 640px; height: 640px; margin: 100px auto; position: relative; } .btn { width: 100%; height: 100%; position: absolute; left: 0; top: 0; background-color: rgba(0, 0, 0, 0.3); z-index: 2; } .btn button { background: none; border: none; background-size: 100% 100%; cursor: pointer; outline: none; position: absolute; left: 50%; top: 50%; } .startBtn button { width: 200px; height: 200px; background-image: url(../images/startGame.png); margin-left: -100px; margin-top: -100px; } .pauseBtn { display: none; } .pauseBtn button { width: 70px; height: 70px; background-image: url(../images/pauseGame.png); margin-top: -35px; margin-left: -35px; } /* snakeWrap */ #snakeWrap { width: 600px; height: 600px; background-color: #225675; border: 20px solid #7dd9ff; position: relative; } #snakeWrap div { width: 20px; height: 20px; } .snakeHead { background-image: url(../images/snakeHead.png); background-size: cover; border-top-right-radius: 30%; border-bottom-right-radius: 30%; } .snakeBody { background-color: #9ddbb1; border-radius: 50%; } .food { background-image: url(../images/food.png); background-size: cover; }
index.js(核心部分)
var sw = 20, // 方塊的寬 sh = 20, // 方塊的高 tr = 30, // 行數(shù) td = 30; // 列數(shù) var snake = null, //蛇的實例 food = null, //食物的實例 game = null; //游戲的實例 // 創(chuàng)建小方塊的構(gòu)造函數(shù) // x,y代表小方塊的坐標(biāo) // classname 代表等下小方塊的樣式 // 按照像素坐標(biāo) 第一個0,0 第二個20,0 // 但這里的x,y表示的是第一個0,0 第二個1,0 function Square(x, y, classname) { // 進行坐標(biāo) 轉(zhuǎn)換成像素坐標(biāo) this.x = x * sw; this.y = y * sh; this.class = classname; this.viewContent = document.createElement('div'); // 小方塊所對應(yīng)的dom元素 this.viewContent.className = this.class; this.parent = document.getElementById('snakeWrap'); // 方塊的父級 } Square.prototype.create = function () { this.viewContent.style.position = 'absolute'; // 創(chuàng)建方塊DOM this.viewContent.style.width = sw + 'px'; this.viewContent.style.height = sh + 'px'; this.viewContent.style.left = this.x + 'px'; this.viewContent.style.top = this.y + 'px'; this.parent.appendChild(this.viewContent); // 將小方塊添加到頁面當(dāng)中 }; Square.prototype.remove = function () { this.parent.removeChild(this.viewContent); }; // 蛇 function Snake() { this.head = null; // 存一下蛇頭的信息 this.tail = null; // 存一下蛇尾的信息 this.pos = []; // 存儲蛇身上的每一個方塊的位置 二維數(shù)組 this.directionNum = { left: { x: -1, y: 0, rotate: 180 //蛇頭在不同的方向中 應(yīng)該進行旋轉(zhuǎn) }, right: { x: 1, y: 0, rotate: 0 }, up: { x: 0, y: -1, rotate: -90 }, down: { x: 0, y: 1, rotate: 90 } }; //存儲蛇走的方向 用一個對象來表示 } Snake.prototype.init = function () { // 初始化 // 創(chuàng)建蛇頭 var snakeHead = new Square(2, 0, 'snakeHead'); snakeHead.create(); this.head = snakeHead; // 存儲蛇頭信息 this.pos.push([2, 0]); // 把蛇頭的位置存儲起來 // 創(chuàng)建蛇的身體1 var snakeBody1 = new Square(1, 0, 'snakeBody'); snakeBody1.create(); this.pos.push([1, 0]); //把蛇身1的坐標(biāo)存儲 // 創(chuàng)建蛇的身體2 var snakeBody2 = new Square(0, 0, 'snakeBody'); snakeBody2.create(); this.pos.push([0, 0]); //把蛇身2的坐標(biāo)存儲 this.tail = snakeBody2; //存儲蛇尾信息 // 形成鏈表關(guān)系 snakeHead.last = null; snakeHead.next = snakeBody1; snakeBody1.last = snakeHead; snakeBody1.next = snakeBody2; snakeBody2.last = snakeBody1; snakeBody2.next = null; // 添加一條屬性,用來表示蛇走的方向 this.direction = this.directionNum.right; // 默認讓蛇往右走 }; // 這個方法用來獲取蛇頭的下一個位置對應(yīng)的元素 // 要根據(jù)元素做不同的事情 Snake.prototype.getNextPos = function () { var nextPos = [ // 蛇頭要走的下一個點的坐標(biāo) this.head.x / sw + this.direction.x, this.head.y / sh + this.direction.y ]; // 下一個點是自己,代表撞到了自己,游戲結(jié)束 var selfCollied = false; //是否撞到自己 this.pos.forEach(function (value) { // 數(shù)組,對象,直接比較,還要比較引用值 if (value[0] == nextPos[0] && value[1] == nextPos[1]) { selfCollied = true; // 表示撞到了自己 } }); if (selfCollied) { // console.log('撞到自己的了'); this.strategies.die.call(this); return; } // 下一個點是墻,代表撞到了圍墻,游戲結(jié)束 if (nextPos[0] < 0 || nextPos[1] < 0 || nextPos[0] > td - 1 || nextPos[1] > tr - 1) { // console.log('撞到墻上了'); this.strategies.die.call(this); return; } // 下一個點是food,代表吃大了食物,吃 if (food && food.pos[0] == nextPos[0] && food.pos[1] == nextPos[1]) { //說明蛇頭要走的下一個點是食物的那個點 // console.log('eat food'); this.strategies.eat.call(this); return; } // 使用return 結(jié)束函數(shù)下面的代碼運行,若是上述的情況均為發(fā)生,則最后的情況,肯定是空 // 下一個點是空,走 this.strategies.move.call(this); }; // 處理碰撞后的事件 Snake.prototype.strategies = { move: function (format) { // 這個參數(shù)用來決定要不要刪除蛇尾 當(dāng)傳了操作(true)后為吃 // 創(chuàng)建一個新的身體(在舊蛇頭的位置) var newBody = new Square(this.head.x / sw, this.head.y / sh, 'snakeBody'); // 更新鏈表的關(guān)系 newBody.next = this.head.next; newBody.next.last = newBody; newBody.last = null; this.head.remove(); // 把舊蛇頭從原來的位置刪除 newBody.create(); // 創(chuàng)建一個新的蛇頭,在(nextPos 位置創(chuàng)建) var newHead = new Square(this.head.x / sw + this.direction.x, this.head.y / sh + this.direction.y, 'snakeHead'); // 更新鏈表的關(guān)系 newHead.last = null; newHead.next = newBody; newHead.next.last = newHead; newHead.viewContent.style.transform = 'rotate(' + this.direction.rotate + 'deg)'; newHead.create(); // 蛇身上的每一個坐標(biāo)進行更新 this.pos.splice(0, 0, [this.head.x / sw + this.direction.x, this.head.y / sh + this.direction.y]); this.head = newHead; //把this.head的信息更新 // 刪除蛇尾 通過判斷是否吃food,如果吃了food,就不刪除,若是沒有吃,就刪除 if (!format) { //如果format 的值為false 表示需要刪除(除了吃之外的操作) this.tail.remove(); // 更新鏈表 this.tail = this.tail.last; this.tail.next = null; // 更新蛇身坐標(biāo)數(shù)組 this.pos.pop(); } }, eat: function () { this.strategies.move.call(this, true); createFood(); game.score++; }, die: function () { game.over(); } } snake = new Snake(); // 創(chuàng)建食物 function createFood() { // 食物小方塊的隨機坐標(biāo) var x = null, y = null; var include = true; // 循環(huán)跳出的條件,true表示隨機生成的坐標(biāo)在蛇身上,繼續(xù)讓他循環(huán),false表示食物坐標(biāo)不在蛇身上,不循環(huán) while (include) { // 0~29隨機數(shù) x = Math.round(Math.random() * (td - 1)) y = Math.round(Math.random() * (tr - 1)) snake.pos.forEach(function (value) { if (value[0] != x && value[1] != y) { // 這個條件成立說明現(xiàn)在隨機出的食物坐標(biāo),并未在蛇身上 include = false; } }); } // 生成食物 food = new Square(x, y, 'food'); food.pos = [x, y]; // 存儲一下生成食物的坐標(biāo),用于跟蛇頭要走的下一個點做對比 var foodDom = document.querySelector('.food'); if (foodDom) { foodDom.style.left = x * sw + 'px'; foodDom.style.top = y * sh + 'px'; } else { food.create(); } } // 創(chuàng)建游戲邏輯 function Game() { this.timer = null; this.score = 0; } Game.prototype.init = function () { snake.init(); // snake.getNextPos(); createFood(); document.onkeydown = function (ev) { if (ev.which == 37 && snake.direction != snake.directionNum.right) { //用戶摁下左鍵時候,這條蛇不能是正在往右走 snake.direction = snake.directionNum.left; } else if (ev.which == 38 && snake.direction != snake.directionNum.down) { snake.direction = snake.directionNum.up; } else if (ev.which == 39 && snake.direction != snake.directionNum.left) { snake.direction = snake.directionNum.right; } else if (ev.which == 40 && snake.direction != snake.directionNum.up) { snake.direction = snake.directionNum.down; } } this.start(); } Game.prototype.start = function () { // 開始游戲 this.timer = setInterval(function () { snake.getNextPos(); }, 200) } Game.prototype.pause = function () { clearInterval(this.timer); } Game.prototype.over = function () { clearInterval(this.timer); alert('你的得分為:' + this.score + '分'); // 游戲回到最初始的狀態(tài) var snakeWrap = document.getElementById('snakeWrap'); snakeWrap.innerHTML = ''; snake = new Snake(); game = new Game(); var startBtnWrap = document.querySelector('.startBtn'); startBtnWrap.style.display = 'block'; } // 開啟游戲 game = new Game(); var startBtn = document.querySelector('.startBtn button'); startBtn.onclick = function () { startBtn.parentNode.style.display = 'none'; game.init(); }; // 暫停 var snakeWrap = document.getElementById('snakeWrap'); var pauseBtn = document.querySelector('.pauseBtn button'); snakeWrap.onclick = function () { game.pause(); pauseBtn.parentNode.style.display = 'block' } pauseBtn.onclick = function () { game.start(); pauseBtn.parentNode.style.display = 'none'; }
更多有趣的經(jīng)典小游戲?qū)崿F(xiàn)專題,分享給大家:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Django1.7+JQuery+Ajax驗證用戶注冊集成小例子
下面是散仙使用Django+Jquery+Ajax的方式來模擬實現(xiàn)了一個驗證用戶注冊時,用戶名存在不存在的一個小應(yīng)用。注意,驗證存在不存在使用的是Ajax的方式,不用讓用戶點擊按鈕驗證是否存在,需要的朋友可以參考下2017-04-04JavaScript實現(xiàn)微信小程序打卡時鐘項目實例
這篇文章主要為大家介紹了JavaScript實現(xiàn)微信小程序打卡時鐘項目實例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-04-04