JSFiddle - React, Tailwind, and code Playground

HTML

<!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, i, div, x = 0, y = 0, min = 0, max = 400, flag, 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, 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';
}

//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;
  }
  if(x < 0) x = 0;
  if(x >= fields) x =  fields - 1;
  if(x == y && direction == 'right') {
  	 setCell(x, true);
    setCell(x + 1, true);
  
  }

  else {
  	 
 		 setCell(x, true);
  }
}

function generateEat(min, max) {
	y = Math.floor(Math.random() * (max - min) + min);
  setCell(y, true, true);
}

setInterval(move,300);
generateEat(min, max);

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>