Snake Game

by Sebastian Kay

HTML

<canvas id="snakeCanvas" width="400" height="400"></canvas>
<button id="startButton">Start</button>

CSS

body {
  margin: 0;
  padding: 0;
  background-color: #141716;
}

canvas {
  border: 1px solid #ccc;
}

JavaScript

var canvas = document.getElementById("snakeCanvas");
    var ctx = canvas.getContext("2d");
    var gridSize = 20;
    var step = 1;
    var snake = [{ x: 5, y: 5 }];
    var direction = "right";
    var apple = { x: Math.floor(Math.random() * gridSize), y: Math.floor(Math.random() * gridSize) };
    var gameLoop;

    document.getElementById("startButton").addEventListener("click", function() {
      startGame();
    });

    document.addEventListener("keydown", function(e) {
      if (e.key === "ArrowUp" && direction !== "down") {
        direction = "up";
      } else if (e.key === "ArrowDown" && direction !== "up") {
        direction = "down";
      } else if (e.key === "ArrowLeft" && direction !== "right") {
        direction = "left";
      } else if (e.key === "ArrowRight" && direction !== "left") {
        direction = "right";
      }
    });

    function startGame() {
      snake = [{ x: 5, y: 5 }];
      direction = "right";
      apple = { x: Math.floor(Math.random() * gridSize), y: Math.floor(Math.random() * gridSize) };
      clearInterval(gameLoop);
      gameLoop = setInterval(update, 100);
    }

    function update() {
      var head = { x: snake[0].x, y: snake[0].y };
      if (direction === "up") {
        head.y -= step;
      } else if (direction === "down") {
        head.y += step;
      } else if (direction === "left") {
        head.x -= step;
      } else if (direction === "right") {
        head.x += step;
      }

      snake.unshift(head);

      if (head.x === apple.x && head.y === apple.y) {
        apple = { x: Math.floor(Math.random() * gridSize), y: Math.floor(Math.random() * gridSize) };
      } else {
        snake.pop();
      }

      if (head.x < 0 || head.x >= gridSize || head.y < 0 || head.y >= gridSize) {
        clearInterval(gameLoop);
        alert("Game Over!");
      }

      for (var i = 1; i < snake.length; i++) {
        if (snake[i].x === head.x && snake[i].y === head.y) {
          clearInterval(gameLoop);
   ...