效果展示
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 = n