Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Snake Game</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="game-container">
    <canvas id="gameCanvas" width="400" height="400"></canvas>
    <div class="start-menu" id="startMenu">
      <h2>Snake Game</h2>
      <button onclick="startGame()">Start Game</button>
    </div>
    <div class="score-container" id="scoreContainer">
      <span id="score">Score: 0</span>
    </div>
  </div>

  <script src="snake.js"></script>
</body>
</html>

              
            
!

CSS

              
                body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
  background-color: #f0f0f0;
}

.game-container {
  position: relative;
  text-align: center; /* Center the content within the game container */
}

#gameCanvas {
  border: 2px solid #000;
}

.score-container {
  position: absolute;
  top: 10px;
  right: 10px;
}

button {
  padding: 5px 10px;
  font-size: 16px;
  cursor: pointer;
}

.start-menu {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

              
            
!

JS

              
                document.addEventListener('DOMContentLoaded', () => {
  const canvas = document.getElementById('gameCanvas');
  const ctx = canvas.getContext('2d');
  const scoreElement = document.getElementById('score');
  const startMenu = document.getElementById('startMenu');

  let snake;
  let food;
  let score = 0;
  let intervalId;
  let touchStartX;
  let touchStartY;

  const tileSize = 20;
  const canvasSize = 400;
  const gridSize = canvasSize / tileSize;

  function initializeGame() {
      snake = {
          body: [{ x: 5, y: 5 }],
          direction: 'right'
      };
      generateFood();
      score = 0;
      updateScore();
      hideStartMenu();
      scoreElement.style.display = 'block';

      intervalId = setInterval(update, 150);

      // Add event listeners for arrow keys and touch events
      document.addEventListener('keydown', handleKeyDown);
      canvas.addEventListener('touchstart', handleTouchStart);
      canvas.addEventListener('touchmove', handleTouchMove);
  }

  function handleKeyDown(event) {
      switch (event.key) {
          case 'ArrowUp':
              changeDirection('up');
              break;
          case 'ArrowDown':
              changeDirection('down');
              break;
          case 'ArrowLeft':
              changeDirection('left');
              break;
          case 'ArrowRight':
              changeDirection('right');
              break;
      }
  }

  function handleTouchStart(event) {
      touchStartX = event.touches[0].clientX;
      touchStartY = event.touches[0].clientY;
  }

  function handleTouchMove(event) {
      if (!touchStartX || !touchStartY) {
          return;
      }

      const touchEndX = event.touches[0].clientX;
      const touchEndY = event.touches[0].clientY;

      const deltaX = touchEndX - touchStartX;
      const deltaY = touchEndY - touchStartY;

      if (Math.abs(deltaX) > Math.abs(deltaY)) {
          // Horizontal swipe
          if (deltaX > 0) {
              changeDirection('right');
          } else {
              changeDirection('left');
          }
      } else {
          // Vertical swipe
          if (deltaY > 0) {
              changeDirection('down');
          } else {
              changeDirection('up');
          }
      }

      // Reset touch start coordinates
      touchStartX = null;
      touchStartY = null;
  }

  function changeDirection(newDirection) {
      // Ensure the snake cannot reverse its direction instantly
      if (
          (newDirection === 'up' && snake.direction !== 'down') ||
          (newDirection === 'down' && snake.direction !== 'up') ||
          (newDirection === 'left' && snake.direction !== 'right') ||
          (newDirection === 'right' && snake.direction !== 'left')
      ) {
          snake.direction = newDirection;
      }
  }

  function generateFood() {
      food = {
          x: Math.floor(Math.random() * gridSize),
          y: Math.floor(Math.random() * gridSize)
      };

      // Ensure food does not appear on the snake
      while (isFoodOnSnake()) {
          food.x = Math.floor(Math.random() * gridSize);
          food.y = Math.floor(Math.random() * gridSize);
      }
  }

  function isFoodOnSnake() {
      return snake.body.some(segment => segment.x === food.x && segment.y === food.y);
  }

  function draw() {
      ctx.clearRect(0, 0, canvasSize, canvasSize);

      // Draw Snake
      ctx.fillStyle = '#00f';
      snake.body.forEach(segment => {
          ctx.fillRect(segment.x * tileSize, segment.y * tileSize, tileSize, tileSize);
      });

      // Draw Food
      ctx.fillStyle = '#f00';
      ctx.fillRect(food.x * tileSize, food.y * tileSize, tileSize, tileSize);
  }

  function update() {
      const head = Object.assign({}, snake.body[0]);

      switch (snake.direction) {
          case 'up':
              head.y -= 1;
              break;
          case 'down':
              head.y += 1;
              break;
          case 'left':
              head.x -= 1;
              break;
          case 'right':
              head.x += 1;
              break;
      }

      if (head.x < 0 || head.x >= gridSize || head.y < 0 || head.y >= gridSize || isSnakeCollision()) {
          clearInterval(intervalId);
          showStartMenu();
          document.removeEventListener('keydown', handleKeyDown);
          canvas.removeEventListener('touchstart', handleTouchStart);
          canvas.removeEventListener('touchmove', handleTouchMove);
          return;
      }

      if (head.x === food.x && head.y === food.y) {
          snake.body.unshift(food);
          generateFood();
          score += 10;
          updateScore();
      } else {
          snake.body.unshift(head);
          snake.body.pop();
      }

      draw();
  }

  function isSnakeCollision() {
      const [head, ...body] = snake.body;
      return body.some(segment => segment.x === head.x && segment.y === head.y);
  }

  function updateScore() {
      scoreElement.textContent = `Score: ${score}`;
  }

  function showStartMenu() {
      startMenu.style.display = 'block';
      scoreElement.style.display = 'none';
  }

  function hideStartMenu() {
      startMenu.style.display = 'none';
  }

  window.startGame = function () {
      hideStartMenu();
      initializeGame();
  };
});

              
            
!
999px

Console