<!DOCTYPE html>
<html>
<head>
  <title>Snake Game with Extras</title>
  <meta charset="UTF-8" />
  <style>
    html, body {
      height: 100%;
      margin: 0;
    }
    body {
      background: black;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: white;
      font-family: monospace;
      user-select: none;
    }
    #score, #highscore {
      font-size: 18px;
      margin: 4px 0;
    }
    canvas {
      border: 1px solid white;
      background: #000;
    }
    #gameover, #pauseMenu {
      display: none;
      margin-top: 20px;
      text-align: center;
    }
    #restartBtn, #pauseBtn, #resumeBtn {
      cursor: pointer;
      padding: 8px 14px;
      margin-top: 10px;
      font-weight: bold;
      background: white;
      border: none;
      color: black;
      font-family: monospace;
    }
    #restartBtn:hover, #pauseBtn:hover, #resumeBtn:hover {
      background: lightgray;
    }
    #touchControls {
      margin-top: 15px;
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      gap: 8px;
      max-width: 240px;
    }
    .touchBtn {
      background: white;
      color: black;
      border: none;
      font-size: 20px;
      font-weight: bold;
      width: 50px;
      height: 50px;
      border-radius: 6px;
      user-select: none;
    }
    .touchBtn:active {
      background: #ddd;
    }
  </style>
</head>
<body>

<div id="score">Score: 0</div>
<div id="highscore">High Score: 0</div>
<button id="pauseBtn">Pause</button>
<canvas width="400" height="400" id="game"></canvas>

<div id="pauseMenu">
  <div>Paused</div>
  <button id="resumeBtn">Resume</button>
</div>

<div id="gameover">
  <div>Game Over</div>
  <button id="restartBtn">Restart</button>
</div>

<!-- Touch Controls for Mobile -->
<div id="touchControls">
  <button class="touchBtn" data-dir="w">W</button>
  <button class="touchBtn" data-dir="a">A</button>
  <button class="touchBtn" data-dir="s">S</button>
  <button class="touchBtn" data-dir="d">D</button>
</div>

<script>
  // Setup canvas and context
  var canvas = document.getElementById('game');
  var context = canvas.getContext('2d');

  // UI elements
  var scoreEl = document.getElementById('score');
  var highScoreEl = document.getElementById('highscore');
  var gameOverEl = document.getElementById('gameover');
  var restartBtn = document.getElementById('restartBtn');
  var pauseBtn = document.getElementById('pauseBtn');
  var pauseMenu = document.getElementById('pauseMenu');
  var resumeBtn = document.getElementById('resumeBtn');
  var touchControls = document.getElementById('touchControls');

  var grid = 16;
  var count = 0;
  var score = 0;
  var highScore = localStorage.getItem('snakeHighScore') || 0;
  var isGameOver = false;
  var isPaused = false;

  highScoreEl.textContent = 'High Score: ' + highScore;

  var snake = {
    x: 160,
    y: 160,
    dx: grid,
    dy: 0,
    cells: [],
    maxCells: 4
  };

  var apple = {
    x: 320,
    y: 320
  };

  // Sounds (simple beep sounds using AudioContext)
  var AudioContext = window.AudioContext || window.webkitAudioContext;
  var audioCtx = new AudioContext();

  function playSound(freq, duration = 100) {
    var oscillator = audioCtx.createOscillator();
    var gainNode = audioCtx.createGain();

    oscillator.connect(gainNode);
    gainNode.connect(audioCtx.destination);

    oscillator.type = 'square';
    oscillator.frequency.value = freq;
    oscillator.start();

    gainNode.gain.setValueAtTime(0.1, audioCtx.currentTime);
    gainNode.gain.exponentialRampToValueAtTime(0.0001, audioCtx.currentTime + duration / 1000);

    oscillator.stop(audioCtx.currentTime + duration / 1000);
  }

  // Play eat apple sound
  function playEatSound() {
    playSound(880, 120);
  }

  // Play game over sound
  function playGameOverSound() {
    playSound(220, 300);
  }

  function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
  }

  function resetGame() {
    isGameOver = false;
    isPaused = false;
    gameOverEl.style.display = 'none';
    pauseMenu.style.display = 'none';
    pauseBtn.style.display = 'inline-block';

    score = 0;
    scoreEl.textContent = 'Score: 0';

    snake.x = 160;
    snake.y = 160;
    snake.cells = [];
    snake.maxCells = 4;
    snake.dx = grid;
    snake.dy = 0;

    apple.x = getRandomInt(0, 25) * grid;
    apple.y = getRandomInt(0, 25) * grid;

    requestAnimationFrame(loop);
  }

  function updateHighScore() {
    if (score > highScore) {
      highScore = score;
      localStorage.setItem('snakeHighScore', highScore);
      highScoreEl.textContent = 'High Score: ' + highScore;
    }
  }

  function loop() {
    if (isGameOver || isPaused) return;

    requestAnimationFrame(loop);

    if (++count < 4) return;
    count = 0;

    context.clearRect(0, 0, canvas.width, canvas.height);

    snake.x += snake.dx;
    snake.y += snake.dy;

    if (snake.x < 0) snake.x = canvas.width - grid;
    else if (snake.x >= canvas.width) snake.x = 0;

    if (snake.y < 0) snake.y = canvas.height - grid;
    else if (snake.y >= canvas.height) snake.y = 0;

    snake.cells.unshift({x: snake.x, y: snake.y});

    if (snake.cells.length > snake.maxCells) snake.cells.pop();

    // draw apple
    context.fillStyle = 'red';
    context.fillRect(apple.x, apple.y, grid - 1, grid - 1);

    // draw snake
    context.fillStyle = 'green';
    snake.cells.forEach(function(cell, index) {
      context.fillRect(cell.x, cell.y, grid - 1, grid - 1);

      if (cell.x === apple.x && cell.y === apple.y) {
        snake.maxCells++;
        score++;
        scoreEl.textContent = 'Score: ' + score;
        playEatSound();

        apple.x = getRandomInt(0, 25) * grid;
        apple.y = getRandomInt(0, 25) * grid;
      }

      // Check collision with self
      for (var i = index + 1; i < snake.cells.length; i++) {
        if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y) {
          isGameOver = true;
          playGameOverSound();
          gameOverEl.style.display = 'block';
          pauseBtn.style.display = 'none';
          updateHighScore();
          break;
        }
      }
    });
  }

  // WASD keyboard controls
  document.addEventListener('keydown', function(e) {
    if (isGameOver || isPaused) return;
    var key = e.key.toLowerCase();
    if (key === 'a' && snake.dx === 0) {
      snake.dx = -grid;
      snake.dy = 0;
    } else if (key === 'w' && snake.dy === 0) {
      snake.dy = -grid;
      snake.dx = 0;
    } else if (key === 'd' && snake.dx === 0) {
      snake.dx = grid;
      snake.dy = 0;
    } else if (key === 's' && snake.dy === 0) {
      snake.dy = grid;
      snake.dx = 0;
    }
  });

  // Touch controls
  touchControls.querySelectorAll('.touchBtn').forEach(btn => {
    btn.addEventListener('touchstart', e => {
      e.preventDefault(); // prevent scrolling
      if (isGameOver || isPaused) return;

      var dir = btn.getAttribute('data-dir');
      if (dir === 'a' && snake.dx === 0) {
        snake.dx = -grid;
        snake.dy = 0;
      } else if (dir === 'w' && snake.dy === 0) {
        snake.dy = -grid;
        snake.dx = 0;
      } else if (dir === 'd' && snake.dx === 0) {
        snake.dx = grid;
        snake.dy = 0;
      } else if (dir === 's' && snake.dy === 0) {
        snake.dy = grid;
        snake.dx = 0;
      }
    });
  });

  // Pause button toggle
  pauseBtn.addEventListener('click', () => {
    if (isGameOver) return;
    isPaused = true;
    pauseMenu.style.display = 'block';
    pauseBtn.style.display = 'none';
  });

  // Resume button
  resumeBtn.addEventListener('click', () => {
    if (isGameOver) return;
    isPaused = false;
    pauseMenu.style.display = 'none';
    pauseBtn.style.display = 'inline-block';
    requestAnimationFrame(loop);
  });

  // Restart button
  restartBtn.addEventListener('click', resetGame);

  // Start the game for the first time
  resetGame();
