Javascript實現貪吃蛇小遊戲(含詳細註釋)
阿新 • • 發佈:2020-10-24
本文例項為大家分享了Javascript實現貪吃蛇小遊戲的具體程式碼,供大家參考,具體內容如下
前言
原生JavaScript實現貪吃蛇小遊戲
GitHub地址
直接複製可用
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.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,// 行數 td = 30; // 列數 var snake = null,//蛇的例項 food = null,//食物的例項 game = null; //遊戲的例項 // 建立小方塊的建構函式 // x,y代表小方塊的座標 // classname 代表等下小方塊的樣式 // 按照畫素座標 第一個0,0 第二個20,0 // 但這裡的x,y表示的是第一個0,0 第二個1,0 function Square(x,y,classname) { // 進行座標 轉換成畫素座標 this.x = x * sw; this.y = y * sh; this.class = classname; this.viewContent = document.createElement('div'); // 小方塊所對應的dom元素 this.viewContent.className = this.class; this.parent = document.getElementById('snakeWrap'); // 方塊的父級 } Square.prototype.create = function () { this.viewContent.style.position = 'absolute'; // 建立方塊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); // 將小方塊新增到頁面當中 }; Square.prototype.remove = function () { this.parent.removeChild(this.viewContent); }; // 蛇 function Snake() { this.head = null; // 存一下蛇頭的資訊 this.tail = null; // 存一下蛇尾的資訊 this.pos = []; // 儲存蛇身上的每一個方塊的位置 二維陣列 this.directionNum = { left: { x: -1,y: 0,rotate: 180 //蛇頭在不同的方向中 應該進行旋轉 },right: { x: 1,rotate: 0 },up: { x: 0,y: -1,rotate: -90 },down: { x: 0,y: 1,rotate: 90 } }; //儲存蛇走的方向 用一個物件來表示 } Snake.prototype.init = function () { // 初始化 // 建立蛇頭 var snakeHead = new Square(2,'snakeHead'); snakeHead.create(); this.head = snakeHead; // 儲存蛇頭資訊 this.pos.push([2,0]); // 把蛇頭的位置儲存起來 // 建立蛇的身體1 var snakeBody1 = new Square(1,'snakeBody'); snakeBody1.create(); this.pos.push([1,0]); //把蛇身1的座標儲存 // 建立蛇的身體2 var snakeBody2 = new Square(0,'snakeBody'); snakeBody2.create(); this.pos.push([0,0]); //把蛇身2的座標儲存 this.tail = snakeBody2; //儲存蛇尾資訊 // 形成連結串列關係 snakeHead.last = null; snakeHead.next = snakeBody1; snakeBody1.last = snakeHead; snakeBody1.next = snakeBody2; snakeBody2.last = snakeBody1; snakeBody2.next = null; // 新增一條屬性,用來表示蛇走的方向 this.direction = this.directionNum.right; // 預設讓蛇往右走 }; // 這個方法用來獲取蛇頭的下一個位置對應的元素 // 要根據元素做不同的事情 Snake.prototype.getNextPos = function () { var nextPos = [ // 蛇頭要走的下一個點的座標 this.head.x / sw + this.direction.x,this.head.y / sh + this.direction.y ]; // 下一個點是自己,代表撞到了自己,遊戲結束 var selfCollied = false; //是否撞到自己 this.pos.forEach(function (value) { // 陣列,物件,直接比較,還要比較引用值 if (value[0] == nextPos[0] && value[1] == nextPos[1]) { selfCollied = true; // 表示撞到了自己 } }); if (selfCollied) { // console.log('撞到自己的了'); this.strategies.die.call(this); return; } // 下一個點是牆,代表撞到了圍牆,遊戲結束 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 結束函式下面的程式碼執行,若是上述的情況均為發生,則最後的情況,肯定是空 // 下一個點是空,走 this.strategies.move.call(this); }; // 處理碰撞後的事件 Snake.prototype.strategies = { move: function (format) { // 這個引數用來決定要不要刪除蛇尾 當傳了操作(true)後為吃 // 建立一個新的身體(在舊蛇頭的位置) var newBody = new Square(this.head.x / sw,this.head.y / sh,'snakeBody'); // 更新連結串列的關係 newBody.next = this.head.next; newBody.next.last = newBody; newBody.last = null; this.head.remove(); // 把舊蛇頭從原來的位置刪除 newBody.create(); // 建立一個新的蛇頭,在(nextPos 位置建立) var newHead = new Square(this.head.x / sw + this.direction.x,this.head.y / sh + this.direction.y,'snakeHead'); // 更新連結串列的關係 newHead.last = null; newHead.next = newBody; newHead.next.last = newHead; newHead.viewContent.style.transform = 'rotate(' + this.direction.rotate + 'deg)'; newHead.create(); // 蛇身上的每一個座標進行更新 this.pos.splice(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; // 更新蛇身座標陣列 this.pos.pop(); } },eat: function () { this.strategies.move.call(this,true); createFood(); game.score++; },die: function () { game.over(); } } snake = new Snake(); // 建立食物 function createFood() { // 食物小方塊的隨機座標 var x = null,y = null; var include = true; // 迴圈跳出的條件,true表示隨機生成的座標在蛇身上,繼續讓他迴圈,false表示食物座標不在蛇身上,不迴圈 while (include) { // 0~29隨機數 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) { // 這個條件成立說明現在隨機出的食物座標,並未在蛇身上 include = false; } }); } // 生成食物 food = new Square(x,'food'); food.pos = [x,y]; // 儲存一下生成食物的座標,用於跟蛇頭要走的下一個點做對比 var foodDom = document.querySelector('.food'); if (foodDom) { foodDom.style.left = x * sw + 'px'; foodDom.style.top = y * sh + 'px'; } else { food.create(); } } // 建立遊戲邏輯 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 + '分'); // 遊戲回到最初始的狀態 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'; }
更多有趣的經典小遊戲實現專題,分享給大家:
C++經典小遊戲彙總
python經典小遊戲彙總
python俄羅斯方塊遊戲集合
JavaScript經典遊戲 玩不停
java經典小遊戲彙總
javascript經典小遊戲彙總
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。