🎮ArcadeLab

PIXEL SNAKE

by ChromeFlame24
595 lines12.0 KB
▶ Play

<!DOCTYPE html>
<html lang="ar">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PIXEL SNAKE</title>
<style>
* {
  box-sizing: border-box;
  -webkit-tap-highlight-color: transparent;
}
body {
  margin: 0;
  min-height: 100vh;
  background: #080d18;
  color: #e8f5ff;
  font-family: Arial, sans-serif;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 16px;
}
.game {
  width: min(100%, 430px);
  text-align: center;
}
h1 {
  color: #5fffd0;
  font-size: 32px;
  letter-spacing: 4px;
  margin: 5px 0 16px;
  text-shadow: 0 0 15px #00e6a0;
}
.stats {
  display: flex;
  justify-content: space-between;
  gap: 8px;
  margin-bottom: 12px;
}
.stat {
  flex: 1;
  background: #121e30;
  border: 1px solid #29445b;
  border-radius: 10px;
  padding: 10px 4px;
}
.stat small {
  color: #8da8bd;
  display: block;
  font-size: 11px;
  margin-bottom: 5px;
}
.stat strong {
  color: #5fffd0;
  font-size: 20px;
}
.board-wrap {
  position: relative;
  width: 100%;
  border: 3px solid #2b5264;
  border-radius: 9px;
  overflow: hidden;
  box-shadow: 0 0 25px #00d9a522;
  background: #0c1724;
  touch-action: none;
}
canvas {
  display: block;
  width: 100%;
  height: auto;
  image-rendering: pixelated;
  touch-action: none;
}
.overlay {
  position: absolute;
  inset: 0;
  background: #07101ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  padding: 20px;
}
.overlay.hidden {
  display: none;
}
.overlay h2 {
  color: #5fffd0;
  font-size: 27px;
  margin: 0 0 10px;
}
.overlay p {
  color: #b8cbd9;
  line-height: 1.6;
}
button {
  border: 0;
  border-radius: 8px;
  padding: 13px 22px;
  background: #37e6b0;
  color: #06151a;
  font-weight: bold;
  font-size: 15px;
  cursor: pointer;
}
button:active {
  transform: scale(.96);
}
.controls {
  display: flex;
  gap: 10px;
  margin-top: 14px;
}
.controls button {
  flex: 1;
}
#pauseBtn {
  background: #243b52;
  color: white;
}
.hint {
  color: #7794a9;
  font-size: 12px;
  margin-top: 13px;
}
</style>
</head>
<body>

<div class="game">
  <h1>PIXEL SNAKE</h1>

  <div class="stats">
    <div class="stat">
      <small>SCORE</small>
      <strong id="score">0</strong>
    </div>
    <div class="stat">
      <small>LEVEL</small>
      <strong id="level">1</strong>
    </div>
    <div class="stat">
      <small>BEST</small>
      <strong id="best">0</strong>
    </div>
  </div>

  <div class="board-wrap">
    <canvas id="board" width="320" height="320"></canvas>

    <div class="overlay" id="overlay">
      <h2 id="overlayTitle">PIXEL SNAKE</h2>
      <p id="overlayText">اجمع التفاح وتجنب الصخور وجسم الثعبان.</p>
      <button id="startBtn">START GAME</button>
    </div>
  </div>

  <div class="controls">
    <button id="pauseBtn">PAUSE</button>
    <button id="restartBtn">RESTART</button>
  </div>

  <div class="hint">اسحب بإصبعك على لوحة اللعب لتغيير الاتجاه</div>
</div>

<script>
const canvas = document.getElementById("board");
const ctx = canvas.getContext("2d");

const scoreEl = document.getElementById("score");
const levelEl = document.getElementById("level");
const bestEl = document.getElementById("best");
const overlay = document.getElementById("overlay");
const overlayTitle = document.getElementById("overlayTitle");
const overlayText = document.getElementById("overlayText");
const startBtn = document.getElementById("startBtn");
const pauseBtn = document.getElementById("pauseBtn");
const restartBtn = document.getElementById("restartBtn");

const SIZE = 16;
const COUNT = 20;

let snake, direction, nextDirection;
let apple, rocks;
let score = 0;
let level = 1;
let best = 0;
let timer = null;
let speed = 150;
let running = false;
let paused = false;
let ended = false;
let audioContext = null;

try {
  best = Number(localStorage.getItem("pixelSnakeBest")) || 0;
} catch (e) {
  best = 0;
}
bestEl.textContent = best;

function initAudio() {
  try {
    if (!audioContext) {
      const AudioContext = window.AudioContext ||
                           window.webkitAudioContext;
      if (AudioContext) audioContext = new AudioContext();
    }
    if (audioContext && audioContext.state === "suspended") {
      audioContext.resume();
    }
  } catch (e) {}
}

