效果展示
CSS样式
index.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="css/index.css">
</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>
index.css
* {
margin: 0;
padding: 0;
}
.content {
width: 640px;
height: 640px;
margin: 100px auto;
position: relative;
}
.btn {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.1);
z-index: 2;
}
.btn button {
background: none;
border: none;
outline: none;
cursor: pointer;
background-size: 100% 100%;
position: absolute;
left: 50%;
top: 50%;
}
.startBtn button {
width: 200px;
height: 80px;
background-image: url(../images/bb40248cdc9948fdbc67f8763b7965b0.gif);
margin-top: -40px;
margin-left: -100px;
}
.pauseBtn {
display: none;
}
.pauseBtn button {
width: 70px;
height: 70px;
background-image: url(../images/f2346ea52af94531915045ceafc009d7.png);
margin-top: -35px;
margin-left: -35px;
}
#snakeWrap {
position: relative;
width: 600px;
height: 600px;
background: #FCE4EC;
border: 20px solid #F8BBD0;
}
#snakeWrap div {
width: 20px;
height: 20px;
}
.snakeHead {
background-image: url(../images/fde4a7ae7f97468a93532e63a16befad.png);
background-size: cover;
}
.snakeBody {
background-color: #9CCC65;
border-radius: 50%;
}
.food {
background-image: url(../images/59d8305e0fed4a908a9ed9cc65a8b72a.png);
background-size: 100% 100%;
}
构造方格
- 需要一个构造方块的函数,用来存放蛇的全身以及蛇要经过的路径
var sw = 20, //一个方块的宽度
sh = 20, //一个方块的高度
tr = 30, //行数
td = 30; //列数
var snake = null, //蛇的实例
food = 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') //方块的父级
}
Square.prototype.create = function() { //创建方块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 = []; //是一个二维数组,存储蛇身上每一个方块的位置
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() { //init用来初始化
//创建蛇头
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]) //把蛇身体2的坐标存起来
//形成链表关系
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
]
//下个点是自己,代表撞到自己,游戏结束
var selfCollied = false;
this.pos.forEach(function(value) {
if (value[0] == nextPos[0] && value[1] == nextPos[1]) {
//如果数组中的两个数都相等,就说明下一个点在蛇身上可以找到,代表撞到自己了。比如:[0,1]和[0,1];两个数组的第一个数都是0,相等;第二个数都是1相等,所以两个数组相等
selfCollied = true;
}
});
if (selfCollied) {
this.strategies.die.call(this);
return;
}
//下个点是围墙,游戏结束
if (nextPos[0] < 0 || nextPos[0] > td - 1 || nextPos[1] < 0 || nextPos[1] > tr - 1) {
this.strategies.die.call(this);
return;
}
//下个点是食物,吃
if (food && food.pos[0] == nextPos[0] && food.pos[1] == nextPos[1]) {
this.strategies.eat.call(this);
return;
}
//下个点什么都不是,走
this.strategies.move.call(this);
};
//处理碰撞后要做的事
Snake.prototype.strategies = {
move: function(format) { //这个参数用于决定要不要删除最后一个方块(蛇尾),当传了这个参数后就表示要做的事情是吃
//创建新的身体(在旧蛇头的位置)
var newBody = new Square(this.head.x / sw, this.head.y / sh, 'snakeBody');
//更新链表的关系
newBody.next = this.head.next;
newBody.next.last = newBody;
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(); //删除数组最后一个元素
}
directionIn = false;
},
eat: function() {
this.strategies.move.call(this, true);
game.score++;
createFood();
directionIn = false;
},
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();
}
}
创建游戏逻辑
按下键盘方向键控制蛇移动方向
- 按键不是只能按一个,如果我们在更新之前,判定了正确的方向,那么这个时候我们再按回头的方向键,就会导致出现回头的情况,我们必须去避免这种bug。(比如:当蛇右运动时,同时或快速按上加左,或下加左,会判定蛇直接倒退。)
- 为了防止回头的情况,需要定义一个变量directionIn来控制键盘监听事件是否执行
- 思路:当我们按下一个方向键时,必须等到蛇移动了一个单位(变量directionIn变成true)后,才会开启键盘事件
//创建游戏逻辑
function Game() {
this.timer = null;
this.score = 0;
}
var directionIn = false;
Game.prototype.init = function() {
snake.init();
// snake.getNextPos();
createFood();
document.addEventListener('keydown', fn)
this.start();
}
var fn = function(e) {
if (directionIn) { //判断是否需要改变方向
return;
}
if (e.keyCode == 37 && snake.direction != snake.directionNum.right) {
snake.direction = snake.directionNum.left;
directionIn = true;
} else if (e.keyCode == 38 && snake.direction != snake.directionNum.down) {
snake.direction = snake.directionNum.up
directionIn = true;
} else if (e.keyCode == 39 && snake.direction != snake.directionNum.left) {
snake.direction = snake.directionNum.right
directionIn = true;
} else if (e.keyCode == 40 && snake.direction != snake.directionNum.up) {
snake.direction = snake.directionNum.down
directionIn = true;
}
}
- 在move中添加: directionIn = false;
Snake.prototype.strategies = {
move: function(format) { //这个参数用于决定要不要删除最后一个方块(蛇尾),当传了这个参数后就表示要做的事情是吃
//创建新的身体(在旧蛇头的位置)
var newBody = new Square(this.head.x / sw, this.head.y / sh, 'snakeBody');
//更新链表的关系
newBody.next = this.head.next;
newBody.next.last = newBody;
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(); //删除数组最后一个元素
}
directionIn = false;
},
定时器
蛇每次吃东西的时候速度都会越来越快,我们需要怎么做到这个过程呢?
- 首先我们给定时器设置一个非常快的帧数,让他会不停的刷新。在这个过程中,我们建立一个变量gamef,让他进行一个快速的自增加的算法。
- 我们吃到食物后,得分是会不断增加的,那么我们就设置一个变量,计算这个差值,当我们的gamef % 变量 ==0的时候,我们才执行snake.getNextPos()函数。
- 什么意思呢?就是我们通过控制snake.getNextPos()函数的更新速度,来达到可以控制蛇速度的方法。假如我们的蛇开始是3,我们让30 - 3 = 27,那么不断变化的gamef 只有 % 27 == 0的时候,才会执行,也就是每次在gamef为27的1的倍数,2的倍数,3的倍数的时候,才会去执行snake.getNextPos()。而吃到食物之后,长度为4,那么每次为26的1的倍数,2的倍数,3的倍数的时候,才会去执行snake.getNextPos()。这样就成功做到了加速蛇的速度的功能。
//定时器
var timerN = 5;
var gamef = 0;
Game.prototype.start = function() {
var gamef = 0;
this.timer = setInterval(function() {
gamef++;
var during = game.score < 30 ? 30 - game.score : 1;
gamef % during == 0 && snake.getNextPos();
}, timerN)
}
开始游戏
//开启游戏
game = new Game();
var startBtn = document.querySelector('.startBtn button')
startBtn.onclick = function() {
startBtn.parentNode.style.display = 'none'
game.init();
}
暂停游戏
- 暂停游戏后点方向键,再点击开始游戏蛇会改变方向。
- 原因:暂停游戏后没有解除键盘监听事件,所以要在游戏暂停时解绑键盘事件
Game.prototype.pause = function() {
clearInterval(this.timer);
document.removeEventListener('keydown', fn) //暂停时解绑键盘事件
}
//暂停游戏
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'
document.addEventListener('keydown', fn) //暂停结束添加键盘事件
}
结束游戏
//结束游戏
Game.prototype.over = function() {
clearInterval(this.timer)
alert('你的得分为: ' + this.score)
//游戏回到最初始状态
var snakeWrap = document.getElementById('snakeWrap')
snakeWrap.innerHTML = '';
snake = new Snake();
game = new Game();
startBtn.parentNode.style.display = 'block'
}