JSFiddle - React, Tailwind, and code Playground

by frogggeee McFrogggeee

HTML

<!DOCTYPE html>
<html>
<head>
<body>
<h1>snake</h1>
<p>by frogggeee</p>
<p id = "score"></p>
<canvas id = "canvas" width = "400" height = "400"></canvas>
<script>
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
let tail = [];
let hX = 200; // snake head x and y
let hY = 200;
let aX = (Math.floor(Math.random() * 20) * 20); // apple x and y
let aY = (Math.floor(Math.random() * 20) * 20); //grid size is 400px, so we multiply here. floor wouldn't work well if the number is below 1, so we multiply it in 2 parts.
let mX = 0; // move x and y
let mY = 0;
let TL = 5; // tail length
let score = 0;
document.addEventListener("keydown", keyPressed, false);
function keyPressed(e) {
	if (e.keyCode == 37) {
  	// left
    if (mX == 0) {
    mX = -20;
    mY = 0;
    }
  }
  if (e.keyCode == 38) {
  	// up
    if (mY == 0) {
    mX = 0;
    mY = -20;
    }
  }
  if (e.keyCode == 39) {
  	// right
    if (mX == 0) {
    mX = 20;
    mY = 0;
    }
  }
  if (e.keyCode == 40) {
  	// down
    if (mY == 0) { 
    mX = 0;
    mY = 20;
    }
  }
}
function render() {
  hX = hX + mX;
  hY = hY + mY;
  if (hX > 380) {
  	//hX = 0;
    restart();
  }
  if (hX < 0) {
  	//hX = 380;
    restart();
  }
  if (hY > 380) {
  	//hY = 0;
    restart();
  }
  if (hY < 0) {
  	//hY = 380;
    restart();
  }
  if (tail.length > TL * 2) {
  	tail.shift();
    tail.shift();
  }
	ctx.beginPath();
  ctx.rect(0, 0, 400, 400);
  ctx.fillStyle = "black";
  ctx.fill();
  ctx.closePath();
  for (let i = 0; i < TL * 2; i = i + 2) {
  	ctx.beginPath();
    ctx.rect(tail[i] - 1, tail[i + 1] - 1, 18, 18);
    ctx.fillStyle = "#1aff1a";
    ctx.fill();
    ctx.closePath();
    if (tail[i] == hX && tail[i + 1] == hY) {
    	restart();
    }
  }
	ctx.beginPath();
  ctx.rect(hX - 1, hY - 1, 18, 18);
  ctx.fillStyle = "#009900";
  ctx.fill();
  ctx.closePath();
  ctx.beginPath();
  ctx.rect(aX - 1, aY - 1, 18, 18);
  ctx.fillStyle = "red";
  ctx.fill();
  ctx.closePath();
  if (aX ==...