Snake Game (No Borders)

by slawe

HTML

<h1>🐍 Snake Game (No Borders)</h1>
<canvas id="game" width="400" height="400"></canvas>
<div class="info">
  Score: <span id="score">0</span> |
  Level: <span id="level">1</span>
</div>

CSS

body {
  background: #222;
  font-family: Arial, sans-serif;
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0;
  padding-top: 20px;
}
canvas {
  background: black;
  border: 2px solid white;
}
.info {
  margin-top: 10px;
  font-size: 18px;
}

JavaScript

const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");

const box = 20;
const rows = canvas.width / box;

let snake = [{ x: 9 * box, y: 9 * box }];
let direction = "RIGHT";
let food = spawnFood();
let score = 0;
let level = 1;
let speed = 200;
let game;

function spawnFood() {
  return {
    x: Math.floor(Math.random() * rows) * box,
    y: Math.floor(Math.random() * rows) * box,
  };
}

function update() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Draw food
  ctx.fillStyle = "red";
  ctx.fillRect(food.x, food.y, box, box);

  // Move snake
  let head = { ...snake[0] };

  switch (direction) {
    case "LEFT": head.x -= box; break;
    case "UP": head.y -= box; break;
    case "RIGHT": head.x += box; break;
    case "DOWN": head.y += box; break;
  }

  // Wrap around the edges
  if (head.x >= canvas.width) head.x = 0;
  if (head.x < 0) head.x = canvas.width - box;
  if (head.y >= canvas.height) head.y = 0;
  if (head.y < 0) head.y = canvas.height - box;

  // Check collision with self
  if (snake.some((seg, i) => i > 0 && seg.x === head.x && seg.y === head.y)) {
    clearInterval(game);
    alert("Game Over! Final Score: " + score);
    location.reload();
    return;
  }

  snake.unshift(head);

  // Check food
  if (head.x === food.x && head.y === food.y) {
    score++;
    food = spawnFood();
    updateScoreLevel();
  } else {
    snake.pop();
  }

  // Draw snake
  snake.forEach((s, i) => {
    ctx.fillStyle = i === 0 ? "lime" : "green";
    ctx.fillRect(s.x, s.y, box, box);
  });
}

function updateScoreLevel() {
  document.getElementById("score").innerText = score;
  let newLevel = Math.floor(score / 5) + 1;
  if (newLevel !== level) {
    level = newLevel;
    document.getElementById("level").innerText = level;
    speed = Math.max(50, 200 - (level - 1) * 20);
    clearInterval(game);
    game = setInterval(update, speed);
  }
}

document.addEventListener("keydown", (e) => {
  if (e.key === "ArrowLeft" &&...