</script>
</body>
</html>
 
by

HTML Online Editor & Compiler

Write, Run & Share HTML code online using OneCompiler's HTML online Code editor for free. It's one of the robust, feature-rich online Code editor for HTML language, running on the latest version HTML5. Getting started with the OneCompiler's HTML compiler is simple and pretty fast. The editor shows sample boilerplate code when you choose language as HTML. You can also specify the stylesheet information in styles.css tab and scripts information in scripts.js tab and start coding.

About HTML

HTML(Hyper Text Markup language) is the standard markup language for Web pages, was created by Berners-Lee in the year 1991. Almost every web page over internet might be using HTML.

Syntax help

Fundamentals

  • Any HTML document must start with document declaration <!DOCTYPE html>
  • HTML documents begin with <html> and ends with </html>
  • Headings are defined with <h1> to <h6> where <h1> is the highest important heading and <h6> is the least important sub-heading.
  • Paragrahs are defined in <p>..</p> tag.
  • Links are defined in <a> tag.

    Example:

    <a href="https://onecompiler.com/html">HTML online compiler</a>
    
  • Images are defined in <img> tag, where src attribute consists of image name.
  • Buttons are defined in <button>..</button> tag
  • Lists are defined in <ul> for unordered/bullet list and <ol> for ordered/number list, and the list items are defined in <li>.

HTML Elements and Attributes

  • HTML element is everything present from start tag to end tag.
  • The text present between start and end tag is called HTML element content.
  • Anything can be a tagname but it's preferred to put the meaningful title to the content present as tag name.
  • Do not forget the end tag.
  • Elements with no content are called empty elements.
  • Elements can have attributes which provides additional information about the element.
  • In the below example, href is an attribute and a is the tag name.

    Example:

    <a href="https://onecompiler.com/html">HTML online compiler</a>
    

CSS

CSS(cascading style sheets) describes how HTML elements will look on the web page like color, font-style, font-size, background color etc.

Example:

Below is a sample style sheet which displays heading in green and in Candara font with padding space of 25px.

body{
  padding: 25px;
}
.title {
	color: #228B22;
	font-family: Candara;
}

HTML Tables

  • HTML Tables are defined in <table> tag.
  • Table row should be defined in <tr> tag
  • Table header should be defined in <th> tag
  • Table data should be defined in <td> tag
  • Table caption should be defined in <caption> tag

HTML-Javascript

  • Javascript is used in HTML pages to make them more interactive.
  • <script> is the tag used to write scripts in HTML
  • You can either reference a external script or write script code in this tag.

Example

<script src="script.js"></script>