目录
3、现在整条蛇都动起来了,还缺什么呢?那就是蛋,贪吃蛇不吃蛋那将毫无意义!
如题,今天用js实现贪吃蛇小游戏,主要是记录一下以及加深学习,大佬勿喷!
一、搭建最基本的结构
最终效果大概是这样,这里先搭建最基本的结构,html和css方面不过多阐述。
HTML
<body>
<div>
<li id="head"></li>
<div id="hint">点我立刻开始游戏!</div>
</div>
<span>你的分数是  </span>
<input type="hidden">
</body>
CSS
div {
margin: 0 auto;
position: relative;
width: 900px;
height: 900px;
background-color: pink;
}
li {
list-style: none;
position: absolute;
width: 10px;
height: 10px;
background-color: red;
}
#head {
left: 50%;
top: 50%;
background-color: black;
}
span {
position: absolute;
top: 0;
width: 200px;
height: 200px;
font-size: 20px;
background-color: aqua;
}
#hint {
/* top: 50%; */
color: gray;
font-size: 180px;
transform: translateY(40%);
position: absolute;
width: 100%;
height: 500px;
background: rgba(1, 1, 1, 0.5);
cursor: default;
}
</style>
这时我们就有了一个最基本的架构,以及一个🐍头。
二、JS部分
1、先让蛇头动起来
此时肯定是需要先给document加上keydown事件;并且为了避免用户一直按住方向键导致蛇头旋转漂移,我们还得给函数加上防抖函数;
37 38 39 40分别是方向键左上右下的键码
var timeout;//防抖函数
var head = document.querySelector("head");//蛇头,主要控制方向
function start() {
var code = event.keyCode;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(function () {
switch (code) {
case 37: left1(); break;
case 38: top1(); break;
case 39: right1(); break;
case 40: bottom1(); break;
default: ;
}
}, 50)
}
function top1() {//蛇头向上
head.style.top = head.offsetTop - 10 + "px";
clearInterval(moveTo);
moveTo = setInterval(function () {
head.style.top = head.offsetTop - 10 + "px";
// head.style.left = head.offsetLeft + 10 + "px";
}, 200)
}
function right1() {//蛇头向右
head.style.left = head.offsetLeft + 10 + "px";
clearInterval(moveTo);
moveTo = setInterval(function () {
// head.style.top = head.offsetTop + 10 + "px";
head.style.left = head.offsetLeft + 10 + "px";
}, 200)
}
function bottom1() {//蛇头向下
head.style.top = head.offsetTop + 10 + "px";
clearInterval(moveTo);
moveTo = setInterval(function () {
head.style.top = head.offsetTop + 10 + "px";
// head.style.left = head.offsetLeft