一、對貪喫蛇進行梳理
1.頁面上的主要元素
- 食物(food)
屬性:寬、高;背景顏色。
方法:顯示食物;刪除食物。 - 小蛇(snake)
屬性:每截身體的寬、高;移動的方向;每截身體的x、y座標和顏色。
方法:顯示小蛇;小蛇的移動;刪除小蛇。 - 地圖(map)
因爲小蛇和食物都是相對於地圖顯示的,所以小蛇和食物都是地圖的子元素是隨機位置顯示的,所以食物和小蛇需要脫離文檔流(設置樣式position: absolute),地圖也需要脫離文檔流(設置樣式position: relative)。
2.遊戲邏輯
- 通過WASD || ↑←↓→控制蛇的移動方向;
- 喫食物,喫到一個食物小蛇的身體長度加1;
- 蛇撞到地圖邊界則遊戲結束;
- 蛇喫到自己則遊戲結束;
- 允許掉頭、不允許後退;
- 要避免食物出現在蛇身所在位置。
二、運行效果圖
三、全部代碼展示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js實現貪喫蛇小遊戲</title>
<style>
* {
margin: 0;
padding: 0;
}
.title {
text-align: center;
margin-top: 20px;
}
.btn {
width: 80px;
height: 30px;
border: 1px solid rgb(51, 50, 50);
background-color: #eee;
margin: 20px auto 0;
display: block;
}
.map {
width: 800px;
height: 400px;
background-color: #ccc;
margin: 0 auto;
position: relative;
}
</style>
</head>
<body>
<h2 class="title">貪喫蛇小遊戲</h2>
<button id="btn" class="btn" type="button">開始遊戲</button>
<div id="map" class="map"></div>
<script>
var map = document.getElementById("map");
// 存放food的數組,用來刪除food
var foodElements = [];
function Food() {
this.x = 0;
this.y = 0;
// Food的width、height和color屬性並不需要修改,所以爲了節省內存空間,採用原型對象的方式創建這三個屬性
Food.prototype.width = 20;
Food.prototype.height = 20;
Food.prototype.color = "green";
// 動態原型模式創建對象。用來完成數據共享,節省內存空間
/*
判斷this.init的類型是不是function
如果不是function則證明是第一次創建對象,則把這個funcion添加到原型中
如果是function,則代表原型中已經有了這個方法,則不需要再添加該方法。
*/
// 初始化food
if (typeof this.init != "function") {
Food.prototype.init = function () {
// 先刪除之前的food
food.remove();
// 創建元素
var div = document.createElement("div");
// 設置food的樣式
div.style.width = this.width + "px";
div.style.height = this.height + "px";
div.style.backgroundColor = this.color;
// 設置爲相對定位
div.style.position = "absolute";
this.x = parseInt(Math.random() * (map.offsetWidth / this.width));
this.y = parseInt(Math.random() * (map.offsetHeight / this.height));
// 設置食物出現的位置不是當前小蛇身體所在位置
for (var i = 0; i < snake.body.length; i++) {
while (this.x == snake.body[i].x && this.y == snake.body[i].y) {
this.x = parseInt(Math.random() * (map.offsetWidth / this.width));
this.y = parseInt(Math.random() * (map.offsetHeight / this.height));
continue;
}
}
div.style.left = this.x * this.width + "px";
div.style.top = this.y * this.height + "px";
// 將食物添加到map和foodElements數組中
map.appendChild(div);
foodElements.push(div);
};
}
// 刪除food
if (typeof this.remove != "function") {
Food.prototype.remove = function () {
for (var i = 0; i < foodElements.length; i++) {
// 刪除該元素
map.removeChild(foodElements[i]);
// 刪除foodElements數組中的內容
foodElements.splice(i, 1);
}
};
}
};
// 存放snake的數組,用來刪除snake
var snakeElements = [];
function Snake() {
this.direction = "right";
this.body = [{
x: 3,
y: 2,
color: "red"
},
{
x: 2,
y: 2,
color: "orange"
},
{
x: 1,
y: 2,
color: "orange"
}
];
// 使用原型對象的方式設置Snake的width和height
Snake.prototype.width = 20;
Snake.prototype.height = 20;
// 動態原型模式創建對象
// 初始化snake
if (!(this.init instanceof Function)) { // 判斷是否爲function的另一種方式
Snake.prototype.init = function () {
this.remove();
for (var i = 0; i < this.body.length; i++) {
// 設置snake的樣式
var obj = this.body[i];
var div = document.createElement("div");
map.appendChild(div);
div.style.width = this.width + "px";
div.style.height = this.height + "px";
div.style.position = "absolute";
div.style.backgroundColor = obj.color;
div.style.left = obj.x * this.width + "px";
div.style.top = obj.y * this.height + "px";
// 設置頭部爲圓角,可省略
while (i == 0) {
switch (this.direction) {
case "right":
div.style.borderTopRightRadius = "15px";
div.style.borderBottomRightRadius = "15px";
break;
case "left":
div.style.borderTopLeftRadius = "15px";
div.style.borderBottomLeftRadius = "15px";
break;
case "top":
div.style.borderTopRightRadius = "15px";
div.style.borderTopLeftRadius = "15px";
break;
case "bottom":
div.style.borderBottomRightRadius = "15px";
div.style.borderBottomLeftRadius = "15px";
break;
}
break;
}
// 將snake的每個節點添加到數組中,以便後期刪除使用
snakeElements.push(div);
}
};
}
// 刪除snake
if (!(this.remove instanceof Function)) {
Snake.prototype.remove = function () {
for (var i = snakeElements.length - 1; i >= 0; i--) {
// 在map中移除snake這個子節點
map.removeChild(snakeElements[i]);
// 刪除snakeElements數組中的內容
snakeElements.splice(i, 1);
}
};
}
// 移動snake
if (!(this.move instanceof Function)) {
Snake.prototype.move = function () {
// 改變小蛇的身體的座標位置
for (var i = this.body.length - 1; i > 0; i--) {
this.body[i].x = this.body[i - 1].x;
this.body[i].y = this.body[i - 1].y;
}
// 根據direction屬性確定蛇頭移動的方向並改變小蛇的頭的座標位置
switch (this.direction) {
case "right":
this.body[0].x += 1;
break;
case "left":
this.body[0].x -= 1;
break;
case "top":
this.body[0].y -= 1;
break;
case "bottom":
this.body[0].y += 1;
break;
}
// 如何讓蛇看起來像是在移動:
// 在小蛇移動後,刪除之前的蛇(刪除方法在init()中調用了),然後重新顯示蛇
this.init();
// 判斷是否喫到食物,喫到則蛇身加一節,刪除喫掉的食物,生成新的食物
// 蛇頭的x、y與食物的x、y均相等則爲喫到食物
if (this.body[0].x == food.x && this.body[0].y == food.y) {
var last = this.body[this.body.length - 1];
this.body.push({
x: last.x,
y: last.y,
color: last.color
});
// 刪除喫掉的食物,生成新的食物
food.init();
}
// 判斷是否撞牆,撞牆 即死
var maxX = map.offsetWidth / this.width; // map中最大的x值
var maxY = map.offsetHeight / this.height; // map中最大的y值
var headX = this.body[0].x; // 蛇頭所在位置的x值
var headY = this.body[0].y; // 蛇頭所在位置的y值
if (headX < 0 || headX > maxX - 1 || headY < 0 || headY > maxY - 1) {
// 清除定時器
clearInterval(timeId);
alert("對不起,您撞牆了,遊戲結束!");
// 移除snake
this.remove();
// 還原Snake中direction和body的初始值,讓蛇恢復原狀
this.direction = "right";
this.body = [{
x: 3,
y: 2,
color: "red"
},
{
x: 2,
y: 2,
color: "orange"
},
{
x: 1,
y: 2,
color: "orange"
}
];
// 重新顯示snake
this.init();
// 結束遊戲
return false;
}
// 判斷是否喫到自己,喫到自己 即死
// 因爲蛇長爲5時才能喫到自己,所以i從4開始
for (var i = 4; i < this.body.length; i++) {
// 如果頭部的x、y與身體某一段的x、y相等則爲喫到自己
if (this.body[0].x == this.body[i].x && this.body[0].y == this.body[i].y) {
// 清除定時器
clearInterval(timeId);
alert("對不起,您把自己吃了,遊戲結束!");
// 移除snake
this.remove();
// 還原Snake中direction和body的初始值,讓蛇恢復原狀
this.direction = "right";
this.body = [{
x: 3,
y: 2,
color: "red"
},
{
x: 2,
y: 2,
color: "orange"
},
{
x: 1,
y: 2,
color: "orange"
}
];
// 重新顯示snake
this.init();
// 結束遊戲
return false;
}
}
};
}
};
// 初始化food和snake
var food = new Food();
var snake = new Snake();
// 顯示food和snake
food.init();
snake.init();
// 給頁面添加鍵盤按下事件,
document.onkeydown = function (e) {
var eve = e || window.event; // 兼容低版本IE
switch (eve.keyCode) {
case 37: // ←鍵的keyCode
case 65: // A鍵的keyCode
if (snake.direction != "right") { // 不允許後退的簡單處理。不過有bug,手速夠快的話還是會後退...
snake.direction = "left";
}
break;
case 38: // ↑鍵的keyCode
case 87: // W鍵的keyCode
if (snake.direction != "bottom") {
snake.direction = "top";
}
break;
case 39: // →鍵的keyCode
case 68: // D鍵的keyCode
if (snake.direction != "left") {
snake.direction = "right";
}
break;
case 40: // ↓鍵的keyCode爲38
case 83: // S鍵的keyCode
if (snake.direction != "top") {
snake.direction = "bottom";
}
break;
}
};
var btn = document.getElementById("btn");
var timeId;
// 給按鈕註冊點擊事件,點擊按鈕開始遊戲
function begin() {
clearInterval(timeId); // 防止多次點擊造成多次觸發setInterval
timeId = setInterval("snake.move()", 200);
};
btn.onclick = begin;
</script>
</body>
</html>
附上在線HTML/CSS/JavaScript代碼運行工具:HTML/CSS/Javascript在線代碼運行工具。
謝謝您的查看,希望能對您有所幫助!