JSFiddle - React, Tailwind, and code Playground

by Ksenia Polyakova

HTML

<div class="snake" id="snake">
   
 </div>

CSS

.snake {
  background: gray;
  position: relative;
  overflow: hidden;
}

.snake__item {
  background: green;
  border: 3px double white;
  position: absolute;
  box-sizing: border-box;
  z-index: 1;
  opacity: 1;
  transition-property: left, top, opacity, background-color;
  transition-timing-function: ease-in-out;
  transition-duration: 0.5s;
}

.snake__item_die {
  opacity: 0;
  background-color: red;
}

.snake__item_in-stomach {
  background: orange;
  z-index: 3;
}

.snake__food {
  position: absolute;
  background: blue;
  border: 3px double white;
  box-sizing: border-box;
  z-index: 2;
  transition-property: opacity, background-color;
  transition-timing-function: ease-in-out;
  transition-duration: 0.5s;
}

.snake__item_die {
  opacity: 0;
  background-color: red;
}

JavaScript

function Snake(options) {
	this.options = options;
  this.element = this.options.element;
  this.snake = [];
  this.food = [];
  this.init();
}

Snake.prototype.init = function() {
	this.initField();
  this.initSnake();
  this.generateFood(this.options.food.itemsCount);
  this.stepFunction();
  this.listen();
}

Snake.prototype.initField = function() {
	this.element.style.width = (this.options.field.sizeX*this.options.cellSize)+'px';
  this.element.style.height = (this.options.field.sizeY*this.options.cellSize)+'px';
}

Snake.prototype.initSnake = function() {
	for (var i = 0, len = this.options.snake.minSize; i < len; i++) {
  	var snakeItem = document.createElement('div');
    
    snakeItem.className = 'snake__item';
    snakeItem.style.width = 
    	snakeItem.style.height = this.options.cellSize+'px';
     
    snakeItem.style.top = 0;
    snakeItem.style.left = (i*this.options.cellSize)+'px';
    
    this.snake.push({
    	element: snakeItem,
      posX: i,
      posY: 0,
      direction: 'right',
    });
    
    this.element.appendChild(snakeItem);
  }
}

Snake.prototype.move = function() {
	for (var i = 0, len = this.snake.length; i < len; i++) {
  	var snakeItem = this.snake[i];
    if (snakeItem.in_stomach) {
    	if (snakeItem.posX === this.snake[i+1].posX && snakeItem.posY === this.snake[i+1].posY) {
      	snakeItem.in_stomach = false;
      	snakeItem.element.className = 'snake__item';
      }
    	
      continue;
  	}
    
  	switch (snakeItem.direction) {
    	case 'left':
      	snakeItem.posX--;
        snakeItem.element.style.left = (snakeItem.posX*this.options.cellSize)+'px';
      	break;
      case 'right':
      	snakeItem.posX++;
        snakeItem.element.style.left = (snakeItem.posX*this.options.cellSize)+'px';
      	break;
      case 'top':
      	snakeItem.posY--;
        snakeItem.element.style.top = (snakeItem.posY*this.options.cellSize)+'px';
      	break;
      case 'bottom':
      	snakeItem.posY++;
       ...