本文小編為大家詳細介紹“怎么用JS實現貪吃蛇游戲”,內容詳細,步驟清晰,細節處理妥當,希望這篇“怎么用JS實現貪吃蛇游戲”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。
效果圖:

完整代碼如下:
html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="index.css" > <script src="index.js"></script> </head> <body> <div class="content"> <div class="btn startBtn"><button></button></div> <div class="btn pauseBtn"><button></button></div> <div id="snakeWrap"> <!-- <div class="snakeHead"></div> <div class="snakeBody"></div> <div class="food"></div> --> </div> </div> </body> </html>
css:
.content {
position: relative;
width: 640px;
height: 640px;
margin: 100px auto;
}
.btn {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
background-color: black;
opacity: .1;
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: 80px;
background-image: url(../貪吃蛇/img/btn.gif);
margin-left: -100px;
margin-top: -40px;
}
.pauseBtn {
display: none;
}
.pauseBtn button {
width: 70px;
height: 70px;
background-image: url(../貪吃蛇/img/btn4.png);
margin-left: -35px;
margin-top: -35px;
}
#snakeWrap {
width: 600px;
height: 600px;
background-color: pink;
border: 20px solid purple;
position: relative;
}
/* #snakeWrap div {
width: 20px;
height: 20px;
} */
.snakeHead {
background-image: url(../貪吃蛇/img/snake.png);
background-size: cover;
}
.snakeBody {
background-color: rgb(85, 146, 126);
border-radius: 50%;
}
.food {
background-image: url(../貪吃蛇/img/草莓.png);
background-size: cover;
}js:
window.addEventListener('load', function() {
// 聲明方塊的寬高,行數和列數
var sw = 20,
sh = 20,
tr = 30,
td = 30;
var snake = null, //蛇的實例
food = null, //食物的實例
game = null; //游戲的實例
function Square(x, y, classname) {
this.x = sw * x;
this.y = sh * y;
this.class = classname;
this.viewContent = document.createElement('div'); //方塊對應的DOM元素
this.viewContent.className = this.class;
this.parent = document.getElementById('snakeWrap'); //方塊的父級
}
//創建方塊DOM,并添加到頁面里
Square.prototype.create = function() {
this.viewContent.style.position = 'absolute';
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,
y: 0,
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, 0, 'snakeHead');
snakeHead.create();
this.head = snakeHead; //存儲蛇頭信息
this.pos.push([2, 0]); //把蛇頭的位置存起來
//創建蛇身體1
var snakeBody1 = new Square(1, 0, 'snakeBody');
snakeBody1.create();
this.pos.push([1, 0]); //把蛇身1的坐標存起來
//創建蛇身體2
var snakeBody2 = new Square(0, 0, 'snakeBody');
snakeBody2.create();
this.tail = snakeBody2; //把蛇尾的信息存起來
this.pos.push([0, 0]); //把蛇身1的坐標存起來
//形成鏈表關系
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
];
// console.log(nextPos[0]);
//下個點是自己,游戲結束
var selfCollied = false; //是否撞到自己,默認是否
//value表示數組中的某一項
this.pos.forEach(function(value) {
// console.log(nextPos[0], value[0]);
if (value[0] == nextPos[0] && value[1] == nextPos[1]) {
selfCollied = true;
// console.log(2);
}
});
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;
}
// 下個點是食物,吃
if (food && food.pos[0] == nextPos[0] && food.pos[1] == nextPos[1]) {
//如這條件成立,說明蛇頭走的下一點是食物的點
console.log('撞到食物了');
this.strategies.eat.call(this);
return;
}
// 下個點什么都不是,繼續走
this.strategies.move.call(this);
};
// 處理碰撞后要做的事
Snake.prototype.strategies = {
move: function(format) { //format這個參數用于決定要不要刪除最后一個方塊(蛇尾),當傳了這個參數就表示要做的事情是吃
//創建新身體(在舊蛇頭的位置)
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.next = newBody;
newHead.last = null;
newBody.last = newHead;
newHead.viewContent.style.transform = 'rotate(' + this.direction.rotate + 'deg)';
newHead.create();
//蛇身上的每一個方塊的坐標也要更新
this.pos.splice(0, 0, [this.head.x / sw + this.direction.x, this.head.y / sh + this.direction.y])
this.head = newHead; //還要把this.head的信息更新一下
if (!format) { //如果format的值為false,表示需要刪除(除了吃之外的操作)
this.tail.remove();
this.tail = this.tail.last;
this.pos.pop();
}
},
eat: function() {
this.strategies.move.call(this, true);
createFood();
game.score++;
},
die: function() {
// console.log('die');
game.over();
}
}
snake = new Snake();
//創建食物
function createFood() {
//食物小方塊的隨機坐標
var x = null;
var y = null;
var include = true; //循環跳出的條件,true表示食物坐標在蛇身上。(需要繼續循環)false表示食物的坐標不再蛇身上(不用繼續循環)
while (include) {
x = Math.round(Math.random() * (td - 1));
y = Math.round(Math.random() * (tr - 1));
snake.pos.forEach(function(value) {
if (x != value[0] && y != value[1]) {
//這個條件成立說明現在隨機出來的這個坐標,在蛇身上沒有找到。
include = false;
}
});
}
//生成食物
food = new Square(x, y, '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();
var flag = true;
document.onkeydown = function(ev) {
//當蛇在往右走,不能按左鍵
if (ev.which == 37 && snake.direction != snake.directionNum.right) {
if (flag) {
flag = false;
setTimeout(function() {
snake.direction = snake.directionNum.left;
flag = true;
}, 150)
}
} else if (ev.which == 38 && snake.direction != snake.directionNum.down) {
if (flag) {
flag = false;
setTimeout(function() {
snake.direction = snake.directionNum.up;
flag = true;
}, 150)
}
} else if (ev.which == 39 && snake.direction != snake.directionNum.left) {
if (flag) {
flag = false;
setTimeout(function() {
snake.direction = snake.directionNum.right;
flag = true;
}, 150)
}
} else if (ev.which == 40 && snake.direction != snake.directionNum.up) {
if (flag) {
flag = false;
setTimeout(function() {
snake.direction = snake.directionNum.down;
flag = true;
}, 150)
}
}
}
this.start();
};
//開始游戲
Game.prototype.start = function() {
this.timer = setInterval(function() {
snake.getNextPos();
}, 150);
};
//暫停游戲
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');
console.log(startBtn);
startBtn.onclick = function() {
startBtn.parentNode.style.display = 'none';
game.init();
};
//暫停游戲
var snakeWrap = document.getElementById('snakeWrap');
console.log(snakeWrap);
var pauseBtn = document.querySelector('.pauseBtn button');
console.log(pauseBtn);
snakeWrap.onclick = function() {
game.pause();
pauseBtn.parentNode.style.display = 'block';
console.log(123);
};
pauseBtn.onclick = function() {
game.start();
pauseBtn.parentNode.style.display = 'none';
}
})讀到這里,這篇“怎么用JS實現貪吃蛇游戲”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。