Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's 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 it's URL and the proper URL extention.

+ 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

Save Automatically?

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

              
                <div id="target">
  <canvas id="game" width="400" height="400"></canvas>
</div>
              
            
!

CSS

              
                body {
  font-family: Consolas, monotype;
  margin: 0;
}

#game {
  width: 400px;
  height: 400px;
  position: absolute;
  top: 0;
  left: 0;
}

#target {
  width: 400px;
  height: 400px;
  margin: 0;
}

#game-over-display {
  position: relative;
  z-index: 1;
  color: #eee;
  top: 280px;
  text-align: center;
}

.score {
  color: #f66;
  font-weight: bold;
}

#restart-button {
  position: relative;
  z-index: 1;
  padding: 10px 20px;
  background: #222;
  border: 2px solid #eee;
  color: #eee;
  cursor: pointer;
  font-weight: bold;
}

#restart-button:hover {
  background: #eee;
  color: #222;
}

              
            
!

JS

              
                document.addEventListener('DOMContentLoaded', () => {  
  
  const game = document.querySelector('#game');
  const ctx = game.getContext('2d');

  const state = {
  }

  window.addEventListener('keydown', handleKeydown);

  const LEFT = [-1, 0];
  const UP = [0, -1];
  const RIGHT = [1, 0];
  const DOWN = [0, 1]

  const tileSize = 20;
  const gameWidth = 20;
  const gameHeight = 20;
  const gameTick = 100;

  const bgColor = '#222';
  const snakeColor = '#eee';
  const appleColor = '#f66';

  const gameOverTextArray = [
    [   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0],
    [   0,   3,   2,   1,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0],
    [   0,   4,   0,   0,   0,   0,  15,  16,  17,   0,  31,  32,  33,  38,  39,   0,  49,  48,  47,   0],
    [   0,   5,   0,   0,   0,   0,   0,   0,  18,   0,  30,   0,  34,   0,  40,   0,  50,   0,  46,   0],
    [   0,   6,   0,  14,  13,   0,  25,  26,  19,   0,  29,   0,  35,   0,  41,   0,  51,  44,  45,   0],
    [   0,   7,   0,   0,  12,   0,  24,   0,  20,   0,  28,   0,  36,   0,  42,   0,  52,   0,   0,   0],
    [   0,   8,   9,  10,  11,   0,  23,  22,  21,   0,  27,   0,  37,   0,  43,   0,  53,  54,  55,   0],
    [   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0],
    [   0,  56,  57,  58,  59,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 101,   0],
    [   0,  71,   0,   0,  60,   0,  72,   0,  81,   0,  87,  86,  85,   0,  98,  99, 100,   0, 102,   0],
    [   0,  70,   0,   0,  61,   0,  73,   0,  80,   0,  88,   0,  84,   0,  97,   0,   0,   0, 103,   0],
    [   0,  69,   0,   0,  62,   0,  74,   0,  79,   0,  89,  82,  83,   0,  96,   0,   0,   0, 104,   0],
    [   0,  68,   0,   0,  63,   0,  75,  76,  78,   0,  90,   0,   0,   0,  95,   0,   0,   0,   0,   0],
    [   0,  67,  66,  65,  64,   0,   0,  77,   0,   0,  91,  92,  93,   0,  94,   0,   0,   0,-105,   0]
  ];

  let gameInterval;
  let snakey;
  let pixelTextTimeouts = [];

  function handleKeydown(e) {
    const dirMap = [['ArrowLeft', LEFT], ['ArrowUp', UP], ['ArrowRight', RIGHT], ['ArrowDown', DOWN]];

    const codes = dirMap.map(el => el[0]);
    const idx = codes.indexOf(e.code);
    if (idx > -1) {
      e.preventDefault();
      const dirs = dirMap.map(el => el[1]);

      const keyDir = dirMap[idx][1];

      if ((dirs.indexOf(snakey.getDirection()) + idx) % 2 > 0) {
        snakey.setDirection(keyDir);
      }
    }
  }

  function drawSquare(coords, color) {
    ctx.fillStyle = bgColor;
    ctx.fillRect(coords[0] * tileSize, coords[1] * tileSize, tileSize, tileSize);

    ctx.fillStyle = color;
    ctx.fillRect(coords[0] * tileSize + 1, coords[1] * tileSize + 1, tileSize - 2, tileSize - 2);
  }

  class Snake {
    constructor(headLocation = [4, 1], moveDirection = RIGHT, length = 4, color = snakeColor) {
      this.color = color;
      this.headLocation = headLocation;
      this.squares = [];
      this.moveDirection = this.newMoveDirection = moveDirection;     
      for (let i = 0; i < length; i++) {
        this.squares.push([(gameWidth + this.headLocation[0] - this.moveDirection[0] * i) % gameWidth, (gameHeight + this.headLocation[1] - this.moveDirection[1] * i) % gameHeight]);
      }
    }

    getDirection() {
      return this.moveDirection;
    }

    setDirection(newDir) {
      this.newMoveDirection = newDir;
    }

    getSquares() {
      return this.squares;
    }

    deleteEnd() {
      const toDelete = this.squares.pop(1);
      return toDelete;
    }

    move() {
      this.moveDirection = this.newMoveDirection;
      this.headLocation = this.squares[0];
      this.squares.unshift([(gameWidth + this.headLocation[0] + this.moveDirection[0]) % gameWidth, (gameHeight + this.headLocation[1] + this.moveDirection[1]) % gameHeight]);

      const toErase = this.deleteEnd();

      if (collide(this.squares[0], state.appleLocation)) {
        this.eatApple();
      }
      if (!this.squares.slice(1).every(square => !collide(square, this.squares[0]))) {
        this.die();
      }

      this.draw(toErase);
    }

    getLength() {
      return this.squares.length;
    }

    die() {
      gameOver();
    }

    draw(toErase) {
      this.squares.forEach((square) => drawSquare(square, this.color));
      drawSquare(toErase, bgColor);
    }

    eatApple() {
      const sqln = this.getLength();
      const tailDir = [
        this.squares[sqln - 2][0] - this.squares[sqln - 1][0],
        this.squares[sqln - 2][1] - this.squares[sqln - 1][1]
      ];
      this.squares.push([this.squares[sqln - 1][0] - tailDir[0],
        this.squares[sqln - 1][1] - tailDir[1]
        ]);
      spawnApple();
    }
  }

  function clearScreen() {
    ctx.fillStyle = bgColor;
    ctx.fillRect(0, 0, game.width, game.height);
  }

  function init() {
    state.appleLocation = null;
    const gameOverDisplay = document.querySelector('#game-over-display');
    if (gameOverDisplay) {gameOverDisplay.remove();}
    snakey = new Snake([Math.floor(Math.random() * gameWidth), Math.floor(Math.random() * gameHeight)], [LEFT, UP, RIGHT, DOWN][Math.floor(Math.random() * 4)]);
    clearPixelTextTimeouts();
    clearScreen();
    spawnApple();
    function updateGame() {
      snakey.move();
    }
    gameInterval = setInterval(updateGame, gameTick);
  }

  init();

  function writePixelText(pixelArray, placeholderColor, primaryColor, accentColor) {
    
    pixelArray.forEach((row, y) => {
      row.forEach((pixel, x) => {
        if (pixel === 0) {
          return;
        } else {
          drawSquare([x, y], placeholderColor);
          if (pixel > 0) {
            pixelTextTimeouts.push(setTimeout(() => drawSquare([x, y], primaryColor), pixel * gameTick));
          } else {
            pixelTextTimeouts.push(setTimeout(() => drawSquare([x, y], accentColor), -pixel * gameTick));
          }
        }
      });
    });
  }

  function clearPixelTextTimeouts() {
    pixelTextTimeouts.forEach(el => clearTimeout(el));
    pixelTextTimeouts = [];
  }

  function gameOver() {
    clearInterval(gameInterval);
    setTimeout(() => {
      clearScreen();
      writePixelText(gameOverTextArray, 'rgba(255,255,255,0.1)', snakeColor, appleColor);
    }, 0);
    const gameOverDisplay = document.createElement('div');
    gameOverDisplay.id = 'game-over-display';
    gameOverDisplay.innerHTML = `<p>Final score: <span class="score">${snakey.getLength()}</span></p>
    <button id="restart-button">Restart</button>`;
    document.querySelector('#target').appendChild(gameOverDisplay);
    document.querySelector('#restart-button').onclick = init;

  }

  function spawnApple(color = appleColor) {
    
    let appleLocation;

    do {
      appleLocation = [Math.floor(Math.random() * gameWidth), Math.floor(Math.random() * gameHeight)];
    } while (!snakey.getSquares().every(square => !collide(square, appleLocation)));

    drawSquare(appleLocation, appleColor);
    state.appleLocation = appleLocation;
  }

  function collide(coords1, coords2) {
    if (coords1[0] === coords2[0] && coords1[1] === coords2[1]) {
      return true;
    } else {
      return false;
    }
  }

});

              
            
!
999px

Console