function beep(frequency, duration, type = "square") {
  if (!audioContext) return;

  try {
    const oscillator = audioContext.createOscillator();
    const gain = audioContext.createGain();

    oscillator.type = type;
    oscillator.frequency.value = frequency;

    gain.gain.setValueAtTime(0.08, audioContext.currentTime);
    gain.gain.exponentialRampToValueAtTime(
      0.001,
      audioContext.currentTime + duration
    );

    oscillator.connect(gain);
    gain.connect(audioContext.destination);

    oscillator.start();
    oscillator.stop(audioContext.currentTime + duration);
  } catch (e) {}
}

function randomCell() {
  return {
    x: Math.floor(Math.random() * COUNT),
    y: Math.floor(Math.random() * COUNT)
  };
}

function same(a, b) {
  return a.x === b.x && a.y === b.y;
}

function occupied(x, y) {
  if (snake.some(part => part.x === x && part.y === y)) return true;
  if (rocks.some(rock => rock.x === x && rock.y === y)) return true;
  if (apple && apple.x === x && apple.y === y) return true;
  return false;
}

function findFreeCell() {
  const free = [];

  for (let y = 0; y < COUNT; y++) {
    for (let x = 0; x < COUNT; x++) {
      if (!occupied(x, y)) free.push({ x, y });
    }
  }

  if (free.length === 0) return null;
  return free[Math.floor(Math.random() * free.length)];
}

function spawnApple() {
  apple = findFreeCell();

  if (!apple) {
    winGame();
  }
}

function addRocks() {
  const target = Math.min(3 + (level - 1) * 2, 18);
  let attempts = 0;

  while (rocks.length < target && attempts < 500) {
    attempts++;
    const cell = findFreeCell();

    if (!cell) break;

    // Keep the starting area relatively clear.
    if (cell.x < 5 && cell.y < 5) continue;

    rocks.push(cell);
  }
}

function resetGame() {
  clearInterval(timer);

  snake = [
    { x: 8, y: 10 },
    { x: 7, y: 10 },
    { x: 6, y: 10 }
  ];

  direction = { x: 1, y: 0 };
  nextDirection = { x: 1, y: 0 };

  apple = null;
  rocks = [];
  score = 0;
  level = 1;
  speed = 150;

  running = false;
  paused = false;
  ended = false;

  updateStats();
  addRocks();
  spawnApple();
  draw();
}

function updateStats() {
  scoreEl.textContent = score;
  levelEl.textContent = level;
  bestEl.textContent = best;
}

function startGame() {
  initAudio();

  if (ended) resetGame();

  if (running && paused) {
    paused = false;
    overlay.classList.add("hidden");
    startTimer();
    return;
  }

  if (running) return;

  running = true;
  paused = false;
  ended = false;
  overlay.classList.add("hidden");
  startTimer();
}

function startTimer() {
  clearInterval(timer);
  timer = setInterval(update, speed);
}

function pauseGame() {
  if (!running || ended) return;

  initAudio();
  paused = !paused;

  if (paused) {
    clearInterval(timer);
    overlayTitle.textContent = "PAUSED";
    overlayText.textContent = "اللعبة متوقفة مؤقتًا.";
    startBtn.textContent = "CONTINUE";
    overlay.classList.remove("hidden");
    beep(300, 0.1);
  } else {
    overlay.classList.add("hidden");
    startTimer();
  }
}

function gameOver() {
  clearInterval(timer);
  running = false;
  paused = false;
  ended = true;

  beep(160, 0.35, "sawtooth");

  overlayTitle.textContent = "GAME OVER";
  overlayText.textContent = "نتيجتك: " + score;
  startBtn.textContent = "PLAY AGAIN";
  overlay.classList.remove("hidden");
}

function winGame() {
  clearInterval(timer);
  running = false;
  ended = true;

  overlayTitle.textContent = "YOU WIN";
  overlayText.textContent = "أحسنت! لقد ملأت لوحة اللعب.";
  startBtn.textContent = "PLAY AGAIN";
  overlay.classList.remove("hidden");
}

function update() {
  if (!running || paused || ended) return;

  direction = nextDirection;

  const head = {
    x: snake[0].x + direction.x,
    y: snake[0].y + direction.y
  };

  // Wrap through the walls.
  head.x = (head.x + COUNT) % COUNT;
  head.y = (head.y + COUNT) % COUNT;

  const eating = apple && same(head, apple);

  // If not eating, the tail moves away this turn.
  const bodyToCheck = eating ? snake : snake.slice(0, -1);

  if (bodyToCheck.some(part => same(part, head))) {
    gameOver();
    return;
  }

  if (rocks.some(rock => same(rock, head))) {
    gameOver();
    return;
  }

  snake.unshift(head);

  if (eating) {
    score += 10;
    beep(650, 0.09, "square");

    if (score > best) {
      best = score;
      try {
        localStorage.setItem("pixelSnakeBest", best);
      } catch (e) {}
    }

    const newLevel = Math.floor(score / 50) + 1;

    if (newLevel > level) {
      level = newLevel;
      speed = Math.max(65, 150 - (level - 1) * 12);
      addRocks();
      beep(850, 0.2, "triangle");
      startTimer();
    }

    spawnApple();
    if (ended) return;
  } else {
    snake.pop();
  }

  updateStats();
  draw();
}

