思路
蛇拥有的行为:
能移动、吃食物、变长(加尾巴)
1、蛇身:
编写蛇头、蛇身
通过计时间隔向某方向移动
检测有没有吃到食物,吃到则加尾巴
判断碰撞(蛇吃食物)
2、食物:
编写食物
随机出现
通过计时间隔某时间段出现一个
成品
代码
HTML部分
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="game.css">
<meta name="author" content="一只咸鱼">
<title>贪吃蛇</title>
</head>
<body>
<script src="game.js"></script>
</body>
</html>
CSS部分
* {
padding: 0;
border: 0;
margin: 0;
}
body {
/* background: url("/image/uuu.jpeg"); */
background-color: #31A6FF59;
}
.head {
position: absolute;
z-index: 2;
width: 30px;
height: 30px;
background: url("/images/dog.png") no-repeat 0;
}
.MainBody {
position: absolute;
}
.body {
clear: both;
position: relative;
top: 25%;
left: 25%;
width: 50%;
height: 50%;
background-color: red;
border-radius: 15px;
}
JavaScript部分
var arr = []; //蛇身
var bo = document.body; //获取主体,用于添加元素
//头
var t0 = document.createElement('div');
t0.className = "head";
t0.style.top = '300px';
t0.style.left = '408px';
t0.style.width = '30px';
t0.style.height = '30px';
arr.push(t0);
bo.insertBefore(t0, bo.lastChild);
//身体1
var t1 = document.createElement('div');
t1.className = "MainBody";
t1.style.top = '288px'