话不多说,上图为敬!
上面就是大概的效果了,可能还有很多bug,期待你们发现 =-= !
这个贪吃蛇主要用到了js的定时器和键盘监听事件,通过键盘监听事件来触发定时器(比如点左键,就会触发一个定时器,这个定时器的作用就是每秒使蛇的left变小!),大概就是这么个意思 =-=。
在让我敲一遍也不一定能敲出来=-=,哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈嗝~
好了下面是实现代码
css部分
<style>
.oDiv {
width: 20px;
height: 20px;
border-radius: 20px;
position: absolute;
background-color: brown;
}
#oDiv1 {
width: 500px;
height: 500px;
border: 1px solid #000000;
margin: auto;
background-color: aquamarine;
}
#d{
width: 10px;
height: 10px;
border-radius: 10px;
background-color:black;
position: absolute;
}
</style>
html部分(就两个div,一个是蛇,一个是食物)
<div id="oDiv1">
<div class="oDiv"></div>
<div id="d" style="display: none"></div>
</div>
JavaScript部分
<script>
var NewDiv = null;
var oDiv = document.getElementsByClassName("oDiv");
var oDiv1 = document.getElementById("oDiv1");
var d = document.getElementById("d");
var clc = null;
/*开局5秒后先生成一个食物*/
window.onload = function() {
oDiv[0].style.left = "49%"
oDiv[0].style.top = "27%"
window.setTimeout(function() {
a();
}, 5000)
}
/*随机食物*/
function a() {
d.style.display = "";
d.style.left = (Math.random() * (1209 - 712) + 709) + "px";
d.style.top = (Math.random() * (508 - 13) + 8) + "px";
}
b = setInterval(function() {
/*判断吃到食物后调用随机食物的方法*/
if ((parseInt(d.style.left) - parseInt(oDiv[0].offsetLeft) < 10 && parseInt(d.style.left) - parseInt(oDiv[0].offsetLeft) >
-10) &&
(parseInt(d.style.top) - parseInt(oDiv[0].offsetTop) < 10 && parseInt(d.style.top) - parseInt(oDiv[0].offsetTop) >
-10)) {
a();
NewDiv = document.createElement("div");
oDiv1.appendChild(NewDiv);
NewDiv.className = "oDiv";
tail();
}
/*判断碰到墙壁*/
if (oDiv[0].offsetLeft < oDiv1.offsetLeft || oDiv[0].offsetLeft > oDiv1.offsetLeft + 482 || oDiv[0].offsetTop <
oDiv1.offsetTop || oDiv[0].offsetTop > oDiv1.offsetTop + 482) {
alert("游戏结束!")
clearInterval(clc)
clearInterval(b)
location.reload(true) //reload方法:刷新页面
}
/*判断是否碰到身体*/
for (var i = 5; i < oDiv.length; i++) {
if (oDiv[0].offsetTop == oDiv[i].offsetTop && oDiv[0].offsetLeft == oDiv[i].offsetLeft) {
alert("游戏结束!")
clearInterval(clc)
clearInterval(b)
location.reload(true)
break;
}
}
}, 100)
/*键盘按下判断方向*/
function on() {
switch (event.keyCode) {
case 38:
clearInterval(clc)
clc = setInterval(function() {
oDiv[0].style.top = oDiv[0].offsetTop - 5 + "px";
tail();
}, 50)
break;
case 40:
clearInterval(clc)
clc = setInterval(function() {
oDiv[0].style.top = oDiv[0].offsetTop + 5 + "px";
tail();
}, 50)
break;
case 37:
clearInterval(clc)
clc = setInterval(function() {
oDiv[0].style.left = oDiv[0].offsetLeft - 5 + "px";
tail();
}, 50)
break;
case 39:
clearInterval(clc)
clc = setInterval(function() {
oDiv[0].style.left = oDiv[0].offsetLeft + 5 + "px";
tail();
}, 50)
break;
}
}
/*尾部div跟随前一个div*/
function tail() {
for (var i = oDiv.length - 1; i > 0; i--) {
oDiv[i].style.top = oDiv[i - 1].offsetTop + "px";
oDiv[i].style.left = oDiv[i - 1].offsetLeft + "px";
}
}
</script>