一时兴起想做个贪吃蛇。
等回头研究研究大神的20行贪吃蛇再来修改。
纪念此论坛第一次发帖,萌新瑟瑟发抖。
2017年12月15日。
<html>
<head>
<meta charset="utf-8">
<title>yn.chn@outlook.com</title>
<style>
#box{
height:400px;
width:400px;
background:#000;
margin:100px auto;
position:relative;
}
h1{
height:10px;
width:10px;
background:#fff;
margin:0;
padding:0;
position:absolute;
top:50px;
left:50px;
}
p{
height:10px;
width:10px;
background:#fff;
margin:0;
padding:0;
position:absolute;
top:300px;
left:300px;
}
span{
height:10px;
width:10px;
background:#fff;
margin:0;
padding:0;
position:absolute;
}
</style>
</head>
<body>
<div id="box">
<h1></h1>
<p></p>
</div>
</body>
<script>
let oBox = document.getElementById("box");
let oH = document.getElementsByTagName("h1")[0];
let oP = document.getElementsByTagName("p")[0];
let x = 10;
let y = 0;
let obj = {"left":300,"top":300};
let list = [];
let length = 0;
let timer = null;
//设置头部运动
function move(){
clearInterval(timer);
timer = setInterval(function(){
oH.style.left = oH.offsetLeft + x + "px";
oH.style.top = oH.offsetTop + y + "px";
//------------------判断边界-------------------
if(oH.offsetLeft > 390 || oH.offsetLeft < 0 || oH.offsetTop < 0 || oH.offsetTop > 390){
clearInterval(timer);
alert("Game Over");
}else{
list.unshift(JSON.parse('{"left":' + oH.offsetLeft +',"top":' + oH.offsetTop + '}'));
list = list.slice(0,length + 2);
}
//----------------判断是否吃到食物---------------
if(oH.offsetLeft == obj.left && oH.offsetTop == obj.top){
length ++;
foodAddress();
refresh();
}else{
refresh();
}
//-----------------判断撞到自己---------------
for(let i = 1;i <=length;i ++){
if(oH.offsetLeft == list[i].left && oH.offsetTop == list[i].top){
clearInterval(timer);
alert("Game Over");
}
}
},100)
}
//--------------刷新尾巴---------------
function refresh(){
let span = oBox.getElementsByTagName("span");
for(let i = 0;i < span.length;i ++){
oBox.removeChild(span[i]);
}
for(let i = 0; i < length;i ++){
let oS = document.createElement("span");
oBox.appendChild(oS);
oS.style.left = list[i + 1].left + "px";
oS.style.top = list[i + 1].top + "px";
}
}
//--------------新增食物---------------
function foodAddress(){
let l = Math.floor(Math.random() * 40) * 10;
let t = Math.floor(Math.random() * 40) * 10;
oP.style.left = l + "px";
oP.style.top = t + "px";
obj =JSON.parse('{"left":' + l +',"top":' + t + '}');
}
move();
//--------------键盘事件----------------
document.onkeydown = function(evt){
let e = evt || event;
switch(e.keyCode){
case 37 : if(y != 0){
x = -10;
y = 0;
};break;
case 39 : if(y != 0){
x = 10;
y = 0;
};break;
case 38 : if(x != 0){
y = -10;
x = 0;
};break;
case 40 : if(x != 0){
y = 10;
x = 0;
};break;
}
move();
}
</script>
</html>