JSFiddle - React, Tailwind, and code Playground

by rga4

HTML

<!DOCTYPE html>
<html>
<head>
  <title>Snake Game</title>
  <style>
    canvas {
      display: block;
      margin: auto;
      background-color: black;
    }
  </style>
</head>
<body>
  <canvas id="gameCanvas" width="300" height="300"></canvas>
  <script>
    // Initialize variables
    const canvas = document.getElementById("gameCanvas");
    const ctx = canvas.getContext("2d");
    let foodX = Math.floor(Math.random() * canvas.width / 10) * 10;
    let foodY = Math.floor(Math.random() * canvas.height / 10) * 10;
    let snakeX = canvas.width / 2;
    let snakeY = canvas.height / 2;
    let direction = "right";
    let score = 0;

    // Create the snake body
    let snakeBody = [
      { x: snakeX, y: snakeY },
      { x: snakeX - 10, y: snakeY },
      { x: snakeX - 20, y: snakeY }
    ];

    function drawFood() {
      ctx.fillStyle = "red";
      ctx.fillRect(foodX, foodY, 10, 10);
    }

    function drawSnake() {
      ctx.fillStyle = "green";
      for (let i = 0; i < snakeBody.length; i++) {
        ctx.fillRect(snakeBody[i].x, snakeBody[i].y, 10, 10);
      }
    }

    function moveSnake() {
      let head = { x: snakeBody[0].x, y: snakeBody[0].y };

      if (direction === "up") head.y -= 10;
      if (direction === "down") head.y += 10;
      if (direction === "left") head.x -= 10;
      if (direction === "right") head.x += 10;

      if (head.x >= canvas.width || head.x < 0 || head.y >= canvas.height || head.y < 0 ||
          snakeBody.some(bodyPart => bodyPart.x === head.x && bodyPart.y === head.y)) {
        alert("Game Over! Your score: " + score);
        location.reload();
      } else {
        snakeBody.unshift(head);

        if (head.x === foodX && head.y === foodY) {
          score++;
          foodX = Math.floor(Math.random() * canvas.width / 10) * 10;
          foodY = Math.floor(Math.random() * canvas.height / 10) * 10;
        } else {
          snakeBody.pop();
        }

        drawFood();
        drawSnake();
      }
    }

  ...