JS實(shí)現(xiàn)貪吃蛇游戲
本文實(shí)例為大家分享了JS實(shí)現(xiàn)貪吃蛇游戲的具體代碼,供大家參考,具體內(nèi)容如下
html部分:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="./css/index.css" rel="external nofollow" > <title>貪吃蛇小游戲</title> </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> </body> </html>
css部分:
.content{
width: 640px;
height: 640px;
margin: 50px auto;
position: relative;
}
.btn{
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
background-color: rgba(0,0,0,0);
z-index: 1;
}
.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: 150px;
background-image: url('../images/btn1.gif');
margin-left: -100px;
margin-top: -75px;
}
.pauseBtn{
display: none;
}
.pauseBtn button{
width: 70px;
height: 70px;
background-image: url('../images/btn4.png');
margin-left: -35px;
margin-top: -35px;
}
#snakeWrap{
position: relative;
width: 600px;
height: 600px;
background: #FCE4EC;
border: 20px solid #F8BBD0;
}
.snakeHead{
background-image: url('../images/snake.png');
background-size: cover;
}
.snakeBody{
background-color: #9CCC65;
border-radius: 50%;
}
.food{
background: url('../images/food2.png') no-repeat;
background-size: 100% 100%;
}
js部分:
var sw = 20, // 一個(gè)方塊的寬度
sh = 20, // 高度
tr = 30, // 行數(shù)
td = 30; // 列數(shù)
var snake = null, // 蛇的實(shí)例
food = null, // 食物的實(shí)例
game = null; // 游戲?qū)嵗?
// 方塊構(gòu)造函數(shù)
function Square(x,y,classname) {
this.x = x*sw;
this.y = y*sh;
this.class = classname;
this.viewContent = document.createElement('div');
this.viewContent.className = this.class;
this.parent = document.getElementById('snakeWrap');
}
Square.prototype.create = function(){ // 創(chuàng)建方塊dom
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 = []; // 存儲(chǔ)蛇身上的每一個(gè)方塊的位置
this.directionNum = { // 存儲(chǔ)蛇走的方向,用一個(gè)對(duì)象來表示
left:{
x:-1,
y:0,
rotate:180 // 蛇頭旋轉(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; // 存儲(chǔ)蛇頭信息
this.pos.push([2,0]) // 存儲(chǔ)蛇頭位置
// 創(chuàng)建蛇身體
var snakeBody1 = new Square(1,0,'snakeBody');
snakeBody1.create();
this.pos.push([1,0]) // 存儲(chǔ)蛇身1位置
var snakeBody2 = new Square(0,0,'snakeBody');
snakeBody2.create();
this.tail = snakeBody2; // 存儲(chǔ)蛇尾信息
this.pos.push([0,0]) // 存儲(chǔ)蛇身1位置
// 形成鏈表關(guān)系
snakeHead.last = null;
snakeHead.next = snakeBody1;
snakeBody1.last = snakeHead;
snakeBody1.next = snakeBody2;
snakeBody2.last = snakeBody1;
snakeBody2.next = null;
// 給蛇添加一個(gè)屬性,用來表示蛇走的方向
this.direction = this.directionNum.right; // 默認(rèn)往右走
}
// 獲取蛇頭的下一個(gè)位置對(duì)應(yīng)的元素,要根據(jù)元素做不同的事情
Snake.prototype.getNextPos = function() {
var nextPos = [
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) {
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)是食物,吃
if(food && food.pos[0]==nextPos[0] && food.pos[1]==nextPos[1]){
// 如果這個(gè)條件成立說明現(xiàn)在蛇頭要走的下一個(gè)點(diǎn)是食物的那個(gè)點(diǎn);
console.log('吃到食物了');
this.strategies.eat.call(this);
return;
}
// 下個(gè)點(diǎn)什么都不是,走
this.strategies.move.call(this);
};
// 處理碰撞后要做的事
Snake.prototype.strategies = {
move:function(format) { // 該參數(shù)用于決定是否刪除蛇尾
// 創(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)建蛇頭:蛇頭下一個(gè)點(diǎn)
var newHead = new Square(this.head.x/sw+this.direction.x,this.head.y/sh+this.direction.y,'snakeHead');
// 更新鏈表的關(guān)系
newHead.next = newBody;
newHead.last = null;
newBody.last = newHead;
newHead.viewContent.style.transform = 'rotate('+this.direction.rotate+'deg)';
newHead.create();
// 更新蛇身上每一個(gè)方塊的坐標(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
if(!format){ // false: 需要?jiǎng)h除(處理吃之外的操作)
this.tail.remove();
this.tail = this.tail.last;
this.pos.pop();
}
},
eat:function(){
this.strategies.move.call(this,true);
createFood();
game.score++;
},
die:function(){
game.over();
}
}
snake = new Snake();
// snake.init();
// 創(chuàng)建食物
function createFood(){
// 食物的隨機(jī)坐標(biāo)
var x = null;
var y = null;
var include = true; // 循環(huán)跳出的條件,true表示食物坐標(biāo)在蛇身上,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]){
// 坐標(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();
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';
}
游戲截圖:


更多關(guān)于Js游戲的精彩文章,請(qǐng)查看專題: 《JavaScript經(jīng)典游戲 玩不?!?/a>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
js導(dǎo)出table到excel同時(shí)兼容FF和IE示例
js導(dǎo)出table到excel,在百度可以搜索很多的方法,但是其兼容性是相當(dāng)差的,本文制定了一個(gè)可以同時(shí)兼容FF和IE的方法,感興趣的朋友可以參考下2013-09-09
Javascript 強(qiáng)制類型轉(zhuǎn)換函數(shù)
javascript是弱類型的語(yǔ)言,所以強(qiáng)制類型轉(zhuǎn)換還是比較重要的,下面看一下它的幾個(gè)強(qiáng)制轉(zhuǎn)換的函數(shù)2009-05-05
JavaScript數(shù)組去重由慢到快由繁到簡(jiǎn)(優(yōu)化篇)
本文給大家介紹通過indexof去重,hash去重,排序后去重及set去重由慢到快有繁到簡(jiǎn)的方法給大家介紹了js數(shù)組去重的方法,非常不錯(cuò),具有參考借鑒價(jià)值,感興趣的朋友一起看看吧2016-08-08
微信小程序自定義組件傳值 頁(yè)面和組件相互傳數(shù)據(jù)操作示例
這篇文章主要介紹了微信小程序自定義組件傳值 頁(yè)面和組件相互傳數(shù)據(jù)操作,結(jié)合實(shí)例形式分析了微信小程序常見傳值操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2019-05-05
JavaScript 實(shí)現(xiàn)輪播圖特效的示例
這篇文章主要介紹了JavaScript 實(shí)現(xiàn)輪播圖特效,幫助大家更好的制作網(wǎng)頁(yè),完成需求,感興趣的朋友可以了解下2020-11-11
uniapp中scroll-view基礎(chǔ)用法示例代碼
我們?cè)陧?xiàng)目中往往都能遇到實(shí)現(xiàn)左右滑動(dòng)跟上下滑動(dòng)的需求,下面這篇文章主要給大家介紹了關(guān)于uniapp中scroll-view基礎(chǔ)用法的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-11-11
基于layui內(nèi)置模塊(element常用元素的操作)
今天小編就為大家分享一篇基于layui內(nèi)置模塊(element常用元素的操作),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-09-09

