<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>贪吃蛇</title>
<style>
*{margin: 0; padding: 0;}
.canvas{width: 400px; height: 400px; position: absolute;}
</style>
</head>
<body>
<div class="canvas"></div>
<script>
//创建二维坐标数组
var zbxArr = [];
//创建画布
var frag = document.createDocumentFragment();
for(var i=0; i<20; i++){
var oneArr = [];
for(var j=0; j<20; j++){
var div = document.createElement('div');
//div.setAttribute('class','item');
div.style.position = 'absolute';
div.style.left = j*20+'px';
div.style.top = i*20+'px';
div.style.width = '20px';
div.style.height = '20px';
// div.style.background = 'black';
div.style.border = '1px solid black';
frag.appendChild(div);
oneArr.push(div);
}
zbxArr.push(oneArr);
}
document.querySelector('.canvas').appendChild(frag);
function drawOneSquare(location,color){
//1.通过location能够计算出,想要设置颜色的色块的margin值
//2.在二维数组中 查找哪一个色块的margin值和【通过location计算的值】相等
//3.把在二维数组中找到的这个色块 填充颜色
for(var i=0; i<zbxArr.length; i++){
//在画布中纵向查找20行
for(var j=0; j<zbxArr[i].length; j++){
//在一行中纵向查找20列
//比对每一个div的margin是否和计算的margin相同
// 找到画布中,横向和纵向的每一个div
var left = zbxArr[i][j].style.left;
var top = zbxArr[i][j].style.top;
//如果相同,证明当前这个div就是想要找到的div
if(
// 意思是比如'20px',从头开始,截取2个,把字符串转变为数字(横向div的值和算法的值相比较)==location对20取余再*20
parseInt(left.substring(0,left.length-2))==(location%20*20)&&
// 纵向div的值和算法的值相比较,
parseInt(top.substring(0,top.length-2))==(
// 向下取整,location除以20再*20
Math.floor(location/20)*20)
){
// 找到了数组中的某个div后,定义一个颜色
zbxArr[i][j].style.backgroundColor = color;
}
}
}
}
</script>
</body>
</html>