<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
body{
width: 100%;
height: 100%;
position: relative;
background-color: green;
}
#head{
width: 30px;
height: 30px;
border: 1px black solid;
position: absolute;
line-height: 30px;
text-align: center;
position: absolute;
background-color: white;
}
.body{
width: 30px;
height: 30px;
border: 1px black solid;
position: absolute;
left: 30px;
line-height: 30px;
text-align: center;
background-color: white;
}
#tail{
width: 30px;
height: 30px;
border: 1px solid;
position: absolute;
line-height: 30px;
text-align: center;
left: 60px;
background-color: white;
}
#food{
width: 30px;
height: 30px;
background-color: yellow;
position: absolute;
left: 300px;
top: 300px;
}
</style>
</head>
<body>
<div id="snake">
<div id="head">头</div>
<div class="body">身</div>
<div id="tail">尾</div>
</div>
<div id="food"></div>
<script>
var body = document.getElementsByClassName('body');
// 移动
var speedX = 0;
var speedY = 30;
function snakeMove(){
var x = head.offsetLeft + speedX;
var y = head.offsetTop + speedY;
for(var i = snake.children.length-1;i>0;i--){
snake.children[i].style.left = snake.children[i-1].offsetLeft + "px";
snake.children[i].style.top = snake.children[i-1].offsetTop + "px";
}
eat(x,y);
head.style.left = x + "px";
head.style.top = y + "px";
}
// 循环定时器
var timer = setInterval(snakeMove,800);
// 绑定按键
document.addEventListener("keydown",function(event){
switch(event.keyCode){
case 37:
if(speedX == 0){
speedX = -30;
speedY = 0;
}
if(speedX == 30){
return false;
}
break;
case 38:
if(speedY == 0){
speedX = 0;
speedY = -30;
}
if(speedY == 30){
return false;
}
break;
case 39:
if(speedX == 00){
speedX = 30;
speedY = 0;
}
if(speedX == -30){
return false;
}
break;
case 40:
if(speedY == 00){
speedX = 0;
speedY = 30;
}
if(speedY == -30){
return false;
}
break;
default:
return;
break;
}
snakeMove();
},false);
// 创建身体
function createBody(){
var ndiv = document.createElement('div');
ndiv.style.left = head.offsetLeft + "px";
ndiv.style.top = head.offsetTop + "px";
ndiv.className = "body";
ndiv.innerText = "身";
snake.insertBefore(ndiv,snake.children[1]);
}
// 随机函数
function rndNum(min,max){
return Math.floor(Math.random() * (max - min +1 ) + min);
}
// 创建食物
function createFood(){
var maxWidth = document.documentElement.clientWidth - food.offsetWidth;
var maxHeight = document.documentElement.clientHeight - food.offsetHeight;
var x = rndNum(0,maxWidth);
var y = rndNum(0,maxHeight);
food.style.left = x + "px";
food.style.top = y + "px";
}
// 吃掉食物
function eat(x,y){
if(x == food.offsetLeft && y ==food.offsetTop){
createBody();
createFood();
}
}
</script>
</body>
</html>
当head和food坐标重叠的时候,判定为吃掉食物,但新创建的食物会出现在head无法与之重叠的地方,吃完第一次之、后,吃不了第二次了,请高手帮解决
主要是随机数的问题,怎样让随机出来的数能整除30