Пытался-не получилось
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
<style type="text/css">
#output {
width:400px;
height:400px;
border-top: 1px solid gray;
border-left: 1px solid gray;
}
.inner {
border-bottom: 1px solid gray;
border-right: 1px solid gray;
width:19px;
height:19px;
float: left;
}
</style>
</head>
<body>
<div id="output"></div>
<script>
"use strict"
let fields = 20 * 20, min = 1, max = 400, i, div, x = 0, y = 0, flag = false, direction = 'right', ar = [];
function createMatrix() {
let output = document.getElementById('output');
for(i = 0; i < fields; i+=1) {
div = document.createElement('div');
div.className = 'inner';
output.appendChild(div);
ar.push(div);
}
}
createMatrix();
function setCell(num, val, eat) {
let output = document.getElementById('output');
let cell = output.children[num];
if(val)
cell.style.backgroundColor = 'red';
else
cell.style.backgroundColor = 'transparent';
if(eat)
cell.style.backgroundColor = 'green';
}
function getCell(num) {
return num;
}
//setCell(0, true);
function move() {
for(i = 0; i < fields; i+=1) {
ar[i] = 0;
setCell(ar[i], false);
switch (direction) {
case 'right': ar[i] = ar[i+1]; break;
case 'left': ar[i] = ar[i-1]; break;
//case 'up': x -= 20; break;
//case 'down': x += 20; break;
}
if(ar[i] < 0) ar[i] = 0;
if(ar[i] >= fields) ar[i] = fields - 1;
if(ar[i] == y) {
setCell(ar[i], true);
setCell(ar[i+1], true);
}
else setCell(ar[i], true);
}
}
function generateEat(min, max) {
y = Math.floor(Math.random() * (max - min) + min);
setCell(y, false, true);
return y;
}
setInterval(move,500);
setInterval(generateEat(min,max),500);
document.onkeydown = function(e) {
switch (e.keyCode) {
case 37: direction = 'left';break;
case 38: direction = 'up';break;
case 39: direction = 'right';break;
case 40: direction = 'down';break;
}
}
</script>
</body>
</html>
|