function drawBackground() {
  ctx.fillStyle = "#0c1724";
  ctx.fillRect(0, 0, 320, 320);

  for (let y = 0; y < COUNT; y++) {
    for (let x = 0; x < COUNT; x++) {
      ctx.fillStyle = (x + y) % 2 === 0 ? "#102033" : "#0e1b2c";
      ctx.fillRect(x * SIZE, y * SIZE, SIZE, SIZE);
    }
  }
}

function drawSnake() {
  snake.forEach((part, index) => {
    const x = part.x * SIZE;
    const y = part.y * SIZE;

    ctx.fillStyle = index === 0 ? "#b4ffe9" : "#27dba5";
    ctx.fillRect(x + 1, y + 1, 14, 14);

    ctx.fillStyle = index === 0 ? "#24b98b" : "#138b70";
    ctx.fillRect(x + 3, y + 3, 10, 10);

    if (index === 0) {
      ctx.fillStyle = "#071a20";

      // Pixel eyes according to direction.
      if (direction.x !== 0) {
        ctx.fillRect(x + (direction.x > 0 ? 10 : 3), y + 4, 3, 3);
        ctx.fillRect(x + (direction.x > 0 ? 10 : 3), y + 10, 3, 3);
      } else {
        ctx.fillRect(x + 4, y + (direction.y > 0 ? 10 : 3), 3, 3);
        ctx.fillRect(x + 10, y + (direction.y > 0 ? 10 : 3), 3, 3);
      }
    }
  });
}

function drawApple() {
  if (!apple) return;

  const x = apple.x * SIZE;
  const y = apple.y * SIZE;

  ctx.fillStyle = "#ff435f";
  ctx.fillRect(x + 3, y + 4, 10, 10);
  ctx.fillRect(x + 5, y + 2, 7, 13);
  ctx.fillStyle = "#bd203e";
  ctx.fillRect(x + 5, y + 7, 3, 5);

  ctx.fillStyle = "#64e68b";
  ctx.fillRect(x + 9, y + 1, 5, 3);
  ctx.fillStyle = "#b5ffb6";
  ctx.fillRect(x + 6, y + 5, 2, 2);
}

function drawRocks() {
  rocks.forEach(rock => {
    const x = rock.x * SIZE;
    const y = rock.y * SIZE;

    ctx.fillStyle = "#63778b";
    ctx.fillRect(x + 2, y + 5, 12, 9);
    ctx.fillRect(x + 4, y + 3, 8, 12);

    ctx.fillStyle = "#91a6b8";
    ctx.fillRect(x + 5, y + 4, 5, 3);

    ctx.fillStyle = "#3b4b5c";
    ctx.fillRect(x + 3, y + 11, 9, 2);
  });
}

function draw() {
  drawBackground();
  drawApple();
  drawRocks();
  drawSnake();
}

// Swipe controls.
let pointerStart = null;

canvas.addEventListener("pointerdown", event => {
  initAudio();
  pointerStart = {
    x: event.clientX,
    y: event.clientY
  };
});

canvas.addEventListener("pointerup", event => {
  if (!pointerStart) return;

  const dx = event.clientX - pointerStart.x;
  const dy = event.clientY - pointerStart.y;

  pointerStart = null;

  if (Math.max(Math.abs(dx), Math.abs(dy)) < 15) return;

  if (Math.abs(dx) > Math.abs(dy)) {
    if (dx > 0 && direction.x !== -1) {
      nextDirection = { x: 1, y: 0 };
    } else if (dx < 0 && direction.x !== 1) {
      nextDirection = { x: -1, y: 0 };
    }
  } else {
    if (dy > 0 && direction.y !== -1) {
      nextDirection = { x: 0, y: 1 };
    } else if (dy < 0 && direction.y !== 1) {
      nextDirection = { x: 0, y: -1 };
    }
  }
});

canvas.addEventListener("pointercancel", () => {
  pointerStart = null;
});

startBtn.addEventListener("click", startGame);
pauseBtn.addEventListener("click", pauseGame);

restartBtn.addEventListener("click", () => {
  initAudio();
  resetGame();
  startGame();
});

// Initial screen.
resetGame();
</script>
</body>
</html>

Game Source: PIXEL SNAKE

Creator: ChromeFlame24

Libraries: none

Complexity: complex (595 lines, 12.0 KB)

The full source code is displayed above on this page.

Remix Instructions

To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: pixel-snake-chromeflame24" to link back to the original. Then publish at arcadelab.ai/publish.