JSFiddle - React, Tailwind, and code Playground
HTML
<div id="output"></div>
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;
}
JavaScript
let fields = 20 * 20, i, div, x = 0, 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);
}
}
createMatrix();
function setCell(num, val) {
let output = document.getElementById('output');
let cell = output.children[num];
if(val)
cell.style.backgroundColor = 'red';
else
cell.style.backgroundColor = 'transparent';
}
//setCell(0, true);
function move() {
setCell(x, false);
switch (direction) {
case 'right': x++; break;
case 'left': x--; break;
case 'up': x - 20; break;
case 'down': x + 20; break;
}
setCell(x, true);
}
setInterval(move,1000);
document.onkeydown = function(e) {
switch (e.keyCode) {
case 37: direction = 'left';
case 38: direction = 'up';
case 39: direction = 'right';
case 40: direction = 'down';
}
}