JSFiddle - React, Tailwind, and code Playground

by Luis Pulido Diaz

JavaScript

/* create the snake game from nokia */
var canvas = document.createElement('canvas');
canvas.width = 600;
canvas.height = 400;
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
var snake = {
  x: canvas.width / 2,
  y: canvas.height / 2,
  dx: 0,
  dy: 0,
  size: 10,
  speed: 5,
  tail: [],
  tailSize: 5,
  tailColor: '#00ff00',
  headColor: '#ff0000',
  draw: function() {
    ctx.fillStyle = this.tailColor;
    for (var i = 0; i < this.tail.length; i++) {
      ctx.fillRect(this.tail[i].x, this.tail[i].y, this.size, this.size);
    }
    ctx.fillStyle = this.headColor;
    ctx.fillRect(this.x, this.y, this.size, this.size);
  },
  update: function() {
    this.x += this.dx;
    this.y += this.dy;
    if (this.x < 0) {
      this.x = canvas.width;
    }
    if (this.x > canvas.width) {
      this.x = 0;
    }
    if (this.y < 0) {
      this.y = canvas.height;
    }
    if (this.y > canvas.height) {
      this.y = 0;
    }
    this.tail.push({x: this.x, y: this.y});
    while (this.tail.length > this.tailSize) {
      this.tail.shift();
    }
  }
};
var apple = {
  x: 0,
  y: 0,
  size: 10,
  color: '#ff0000',
  draw: function() {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, this.size, this.size);
  },
  update: function() {
    if (snake.x === this.x && snake.y === this.y) {
      snake.tailSize++;
      this.x = Math.floor(Math.random() * (canvas.width / this.size)) * this.size;
      this.y = Math.floor(Math.random() * (canvas.height / this.size)) * this.size;
    }
  }
};
var keys = {
  up: false,
  down: false,
  left: false,
  right: false,
  update: function() {
    if (this.up) {
      snake.dy = -snake.speed;
      snake.dx = 0;
    }
    if (this.down) {
      snake.dy = snake.speed;
      snake.dx = 0;
    }
    if (this.left) {
      snake.dx = -snake.speed;
      snake.dy = 0;
    }
    if (this.right) {
      snake.dx = snake.speed;
      snake.dy = 0;
    }
  }
};
function update() {
  snake.update();
 ...