Javascript實(shí)現(xiàn)貪吃蛇小游戲(含詳細(xì)注釋)
本文實(shí)例為大家分享了Javascript實(shí)現(xiàn)貪吃蛇小游戲的具體代碼,供大家參考,具體內(nèi)容如下
前言
原生JavaScript實(shí)現(xiàn)貪吃蛇小游戲
GitHub地址
直接復(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='http://www.cgvv.com.cn/bcjs/CSS/index.css' > <link rel='icon' href='http://www.cgvv.com.cn/bcjs/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='http://www.cgvv.com.cn/bcjs/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, //蛇的實(shí)例 food = null, //食物的實(shí)例 game = null; //游戲的實(shí)例// 創(chuàng)建小方塊的構(gòu)造函數(shù)// x,y代表小方塊的坐標(biāo)// classname 代表等下小方塊的樣式// 按照像素坐標(biāo) 第一個(gè)0,0 第二個(gè)20,0 // 但這里的x,y表示的是第一個(gè)0,0 第二個(gè)1,0function Square(x, y, classname) { // 進(jìn)行坐標(biāo) 轉(zhuǎn)換成像素坐標(biāo) this.x = x * sw; this.y = y * sh; this.class = classname; this.viewContent = document.createElement(’div’); // 小方塊所對(duì)應(yīng)的dom元素 this.viewContent.className = this.class; this.parent = document.getElementById(’snakeWrap’); // 方塊的父級(jí)}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); // 將小方塊添加到頁(yè)面當(dāng)中};Square.prototype.remove = function () { this.parent.removeChild(this.viewContent);};// 蛇function Snake() { this.head = null; // 存一下蛇頭的信息 this.tail = null; // 存一下蛇尾的信息 this.pos = []; // 存儲(chǔ)蛇身上的每一個(gè)方塊的位置 二維數(shù)組 this.directionNum = { left: { x: -1, y: 0, rotate: 180 //蛇頭在不同的方向中 應(yīng)該進(jìn)行旋轉(zhuǎn) }, right: { x: 1, y: 0, rotate: 0 }, up: { x: 0, y: -1, rotate: -90 }, down: { x: 0, y: 1, rotate: 90 } }; //存儲(chǔ)蛇走的方向 用一個(gè)對(duì)象來(lái)表示}Snake.prototype.init = function () { // 初始化 // 創(chuàng)建蛇頭 var snakeHead = new Square(2, 0, ’snakeHead’); snakeHead.create(); this.head = snakeHead; // 存儲(chǔ)蛇頭信息 this.pos.push([2, 0]); // 把蛇頭的位置存儲(chǔ)起來(lái) // 創(chuàng)建蛇的身體1 var snakeBody1 = new Square(1, 0, ’snakeBody’); snakeBody1.create(); this.pos.push([1, 0]); //把蛇身1的坐標(biāo)存儲(chǔ) // 創(chuàng)建蛇的身體2 var snakeBody2 = new Square(0, 0, ’snakeBody’); snakeBody2.create(); this.pos.push([0, 0]); //把蛇身2的坐標(biāo)存儲(chǔ) this.tail = snakeBody2; //存儲(chǔ)蛇尾信息 // 形成鏈表關(guān)系 snakeHead.last = null; snakeHead.next = snakeBody1; snakeBody1.last = snakeHead; snakeBody1.next = snakeBody2; snakeBody2.last = snakeBody1; snakeBody2.next = null; // 添加一條屬性,用來(lái)表示蛇走的方向 this.direction = this.directionNum.right; // 默認(rèn)讓蛇往右走};// 這個(gè)方法用來(lái)獲取蛇頭的下一個(gè)位置對(duì)應(yīng)的元素 // 要根據(jù)元素做不同的事情Snake.prototype.getNextPos = function () { var nextPos = [ // 蛇頭要走的下一個(gè)點(diǎn)的坐標(biāo) this.head.x / sw + this.direction.x, this.head.y / sh + this.direction.y ]; // 下一個(gè)點(diǎn)是自己,代表撞到了自己,游戲結(jié)束 var selfCollied = false; //是否撞到自己 this.pos.forEach(function (value) { // 數(shù)組,對(duì)象,直接比較,還要比較引用值 if (value[0] == nextPos[0] && value[1] == nextPos[1]) { selfCollied = true; // 表示撞到了自己 } }); if (selfCollied) { // console.log(’撞到自己的了’); this.strategies.die.call(this); return; } // 下一個(gè)點(diǎn)是墻,代表撞到了圍墻,游戲結(jié)束 if (nextPos[0] < 0 || nextPos[1] < 0 || nextPos[0] > td - 1 || nextPos[1] > tr - 1) { // console.log(’撞到墻上了’); this.strategies.die.call(this); return; } // 下一個(gè)點(diǎn)是food,代表吃大了食物,吃 if (food && food.pos[0] == nextPos[0] && food.pos[1] == nextPos[1]) { //說(shuō)明蛇頭要走的下一個(gè)點(diǎn)是食物的那個(gè)點(diǎn) // console.log(’eat food’); this.strategies.eat.call(this); return; } // 使用return 結(jié)束函數(shù)下面的代碼運(yùn)行,若是上述的情況均為發(fā)生,則最后的情況,肯定是空 // 下一個(gè)點(diǎn)是空,走 this.strategies.move.call(this);};// 處理碰撞后的事件Snake.prototype.strategies = { move: function (format) { // 這個(gè)參數(shù)用來(lái)決定要不要?jiǎng)h除蛇尾 當(dāng)傳了操作(true)后為吃 // 創(chuàng)建一個(gè)新的身體(在舊蛇頭的位置) 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(); // 把舊蛇頭從原來(lái)的位置刪除 newBody.create(); // 創(chuàng)建一個(gè)新的蛇頭,在(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(); // 蛇身上的每一個(gè)坐標(biāo)進(jìn)行更新 this.pos.splice(0, 0, [this.head.x / sw + this.direction.x, this.head.y / sh + this.direction.y]); this.head = newHead; //把this.head的信息更新 // 刪除蛇尾 通過(guò)判斷是否吃food,如果吃了food,就不刪除,若是沒有吃,就刪除 if (!format) { //如果format 的值為false 表示需要?jiǎng)h除(除了吃之外的操作) 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() { // 食物小方塊的隨機(jī)坐標(biāo) var x = null, y = null; var include = true; // 循環(huán)跳出的條件,true表示隨機(jī)生成的坐標(biāo)在蛇身上,繼續(xù)讓他循環(huán),false表示食物坐標(biāo)不在蛇身上,不循環(huán) while (include) { // 0~29隨機(jī)數(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) { // 這個(gè)條件成立說(shuō)明現(xiàn)在隨機(jī)出的食物坐標(biāo),并未在蛇身上 include = false; } }); } // 生成食物 food = new Square(x, y, ’food’); food.pos = [x, y]; // 存儲(chǔ)一下生成食物的坐標(biāo),用于跟蛇頭要走的下一個(gè)點(diǎn)做對(duì)比 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) { //用戶摁下左鍵時(shí)候,這條蛇不能是正在往右走 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)專題,分享給大家:
C++經(jīng)典小游戲匯總
python經(jīng)典小游戲匯總
python俄羅斯方塊游戲集合
JavaScript經(jīng)典游戲 玩不停
java經(jīng)典小游戲匯總
javascript經(jīng)典小游戲匯總
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼2. 如何在PHP中讀寫文件3. java加載屬性配置properties文件的方法4. PHP正則表達(dá)式函數(shù)preg_replace用法實(shí)例分析5. 什么是Python變量作用域6. 《Java程序員修煉之道》作者Ben Evans:保守的設(shè)計(jì)思想是Java的最大優(yōu)勢(shì)7. CSS3中Transition屬性詳解以及示例分享8. php redis setnx分布式鎖簡(jiǎn)單原理解析9. bootstrap select2 動(dòng)態(tài)從后臺(tái)Ajax動(dòng)態(tài)獲取數(shù)據(jù)的代碼10. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式
