javascript實現貪吃蛇經典游戲
js面向對象編程之貪吃蛇,供大家參考,具體內容如下
首先:面向對象編程,我們要找到項目中具體的對象,此處為(食物(food),蛇(snake),游戲本身(game))也可不把游戲本身作為對象,邏輯體現出來即可。
接著分析每個對象的具體的屬性及方法:
1)food 對象:屬性有:位置,大小,顏色;方法有:渲染在頁面,隨機不同位置生成;
2)snake對象:屬性有:位置,大小,總節(jié)數(計分方便),顏色;方法有:渲染在頁面,移動(移動過程中判斷其它)。
3)game對象:游戲邏輯的編寫;
ok 開敲:
1)簡單的靜態(tài)頁面編寫(地圖)
(1)html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/index.css" > <script src="js/food.js"></script> <script src="js/snake.js"></script> <script src="js/game.js"></script> <script src="js/main.js"></script> <title>貪吃蛇</title> </head> <body> <div class="map"></div> </body> </html>
(2)css(如果用邊框來作為限制的邊界,那么box-sizing屬性是必不可少的(以免食物和蛇頭坐標之間存在誤差))
* {
margin: 0;
padding: 0;
}
.map {
position: relative;
height: 600px;
width: 800px;
border: 1px solid #333;
margin: 0 auto;
/* 盒子模型去除邊框 */
box-sizing: border-box;
}
2)food對象編寫(細節(jié)處含注釋)
//cwen加載頁面所有元素
window.addEventListener('load', function() {
//cwen自調用函數,開啟一個新的作用域,避免命名沖突
(function() {
//cwen定義全局變量
//實物數組
var elements = [];
//cwen實物
function Food(options) {
options = options || {};
this.x = options.x || 0;
this.y = options.y || 0;
this.width = options.width || 20;
this.height = options.height || 20;
this.color = options.color || 'yellow';
}
//cwen隨機數函數
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
//cwen渲染
Food.prototype.render = function(map) {
//刪除之前的食物
remove();
//todo動態(tài)創(chuàng)建div實物
var div = document.createElement('div');
map.appendChild(div);
//把div添加給數組
elements.push(div);
//todo隨機設置x,y的值(實物的位置)-----在map中生成隨機位置
// ! 值 = Math.floor(Math.random() * 可能值得總數 + 第一個可能的值)
this.x = getRandom(0, map.offsetWidth / this.width - 1) * this.width;
this.y = getRandom(0, map.offsetHeight / this.height - 1) * this.height;
div.style.position = 'absolute';
div.style.left = this.x + 'px';
div.style.top = this.y + 'px';
div.style.width = this.width + 'px';
div.style.height = this.height + 'px';
div.style.backgroundColor = this.color;
}
function remove() {
//為了刪除干凈,從索引最大的開始循環(huán)刪除
for (var i = elements.length - 1; i >= 0; i--) {
//刪除遍歷到的div
elements[i].parentNode.removeChild(elements[i]);
//刪除數組中的元素1)第幾個開始,2)要刪除個數
elements.splice(i, 1);
}
}
//把Food開放出去
window.Food = Food;
})()
//cwen測試
// var map = document.querySelector('.map');
// var options = { x: 20, y: 20, width: 30, height: 30, color: 'green' };
// //todo不傳值默認為自定義food
// var food = new Food();
// food.render(map);
})
3)snake對象編寫()
window.addEventListener('load', function() {
(function() {
//記錄蛇的每一節(jié)
var elements = [];
//cwen立即執(zhí)行函數,開啟新的作用于,避免命名沖突
function Snake(options) {
options = options || {};
//對象(蛇)每節(jié)的大小
this.width = options.width || 20;
this.height = options.height || 20;
//cwen蛇的總節(jié)數(計分)
this.mark = options.mark || 0;
//對象的移動方向
this.direction = options.direction || 'right';
//對象的身體(蛇節(jié))
this.kont = [{ x: 3, y: 2, color: 'red' }, { x: 2, y: 2, color: 'black' }, { x: 1, y: 2, color: 'black' }];
}
//cwen渲染對象
Snake.prototype.render = function(map) {
//移除之前的蛇
remove();
//循環(huán)輸出對象的身體(蛇節(jié))
for (var i = 0, len = this.kont.length; i < len; i++) {
var obj = this.kont[i];
var div = document.createElement('div');
map.appendChild(div);
//將蛇節(jié)添加入數組
elements.push(div);
//添加樣式
div.style.position = 'absolute';
div.style.width = this.width + 'px';
div.style.height = this.height + 'px';
div.style.left = obj.x * this.width + 'px';
div.style.top = obj.y * this.height + 'px';
div.style.backgroundColor = obj.color;
}
}
//cwen控制蛇移動的方法
//todo傳參food,map 在game中調用move方法也要傳入相應參數
Snake.prototype.move = function(food, map) {
//控制蛇節(jié)的移動(當前蛇節(jié)到下一個蛇節(jié)的位置)
for (var i = this.kont.length - 1; i > 0; i--) {
this.kont[i].x = this.kont[i - 1].x;
this.kont[i].y = this.kont[i - 1].y;
}
//判斷并控制蛇頭移動,判斷蛇頭移動方向
var head = this.kont[0];
switch (this.direction) {
case 'right':
head.x += 1;
break;
case 'left':
head.x -= 1;
break;
case 'top':
head.y -= 1;
break;
case 'bottom':
head.y += 1;
break;
}
//蛇頭碰到食物時處理
// cwen判斷蛇頭是否和食物坐標重合
var headX = head.x * this.width;
var headY = head.y * this.height;
if (headX == food.x && headY == food.y) {
//1,增加蛇節(jié)(找到最后一根蛇節(jié),然后添加給創(chuàng)建的蛇數組)
var last = this.kont[this.kont.length - 1];
this.kont.push({ x: last.x, y: last.y, color: last.color });
//cwen求出蛇節(jié)的總個數(計分)
var mark = this.mark++;
//2,重新渲染食物
food.render(map);
}
}
//刪除之前的蛇
function remove() {
for (var i = elements.length - 1; i >= 0; i--) {
elements[i].parentNode.removeChild(elements[i]);
elements.splice(i, 1);
}
}
//把Snake構造函數暴露出去
window.Snake = Snake;
})()
//測試
// var map = document.querySelector('.map');
// var snake = new Snake();
// snake.render(map);
})
4)game對象編寫,其中一個為無敵版(含細節(jié)注釋)
window.addEventListener('load', function() {
(function() {
//改變計時器內this指向
var that;
function Game(map) {
// var options = { x: 20, y: 20, width: 30, height: 30, color: 'green' };
this.food = new Food();
this.snake = new Snake();
this.map = map;
that = this;
}
//cwen渲染
Game.prototype.start = function() {
// 1.把食物和蛇渲染到頁面
this.food.render(this.map);
this.snake.render(this.map);
// 2.游戲邏輯編寫
//讓蛇動起來
//判斷地圖邊界
// runSnake();
//todo判斷玩法(兩種模式,原理一樣)
goInput();
//通過鍵盤控制蛇頭方向
//! keydown();
//蛇頭碰到食物時處理
//在snake.js中判斷
}
function goInput() {
var it = prompt('try:\n 經典玩法請按1\n 無敵玩法請輸入(博主最帥)\n')
if (it == 1) {
runSnake();
keydown();
} else if (it == '博主最帥') {
runSnake1();
keydown1();
} else {
alert('you input could not be found!!!');
goInput();
}
}
//讓蛇動起來
function runSnake() {
var timeId = setInterval(function() {
// var a = mark;
that.snake.move(that.food, that.map);
that.snake.render(that.map);
//判斷地圖邊界
var maxX = (that.map.offsetWidth) / that.snake.width;
var maxY = (that.map.offsetHeight) / that.snake.height;
var headX = that.snake.kont[0].x;
var headY = that.snake.kont[0].y;
if (headX < 0 || headX >= maxX) {
alert('Game Over ' + '得分為 ' + that.snake.mark);
clearInterval(timeId);
} else if (headY < 0 || headY >= maxY) {
alert('Game Over ' + '成績?yōu)?' + that.snake.mark);
clearInterval(timeId);
}
}, 150)
}
//無敵版本蛇運動
function runSnake1() {
var timeId1 = setInterval(function() {
that.snake.move(that.food, that.map);
that.snake.render(that.map);
//判斷地圖邊界
var maxX = (that.map.offsetWidth - that.snake.width) / that.snake.width;
var maxY = (that.map.offsetHeight - that.snake.height) / that.snake.height;
var headX = that.snake.kont[0].x;
var headY = that.snake.kont[0].y;
if (headX < 0) {
that.snake.kont[0].x = (that.map.offsetWidth - that.snake.width) / that.snake.width;
} else if (headX > maxX) {
that.snake.kont[0].x = 0;
} else if (headY < 0) {
that.snake.kont[0].y = (that.map.offsetHeight - that.snake.height) / that.snake.height;
} else if (headY > maxY) {
that.snake.kont[0].y = 0;
}
}, 50)
}
//通過鍵盤控制蛇頭方向
function keydown() {
document.addEventListener('keydown', function(e) {
//通過事件對象判斷按了哪個鍵 37left,38top,39right,40bottom
// console.log(e.keyCode);
//其在走的同時按下反方向無用
if (e.keyCode == 37 && that.snake.direction != 'right') {
that.snake.direction = 'left';
} else if (e.keyCode == 38 && that.snake.direction != 'bottom') {
that.snake.direction = 'top';
} else if (e.keyCode == 39 && that.snake.direction != 'left') {
that.snake.direction = 'right';
} else if (e.keyCode == 40 && that.snake.direction != 'top') {
that.snake.direction = 'bottom';
}
});
}
function keydown1() {
document.addEventListener('keydown', function(e) {
//通過事件對象判斷按了哪個鍵 37left,38top,39right,40bottom
// console.log(e.keyCode);
//無敵版本四面八方任你行
if (e.keyCode == 37) {
that.snake.direction = 'left';
} else if (e.keyCode == 38) {
that.snake.direction = 'top';
} else if (e.keyCode == 39) {
that.snake.direction = 'right';
} else if (e.keyCode == 40) {
that.snake.direction = 'bottom';
}
});
}
//把Game開放
window.Game = Game;
})()
})
5)main開啟游戲
window.addEventListener('load', function() {
(function(window, undefind) {
//測試
var map = document.querySelector('.map');
var game = new Game(map);
game.start();
})(window, undefined)
})
last but not least
*建議把所有js文件寫在同一個js文件中,可以大大提高加載速度。注意在每個立即執(zhí)行函數前加上‘ ;',以免出錯。
小編還為大家準備了精彩的專題:javascript經典小游戲匯總
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
JavaScript省市區(qū)三級聯(lián)動菜單效果
這篇文章主要為大家詳細介紹了JavaScript省市區(qū)三級聯(lián)動菜單效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-09-09
IE和Firefox的Javascript兼容性總結[推薦收藏]
長久以來JavaScript兼容性一直是Web開發(fā)者的一個主要問題。在正式規(guī)范、事實標準以及各種實現之間的存在的差異讓許多開發(fā)者日夜煎熬2011-10-10
JavaScript之json_動力節(jié)點Java學院整理
這篇文章主要介紹了JavaScript之json,JSON它是一種數據交換格式。有興趣的可以了解一下2017-06-06

