基于javascript實(shí)現(xiàn)貪吃蛇小游戲
本文實(shí)例為大家分享了js貪吃蛇游戲的具體代碼,供大家參考,具體內(nèi)容如下
先不多說先上圖

下面是代碼部分(這里你可以根據(jù)需要改變蛇頭和身體還有食物的圖片,然后默認(rèn)的樣式是使用純顏色的如果沒有更改我的背景圖片的話------改這些圖開始是想搞笑一下朋友哈哈哈,請(qǐng)不要在意哈),還有操作鍵是使用 ↑ ↓ ← → )
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>貪食蛇</title>
<style>
.map {
width: 800px;
height: 600px;
background-color: #ccc;
position: relative;
left: 50%;
transform: translate(-50%);
}
#dv {
color: whitesmoke;
font-weight: 700;
text-align: center;
line-height: 50px;
width: 150px;
height: 50px;
position: absolute;
background-color: orange;
border-radius: 10px;
top: 50%;
left: 50%;
transform: translate(-50%);
cursor: pointer;
}
</style>
</head>
<body>
<div class="map">
<div id="dv">開始游戲</div>
</div>
<script>
//食物:是一個(gè)對(duì)象,有寬,有高,有顏色,有橫縱坐標(biāo)
//自調(diào)用函數(shù)
(function () {
var element = []; //用來保存每個(gè)小方塊食物的
function Food(x, y, width, height, color) {
this.x = x || 0;
this.y = y || 0;
this.width = width || 20;
this.height = height || 20;
this.color = color || "green";
}
//為原型添加初始化的方法(作用:在頁面上顯示這個(gè)食物)
//因?yàn)槭澄镆诘貓D上顯示,所以,需要地圖的這個(gè)參數(shù)(map--就是頁面上的.class=map的這個(gè)div)
Food.prototype.init = function (map) {
//先刪除這個(gè)小食物
//外部無法訪問,此函數(shù)在自調(diào)用函數(shù)里面
remove();
//創(chuàng)建div
var div = document.createElement("div");
//把div加到map里面
map.appendChild(div);
//獲取div的樣式
div.style.width = this.width + "px";
div.style.height = this.height + "px";
div.style.backgroundColor = this.color;
//脫離文檔流
div.style.position = "absolute";
//橫縱坐標(biāo)先停止----隨機(jī)產(chǎn)生
this.x = parseInt(Math.random() * (map.offsetWidth / this.width)) * this.width;
this.y = parseInt(Math.random() * (map.offsetHeight / this.height)) * this.height;
div.style.left = this.x + "px";
div.style.top = this.y + "px";
//把div加入element數(shù)組中
element.push(div);
//改變食物的樣式---改成自己喜歡的東西
div.style.backgroundImage = "url(" + "../images/shi.png" + ")";
div.style.backgroundRepeat = "no-repaet";
div.style.backgroundSize = "cover";
};
//私有函數(shù)
function remove() {
for (var i = 0; i < element.length; i++) {
var ele = element[i];
//找到這個(gè)子元素的父級(jí)元素,然后刪除這個(gè)子元素
ele.parentNode.removeChild(ele);
//再次把element中的這個(gè)子元素刪除
element.splice(i, 1);
}
}
//把Food暴露給window,外部可以使用
window.Food = Food;
}());
//自調(diào)用函數(shù)---小蛇
(function () {
//存放小蛇的每個(gè)身體部分
var element = [];
//小蛇的構(gòu)造函數(shù)
function Snake(width, height, driection) {
this.width = width || 20;
this.height = height || 20;
//小蛇的身體
this.body = [{
x: 3,
y: 2,
color: "red"
},
{
x: 2,
y: 2,
color: "orange"
},
{
x: 1,
y: 2,
color: "orange"
}
];
//方向
this.driection = driection || "right";
}
//為原型添加方法---小蛇初始化的方法
Snake.prototype.init = function (map) {
//先刪除之前的小蛇
remove();
//循環(huán)遍歷創(chuàng)建div
for (var i = 0; i < this.body.length; i++) {
//數(shù)組中的每個(gè)數(shù)組元素都是一個(gè)對(duì)象
var obj = this.body[i];
//創(chuàng)建div
var div = document.createElement("div");
//把div加入地圖map中
map.appendChild(div);
//設(shè)置div的樣式
div.style.position = "absolute";
div.style.width = this.width + "px";
div.style.height = this.height + "px";
//橫縱坐標(biāo)
div.style.left = obj.x * this.width + "px";
div.style.top = obj.y * this.height + "px";
//背景顏色
div.style.backgroundColor = obj.color;
//方向還沒定
//把div加入到element數(shù)組中---目的是為了刪除
//把div加入數(shù)組中
element.push(div);
//更改頭部的----變成圖片
if (i == 0) {
div.style.backgroundImage = "url(" + "../images/tou_03.png" + ")";
div.style.backgroundRepeat = "no-repaet";
div.style.backgroundSize = "cover";
}
//更改尾巴的樣式照片
if (i != 0) {
div.style.backgroundImage = "url(" + "../images/shi.png" + ")";
div.style.backgroundRepeat = "no-repaet";
div.style.backgroundSize = "cover";
}
}
};
//為原型添加方法---小蛇動(dòng)起來
Snake.prototype.move = function (food, map) {
var i = this.body.length - 1;
for (; i > 0; i--) {
this.body[i].x = this.body[i - 1].x;
this.body[i].y = this.body[i - 1].y;
}
//判斷方向---改變小蛇的頭的坐標(biāo)位置
switch (this.driection) {
case "left":
this.body[0].x -= 1;
break;
case "right":
this.body[0].x += 1;
break;
case "top":
this.body[0].y -= 1;
break;
case "bottom":
this.body[0].y += 1;
break;
}
//判斷有沒有吃到食物
//小蛇的頭的坐標(biāo)和食物的坐標(biāo)一致
var headX = this.body[0].x * this.width;
var headY = this.body[0].y * this.height;
//判斷小蛇的頭和食物坐標(biāo)是否相同
if (headX == food.x && headY == food.y) {
//獲取小蛇的最后的尾巴
var last = this.body[this.body.length - 1];
//把最后的蛇尾復(fù)制一個(gè),重新的加入到小蛇的body中
this.body.push({
x: last.x,
y: last.y,
color: last.color
});
//把食物刪除,重新初始化食物
food.init(map);
}
};
//刪除小蛇的私有函數(shù)
function remove() {
//獲取數(shù)組
var i = element.length - 1;
for (; i >= 0; i--) {
var ele = element[i];
//從map地圖上刪除這個(gè)子元素div
ele.parentNode.removeChild(ele);
element.splice(i, 1);
}
}
window.Snake = Snake;
}());
//自調(diào)用函數(shù)---游戲?qū)ο?
(function () {
var that = null;
//游戲的構(gòu)造函數(shù)
function game(map) {
this.food = new Food(); //食物對(duì)象
this.snake = new Snake(); //小蛇對(duì)象
this.map = map; //地圖
that = this;
}
game.prototype.init = function () {
//初始化游戲
//食物初始化
this.food.init(this.map);
//小蛇初始化
this.snake.init(this.map);
that = this;
document.getElementById("dv").onclick = function () {
document.getElementById("dv").style.display = "none";
//調(diào)用小蛇移動(dòng)的方法
that.runSnake(that.food, that.map);
//調(diào)用按鍵的方法
that.bindKey();
}.bind(that);
};
//添加原型方法---設(shè)置小蛇可以自動(dòng)跑起來
game.prototype.runSnake = function (food, map) {
//自動(dòng)的去移動(dòng)
var time = 90;
var fn = function () {
//此時(shí)this是window
//移動(dòng)小蛇
this.snake.move(food, map);
//初始化小蛇
this.snake.init(map);
//橫坐標(biāo)的最大值
var maxX = map.offsetWidth / this.snake.width;
//縱坐標(biāo)的最大值
var maxY = map.offsetHeight / this.snake.height;
//小蛇的頭的坐標(biāo)
var headX = this.snake.body[0].x;
var headY = this.snake.body[0].y;
//判斷 橫坐標(biāo) 有沒撞墻
if (headX < 0 || headX >= maxX) {
//撞墻停止定時(shí)器
clearInterval(timeId);
alert("游戲結(jié)束");
location.reload();
}
//判斷 縱坐標(biāo) 有沒撞墻
if (headY < 0 || headY >= maxY) {
clearInterval(timeId);
alert("游戲結(jié)束");
location.reload();
}
//判斷 小蛇的頭部 有沒有 撞到自己
for (let i = 1; i < this.snake.body.length; i++) {
let x = this.snake.body[i].x;
let y = this.snake.body[i].y;
if (headX === x && headY === y) {
clearInterval(timeId);
alert("游戲結(jié)束");
location.reload();
}
}
//增加游戲難度,判斷 到達(dá)一定數(shù)量的時(shí)候 加速
switch (true) {
case 5 <= this.snake.body.length && this.snake.body.length <= 10:
clearInterval(timeId);
time = 60;
timeId = setInterval(fn, time);
break;
case 10 <= this.snake.body.length && this.snake.body.length <= 15:
clearInterval(timeId);
time = 40;
timeId = setInterval(fn, time);
break;
case 15 <= this.snake.body.length:
clearInterval(timeId);
time = 30;
timeId = setInterval(fn, time);
break;
}
console.log(this.snake.body.length + "--" + "time:" + time);
}.bind(that);
//定時(shí)器小蛇自運(yùn)動(dòng)
var timeId = setInterval(fn, time);
};
//添加原型方法---設(shè)置用戶按鍵,改變小蛇移動(dòng)的方向
game.prototype.bindKey = function () {
//獲取用戶的按鍵,改變小蛇的移動(dòng)方向
document.addEventListener("keydown", function (e) {
//獲取按鍵的值并進(jìn)行判斷是,改變小蛇移動(dòng)的方向
switch (e.keyCode) {
//沒有bind方法時(shí)此時(shí)的this指向的是documen
case 37:
if (this.snake.driection != "right") {
this.snake.driection = "left";
}
break;
case 38:
if (this.snake.driection != "bottom") {
this.snake.driection = "top";
}
break;
case 39:
if (this.snake.driection != "left") {
this.snake.driection = "right";
}
break;
case 40:
if (this.snake.driection != "top") {
this.snake.driection = "bottom";
}
break;
}
}.bind(that), false);
};
//把game暴露給window,外部就可以訪問game對(duì)象
window.game = game;
}());
//初始化游戲?qū)ο?
var gm = new game(document.querySelector(".map"));
//初始化游戲---開始游戲
gm.init();
</script>
</body>
</html>
我已經(jīng)盡量給以上代碼注上注釋。希望能幫到更多朋友更好的理解貪食蛇游戲的實(shí)現(xiàn)思路!
小編還為大家準(zhǔn)備了精彩的專題:javascript經(jīng)典小游戲匯總
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- js實(shí)現(xiàn)貪吃蛇小游戲(容易理解)
- 20行js代碼實(shí)現(xiàn)的貪吃蛇小游戲
- 純js和css完成貪吃蛇小游戲demo
- js實(shí)現(xiàn)貪吃蛇小游戲
- JS學(xué)習(xí)筆記之貪吃蛇小游戲demo實(shí)例詳解
- 基于javascript實(shí)現(xiàn)貪吃蛇經(jīng)典小游戲
- jsp網(wǎng)頁實(shí)現(xiàn)貪吃蛇小游戲
- js猜數(shù)字小游戲的簡單實(shí)現(xiàn)代碼
- JavaScript編寫連連看小游戲
- JavaScript實(shí)現(xiàn)打地鼠小游戲
- js實(shí)現(xiàn)九宮格拼圖小游戲
- 原生javascript制作貪吃蛇小游戲的方法分析
相關(guān)文章
單行 JS 實(shí)現(xiàn)移動(dòng)端金錢格式的輸入規(guī)則
這篇文章主要介紹了單行 JS 實(shí)現(xiàn)移動(dòng)端金錢格式的輸入規(guī)則,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-05-05
JS異步編程之generator與async/await語法糖詳解
這篇文章主要為大家詳細(xì)介紹了JS異步編程中g(shù)enerator與async/await語法糖的使用,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以學(xué)習(xí)一下2022-11-11
一文搞懂JavaScript中bind,apply,call的實(shí)現(xiàn)
bind、call和apply都是Function原型鏈上面的方法,因此不管是使用function聲明的函數(shù),還是箭頭函數(shù)都可以直接調(diào)用。本文就帶你看看如何實(shí)現(xiàn)bind、call和apply2022-06-06
TypeScript魔法堂之枚舉的超實(shí)用手冊(cè)
這篇文章主要介紹了TypeScript魔法堂之枚舉的超實(shí)用手冊(cè),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
javascript中關(guān)于&& 和 || 表達(dá)式的小技巧分享
我將會(huì)介紹和解析12個(gè)簡單但是強(qiáng)大的JavaScript技巧. 這些技巧所有的JavaScript程序員都可以馬上使用, 你不需要成為JavaScript高手才能理解這些.下面我們開始本系列的第一篇文章,介紹下強(qiáng)大的&& 和 || 表達(dá)式2015-04-04
微信小程序手動(dòng)添加收貨地址省市區(qū)聯(lián)動(dòng)
這篇文章主要為大家詳細(xì)介紹了微信小程序手動(dòng)添加收貨地址省市區(qū)聯(lián)動(dòng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-05-05

