Javascript實(shí)現(xiàn)貪吃蛇小游戲(含詳細(xì)注釋)
本文實(shí)例為大家分享了Javascript實(shí)現(xiàn)貪吃蛇小游戲的具體代碼,供大家參考,具體內(nèi)容如下
前言
原生JavaScript實(shí)現(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, //蛇的實(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,0
function 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); // 將小方塊添加到頁面當(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ì)象來表示
}
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ǔ)起來
// 創(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;
// 添加一條屬性,用來表示蛇走的方向
this.direction = this.directionNum.right; // 默認(rèn)讓蛇往右走
};
// 這個(gè)方法用來獲取蛇頭的下一個(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]) {
//說明蛇頭要走的下一個(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ù)用來決定要不要?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(); // 把舊蛇頭從原來的位置刪除
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的信息更新
// 刪除蛇尾 通過判斷是否吃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è)條件成立說明現(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)專題,分享給大家:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Django1.7+JQuery+Ajax驗(yàn)證用戶注冊(cè)集成小例子
下面是散仙使用Django+Jquery+Ajax的方式來模擬實(shí)現(xiàn)了一個(gè)驗(yàn)證用戶注冊(cè)時(shí),用戶名存在不存在的一個(gè)小應(yīng)用。注意,驗(yàn)證存在不存在使用的是Ajax的方式,不用讓用戶點(diǎn)擊按鈕驗(yàn)證是否存在,需要的朋友可以參考下2017-04-04
JavaScript實(shí)現(xiàn)微信小程序打卡時(shí)鐘項(xiàng)目實(shí)例
這篇文章主要為大家介紹了JavaScript實(shí)現(xiàn)微信小程序打卡時(shí)鐘項(xiàng)目實(shí)例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-04-04
Echarts圖表分析巴西隊(duì)歷年戰(zhàn)績(jī)實(shí)例詳解
這篇文章主要為大家介紹了Echarts圖表分析巴西隊(duì)歷年戰(zhàn)績(jī)實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
Electron啟動(dòng)出現(xiàn)白屏問題的解決方案
對(duì)于 Web 開發(fā)者使用 Electron 構(gòu)建桌面應(yīng)用程序時(shí),經(jīng)常會(huì)遇到如上圖所示的一個(gè)問題,在應(yīng)用窗口創(chuàng)建完成到頁面加載出來的這段時(shí)間里,出現(xiàn)了長(zhǎng)時(shí)間的白屏,本文就來探索基于 Electron 場(chǎng)景下啟動(dòng)白屏的解決方案,需要的朋友可以參考下2024-05-05
微信小程序module.exports模塊化操作實(shí)例淺析
這篇文章主要介紹了微信小程序module.exports模塊化操作,結(jié)合實(shí)例形式簡(jiǎn)單分析了module.exports模塊化的定義與引用相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下2018-12-12

