JSFiddle - React, Tailwind, and code Playground

by Julien Etienne

HTML

<canvas id="canvas"></canvas>

JavaScript

var Base = Base || {};
Base.Snake = function() {
  // Create the Canvas Object tell it 2d
  var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d'),
    w = canvas.width,
    h = canvas.height,
    settings = {
      speed: 60,
      blockSize: 10
    },
    opt = settings,
    snake_array,
    direction,
    food,
    score,
    registered = false,
    player,
    PHPplayer;

  function init() {
    direction = 'right';
    score = 0;
    opt.speed = 60;
    create_snake();
    create_food();
    getHighScore();
    // game_loop is == a number/object when it kicks in
    // then we clearInterval, if not we start fresh
    if (typeof game_loop != "undefined") {
      clearInterval(game_loop);
    }
    game_loop = setInterval(paint, opt.speed);
  }

  function paintCanvas() {
    ctx.fillStyle = 'yellow';
    ctx.fillRect(0, 0, w, h);
  }

  function create_snake() {
    var length = 5;
    snake_array = []
    for (i = length - 1; i >= 0; i--) {
      snake_array.push({
        x: i,
        y: 0
      });
    }
  }

  function create_food() {
    food = {
      x: Math.round(Math.random() * (w - opt.blockSize) / opt.blockSize),
      y: Math.round(Math.random() * (h - opt.blockSize) / opt.blockSize),
    };
    if (check_collision(food.x, food.y, snake_array)) {
      create_food();
    }
  }

  function paint() {
      paintCanvas()
      var nx = snake_array[0].x;
      var ny = snake_array[0].y;
      if (direction == "right") {
        nx++;
      } else if (direction == "left") {
        nx--;
      }
      // If we're going up then we're subtracting from the y axis
      else if (direction == "up") {
        ny--;
      }
      // If we're going down then we're adding to the y axis
      else if (direction == "down") {
        ny++;
      }
      if (nx == -1 || nx == w / opt.blockSize || ny == -1 || ny == h / opt.blockSize ||
        check_collision(nx, ny, snake_array)) {
        submitInfo(score);
        // Call the init and...