JSFiddle - React, Tailwind, and code Playground

by frogggeee McFrogggeee

HTML

<!DOCTYPE html>
<html>
<head>
<body>
<h1>snake</h1>
<canvas id = "canvas" width = "400" height = "400"></canvas>
<script>
let ctx = document.getElementById("canvas").getContext("2d");
let tail = [];
let TL = 5;
let aX = 200; // apple x and y
let aY = 300;
let hX = 200; // head x and y
let hY = 200;
let mX = 0;
let mY = 0;
document.addEventListener("keydown", function down(e) {
if (e.keyCode == 38) {
  mX = 0;
  mY = -20;
} else if (e.keyCode == 39) {
	mX = 20;
  mY = 0;
} else if (e.keyCode == 40) {
	mX = 0;
  mY = 20;
} else if (e.keyCode == 37) {
	mX = -20;
  mY = 0;
}
});
function block(x, y, w, h, c) {
	ctx.beginPath();
  ctx.rect(x, y, w, h);
  ctx.fillStyle = c;
  ctx.fill();
  ctx.closePath();
}
function render() {
  hX += mX;
  hY += mY;
	ctx.clearRect(0, 0, 400, 400);
	block(0, 0, 400, 400, "black");
  block(aX, aY, 20, 20, "red");
  block(hX, hY, 20, 20, "green");
  tail.push(hX);
  tail.push(hY);
  if (tail.length > TL) {
  	tail.shift();
  }
  if (aX == hX && aY == hY) {
  	aX = Math.floor(Math.random() * 20) * 20;
    aY = Math.floor(Math.random() * 20) * 20;
    TL++;
  }
  for (let i = 0; i < TL * 2; i += 2) {
  	block(tail[i], tail[i + 1], 20, 20, "lime");
  }
}
setInterval(render, 100);
</script>
</body>
</head>
</html>