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. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

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

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

              
                <header class="site-header" role="banner">
  <div class="wrap">
    <h1>minesweeper</h1>
    <div class="legend">
      <p><strong>flag:</strong> <code><span class="key">alt</span>+<span class="click">click</span></code></p>
    </div>
  </div>
</header>
<main class="site-main" role="main">
  <div class="wrap">
    <div id="board">
      <div class="top">
        <div id="scoreboard">
          <div id="minecounter" class="counter"></div>
          <div>
            <div class="select-wrap">
              <select name="level" id="level">
                <option value="beginner">Beginner</option>
                <option value="intermediate">Intermediate</option>
                <option value="expert" selected>Expert</option>
              </select>
            </div>
            <button class="reset">🙂</button>
          </div>
          <div id="timer" class="counter"></div>
        </div>
        <div id="grid"></div>
      </div>
      <div class="bottom"></div>
    </div>
  </div>
</main>
              
            
!

CSS

              
                // Variables

// Colors
$colors: (
  white: #fff,
  gray-light: #efefef,
  gray-mid: #e3e3e3,
  gray: #d1d1d1,
  gray-dark: #808080,
  black: #333,
  red: #ec433c,
  maroon: #a6070f,
  purple: #a42887,
  yellow: #d7af42,
  yellow-light: #fef178,
  blue: #2a48ec,
  blue-dark: #233db7,
  green: #2bb13d,
  turquoise: #28907d
);

@function color($color-name) {
  @return map-get($colors, $color-name);
}

//base styles
*, *:before, *:after {
  box-sizing: inherit;
}

html {
  box-sizing: border-box;
}

body {
  text-align: center;
  color: color(black);
  padding: 20px 20px 100px;
  background-color: color(gray-light);
  font-family: 'Space Mono', monospace;
}

h1 {
  margin: 0 0 32px;
}

p {
  font-size: 1em;
  line-height: 1.25em;
}

a {
	color: inherit;
}

img {
  height: auto;
	max-width: 100%;
}

.wrap {
  text-align: center;
  position: relative;
  display: inline-block;
}

$cellSize: 24px;

.legend {
  font-size: 14px;
  margin: 0 auto 32px;
  h4,
  p {
    margin: 0 0 6px;
  }
  code {
    background: color(gray-mid);
    .key {
      color: color(red);
    }
    .click {
      color: color(blue);
    }
  }
}

.top {
  border: 6px solid color(gray-mid);
  background-color: color(gray-mid);
}

#scoreboard {
  display: flex;
  padding-bottom: 12px;
  justify-content: space-between;

  .select-wrap {
    font-weight: 700;
    vertical-align: top;
    display: inline-block;
    select {
      margin: 0;
      height: 36px;
      border-radius: 0;
      border-width: 3px;
      border-style: solid;
      background-color: color(gray);
      border-color: lighten(color(gray), 20%) darken(color(gray), 20%) darken(color(gray), 20%) lighten(color(gray), 20%);
      &:hover,
      &:focus {
        backgroudn-color: lighten(color(gray), 10%);
      }
    }
  }

  .reset {
    padding: 0 4px;
    font-size: 24px;
    cursor: pointer;
    font-weight: 700;
    line-height: 30px;
    border-width: 3px;
    border-style: solid;
    background-color: color(gray);
    border-color: lighten(color(gray), 20%) darken(color(gray), 20%) darken(color(gray), 20%) lighten(color(gray), 20%);
    &:hover,
    &:focus {
      outline: none;
      background-color: lighten(color(gray), 10%);
    }
  }
  .counter {
    padding: 0 4px;
    color: color(red);
    border: 3px inset;
    line-height: 30px;
    letter-spacing: .08em;
    display: inline-block;
    background: color(black);
    text-shadow: 0 0 2px rgba(color(red),1);
    &:first-of-type {
      margin-right: 20px;
    }
    &:last-of-type {
      margin-left: 20px;
    }
  }
}

#grid {
  margin: 0 auto;
  position: relative;
  display: inline-block;

  ::selection {
    background-color: transparent;
  }

  // Disabled when you win or lose
  &.disabled {
    .cell {
      pointer-events: none;
    }

    .status-indicator {
      top: 50%;
      left: 50%;
      z-index: 11;
      width: 8vw;
      height: 8vw;
      font-size: 4vw;
      cursor: pointer;
      line-height: 8vw;
      position: absolute;
      border-radius: 50%;
      pointer-events: auto;
      background-color: color(gray);
      transform: translate(-50%, -50%);
      border: 1px solid rgba(color(black),.25);
      &::after {
        content: '';
      }
    }
    &.win .status-indicator::after {
      content: '😎';
    }
    &.lose .status-indicator::after {
      content: '☚ī¸';
    }
  }

  .row {
    display: flex;
  }
  .cell {
    cursor: pointer;
    width: $cellSize;
    height: $cellSize;
    position: relative;
    background-color: color(gray);
    border-width: 3px;
    border-style: solid;
    border-color: lighten(color(gray), 20%) darken(color(gray), 20%) darken(color(gray), 20%) lighten(color(gray), 20%);

    i {
      left: 0;
      bottom: 0;
      margin: 0;
      width: 100%;
      font-size: 14px;
      font-weight: 700;
      font-style: normal;
      position: absolute;
      line-height: $cellSize;
    }

    // Veil
    &::before {
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 1;
      content: '';
      // opacity: .85;
      position: absolute;
      background-color: color(gray);
    }
    &::after {
      top: 50%;
      left: 50%;
      content: '';
      position: absolute;
      transform: translate(-50%, -50%);
    }

    &:hover {
      &::before {
        background-color: lighten(color(gray),10%);
      }
    }

    &.revealed {
      border: 1px solid darken(color(gray),10%);
      &::before {
        display: none;
      }
      .flag {
        display: none;
      }
    }

    // Flags
    .flag {
      top: 50%;
      left: 50%;
      z-index: 1;
      width: 10px;
      height: 4px;
      position: absolute;
      border-style: solid;
      border-width: 4px 0 4px 10px;
      transform: translate(-50%, -50%);
      border-color: transparent transparent transparent color(red);
    }
    // Maybe
    &.maybe {
      .flag {
        border-color: transparent transparent transparent color(yellow);
      }
    }

    // Mines
    &.mine {
      background-color: color(red);
      &::after {
        border-radius: 50%;
        width: $cellSize / 2;
        height: $cellSize / 2;
        background-color: color(black);
      }
    }

    // Incorrect
    &.incorrect {
      .flag {
        &::before,
        &::after {
          top: 50%;
          z-index: 1;
          left: -13px;
          height: 2px;
          width: 16px;
          content: '';
          position: absolute;
          background-color: black;
        }
        &::before {
          transform: rotate(-45deg);
        }
        &::after {
          transform: rotate(45deg);
        }
      }
    }

    // On mousedown
    &.mousedown {
      border: none;
    }
  }
}

// High Score Board
#leaderboard {
  margin-top: 20px;
  text-align: center;

  h4 {
    margin: 0 0 10px;
  }

  ul {
    margin: 0;
    padding: 10px;
    display: inline-block;
    background-color: rgba(color(gray),.5);
    li {
      padding: 2px;
      list-style: none;
      span {
        font-weight: 900;
        text-transform: capitalize;
      }

      &.highlight {
        background-color: color(yellow-light);
      }
    }
  }

  button {
    border: none;
    outline: none;
    cursor: pointer;
    font-size: 12px;
    font-weight: 700;
    appearance: none;
    background: none;
    text-decoration: underline;
  }
}

// Set Count Color Styles
@each $color, $value in $colors {
  .cell.#{$color} {
    color: $value;
  }
}

// Dev Box
#devbox {
  top: 10px;
  right: 10px;
  position: fixed;
  text-align: left;
  max-width: 300px;
  color: color(white);
  background-color: color(black);
  p {
    margin: 0;
    font-size: 12px;
    padding: 10px 20px;
    + p {
      padding-top: 5px;
    }
  }
}
              
            
!

JS

              
                $(document).ready(function() {

var $body,
      $document,
      $board,
      $grid,
      timer,
      time,
      unstarted;

  function _init() {
    // Cache some common DOM queries
    $document = $(document);
    $body = $('body');
    $body.addClass('loaded');

    // Start Minesweeper
    $board = $('#board');
    $grid = $('#grid');
    var $timer = $('#timer');
    var $mineCounter = $('#minecounter');
    var $levelSelect = $('#level');
    var levels = {
      'beginner': '9x9x10',
      'intermediate': '16x16x44',
      'expert': '16x30x99'
    };
    var level = $levelSelect.val();
    var levelParams,
        rows,
        $rows,
        columns,
        cellCount,
        mines,
        freeCells,
        mineTally,
        pauseTime,
        beginnerHighScore = 999,
        intermediateHighScore = 999,
        expertHighScore = 999;

    var countColors = {0: '', 1: 'blue', 2: 'green', 3: 'red', 4: 'blue-dark', 5: 'maroon', 6: 'turquoise', 7: 'purple', 8: 'gray-dark'};

    time = 0;
    timer = false;
    unstarted = true;
    var statusIndicator = '<div class="status-indicator"></div>';

    // Check for existing high score
    // if (localStorage.getItem('beginner')) {
    //   beginnerHighScore = localStorage.getItem('beginner');
    //   populateHighScore('beginner', localStorage.getItem('beginner'));
    // }
    // if (localStorage.getItem('intermediate')) {
    //   intermediateHighScore = localStorage.getItem('intermediate');
    //   populateHighScore('intermediate', localStorage.getItem('intermediate'));
    // }
    // if (localStorage.getItem('expert')) {
    //   expertHighScore = localStorage.getItem('expert');
    //   populateHighScore('expert', localStorage.getItem('expert'));
    // }

    function setLevel(level) {
      levelParams = levels[level];
      rows = parseInt(levelParams.split('x')[0]);
      columns = parseInt(levelParams.split('x')[1]);
      cellCount = rows*columns;
      mines = levelParams.split('x')[2];
      freeCells = cellCount - mines;
    }

    function setBoard(level) {
      // Clear Grid
      $grid.html(statusIndicator).removeClass('disabled lose win').addClass('unstarted');

      // Set Up Grid
      setLevel(level);

      // Set unstarted
      unstarted = true;

      // Build Rows
      for (r=0;r<rows;r++) {
        var newCells = '';
        // Build Cells
        for (c=0;c<columns;c++) {
          newCells += '<div class="cell"></div>';
        }
        $grid.append('<div class="row">'+newCells+'</div>');
      }

      // Set Minecounter
      mineTally = mines;
      $mineCounter.html(mineTally);

      // Set Timer
      resetTimer();
    }

    // Set initially
    setBoard(level);
    // Set on reset
    $('html').on('mousedown', '.reset', function() {
      $(this).text('😮');
    }).on('mouseup', '.reset', function() {
      $(this).text('🙂');
      stopTimer();
      level = $levelSelect.val();
      setBoard(level);
    });
    // Set when clicking status indicator
    $('html').on('click', '.status-indicator', function() {
      level = $levelSelect.val();
      setBoard(level);
    });
    // Set on level change
    $levelSelect.on('change', function() {
      stopTimer();
      resetTimer();
      level = $levelSelect.val();
      setBoard(level);
    });

    // Lay Mines
    function layMines(level, clickedCellIndex) {
      $rows = $('.row');
      var freeCells = $('.cell');
      var takenCells = [clickedCellIndex];

      // Lay Mines
      for (m=0;m<mines;m++) {
        var mineCell = Math.floor(Math.random() * Math.floor(freeCells.length));
        // If it happens to be the clicked cell, skip it
        if ($.inArray(mineCell, takenCells) > -1) {
          m--;
          continue;
        }
        takenCells.push(mineCell);
        $(freeCells[mineCell]).addClass('mine');
      }

      // Identify Cell Numbers
      var $cells = $('.cell');
      for (c=0;c<$cells.length;c++) {
        var $cell = $($cells[c]);
        $cell.attr('data-cell', c);
        // Skip if it's a mine
        if ($cell.is('.mine')) {
          continue;
        }

        var mineCount = 0;
        var rowPos = Math.floor(c/columns);
        var $currentRow = $cell.closest('.row');
        $currentRow.attr('data-row', rowPos);
        var rowCells = $currentRow.find('.cell');
        var cellPos = c % columns;

        if ($(rowCells[cellPos - 1]).is('.mine')) {
          mineCount++;
        }
        if ($(rowCells[cellPos + 1]).is('.mine')) {
          mineCount++;
        }

        if (rowPos > 0) {
          var prevRowCells = $($rows[rowPos - 1]).find('.cell');
          if ($(prevRowCells[cellPos - 1]).is('.mine')) {
            mineCount++;
          }
          if ($(prevRowCells[cellPos]).is('.mine')) {
            mineCount++;
          }
          if ($(prevRowCells[cellPos + 1]).is('.mine')) {
            mineCount++;
          }
        }

        if (rowPos < rows - 1) {
          var nextRowCells = $($rows[rowPos + 1]).find('.cell');
          if ($(nextRowCells[cellPos - 1]).is('.mine')) {
            mineCount++;
          }
          if ($(nextRowCells[cellPos]).is('.mine')) {
            mineCount++;
          }
          if ($(nextRowCells[cellPos + 1]).is('.mine')) {
            mineCount++;
          }
        }

        if (mineCount > 0) {
          $cell.html('<i>'+mineCount+'</i>');
          // Styling classes
          var colorClass = countColors[mineCount];
          $cell.addClass(colorClass);
        } else {
          $cell.addClass('zero');
        }
      }
    }

    // Click cell to start game
    $('html').off('click', '#grid.unstarted .cell').on('click', '#grid.unstarted .cell', function(e) {
      $grid.removeClass('unstarted');
      if (unstarted && !$(e.target).is('.mine')) {
        layMines(level, $('.cell').index(this));
        timer = window.setInterval(startTimer, 1000);
        unstarted = false;
      }
    });

    // Timer Functions
    function resetTimer() {
      $timer.html('000');
      time = 0;
    }
    function startTimer() {
      time++;
      if (time < 10) {
        $timer.html('00'+time);
      } else if (time > 9 && time < 100) {
        $timer.html('0'+time);
      } else {
        $timer.html(time);
      }
    }

    function stopTimer() {
      window.clearInterval(timer);
    }

    function pauseTimer() {
      stopTimer();
      pauseTime = parseInt($('#timer').html());
    }

    function unpauseTimer() {
      time = pauseTime;
      timer = window.setInterval(startTimer, 1000);
      pauseTime = false;
    }

    // Pause when window loses focus
    $(window).on('blur', function() {
      pauseTimer();
    }).on('focus', function() {
      if (pauseTime) {
        unpauseTimer();
      }
    });

    // Check Cell
    function checkCell($cell) {
      if (!$cell.is('.mine') && !$cell.is('.revealed')) {
        cellClick($cell, 'reveal');

        if ($cell.is('.zero')) {
          $cell.trigger('click');
        }
      }
    }

    // Clicking on a cell
    function cellClick($cell, action) {
      // If Flagging
      if (action === 'flag' && !$cell.is('.revealed')) {
        if ($cell.is('.flagged')) {
          $cell.removeClass('flagged');
          $cell.addClass('maybe');
          mineTally++;
          updateMinecounter(mineTally);
        } else if ($cell.is('.maybe')) {
          $cell.removeClass('maybe');
          var flag = $cell.find('.flag');
          flag.remove();
        } else {
          $cell.addClass('flagged');
          $cell.append('<span class="flag"></span>');
          mineTally--;
          updateMinecounter(mineTally);
        }
        // If Revealing
      } else if (action === 'reveal') {
        $cell.addClass('revealed');

        // If it's a mine you lose!
        if ($cell.is('.mine')) {
          lose();
        }

        statusCheck();
      } else if (action === 'clear') {
        if (!$cell.is('.revealed') || $cell.is('.zero')) {
          return;
        }

        clearClick($cell);
      }
    }

    // Update Minecounter
    function updateMinecounter(mineTally) {
      if (mineTally < 10) {
        $mineCounter.html('0'+mineTally);
      } else {
        $mineCounter.html(mineTally);
      }
    }

    // Clicking on a Zero cell
    function zeroClick($cell) {
      var cellPos = $cell.prevAll().length;
      var $currentRow = $cell.closest('.row');
      var rowPos = parseInt($currentRow.attr('data-row'));
      var rowCells = $currentRow.find('.cell');

      checkCell($(rowCells[cellPos - 1]));
      checkCell($(rowCells[cellPos + 1]));

      if (rowPos > 0) {
        var prevRowCells = $($rows[rowPos - 1]).find('.cell');
        checkCell($(prevRowCells[cellPos - 1]));
        checkCell($(prevRowCells[cellPos]));
        checkCell($(prevRowCells[cellPos + 1]));
      }

      if (rowPos < rows) {
        var nextRowCells = $($rows[rowPos + 1]).find('.cell');
        checkCell($(nextRowCells[cellPos - 1]));
        checkCell($(nextRowCells[cellPos]));
        checkCell($(nextRowCells[cellPos + 1]));
      }
    }

    // Clicking on a number to clear free cells
    function clearClick($cell) {
      var cellPos = $cell.prevAll().length;
      var $currentRow = $cell.closest('.row');
      var rowPos = parseInt($currentRow.attr('data-row'));
      var rowCells = $currentRow.find('.cell');
      var adjacentCells = [];
      var correctClear = true;
      var adjacentMines = 0;
      var adjacentFlags = 0;
      var i;
      adjacentCells.push($(rowCells[cellPos - 1]));
      adjacentCells.push($(rowCells[cellPos + 1]));

      if (rowPos > 0) {
        var prevRowCells = $($rows[rowPos - 1]).find('.cell');
        adjacentCells.push($(prevRowCells[cellPos - 1]));
        adjacentCells.push($(prevRowCells[cellPos]));
        adjacentCells.push($(prevRowCells[cellPos + 1]));
      }

      if (rowPos < rows) {
        var nextRowCells = $($rows[rowPos + 1]).find('.cell');
        adjacentCells.push($(nextRowCells[cellPos - 1]));
        adjacentCells.push($(nextRowCells[cellPos]));
        adjacentCells.push($(nextRowCells[cellPos + 1]));
      }

      for (i = 0; i < adjacentCells.length; i++) {
        // add to mine count
        if ($(adjacentCells[i]).is('.mine')) {
          adjacentMines++;
        }
        // add to flag cout
        if ($(adjacentCells[i]).is('.flagged')) {
          adjacentFlags++;
        }
      }

      if (adjacentFlags === adjacentMines) {
        for (i = 0; i < adjacentCells.length; i++) {
          if ($(adjacentCells[i]).is('.mine')) {
            if ($(adjacentCells[i]).is('.flagged')) {
              continue;
            } else {
              $(adjacentCells[i]).addClass('revealed');
              correctClear = false;
            }
          } else if ($(adjacentCells[i]).is('.flagged')) {
            correctClear = false;
            $(adjacentCells[i]).addClass('incorrect');
            lose();
          }
        }

        if (correctClear) {
          for (i = 0; i < adjacentCells.length; i++) {
            if (!$(adjacentCells[i]).is('.mine')) {
              if ($(adjacentCells[i]).is('.zero')) {
                zeroClick($(adjacentCells[i]));
              }
              cellClick($(adjacentCells[i]), 'reveal');
            }
          }
        }
      } else {
        return;
      }
    }

    // Check status
    function statusCheck() {
      if ($('.cell.revealed').length == freeCells) {
        stopTimer();
        var winTime = $('#timer').html();
        $grid.addClass('disabled win');
        resetHighScore(level, winTime);
      }
    }

    function lose() {
      $grid.addClass('disabled lose');
      stopTimer();
    }

    // Clicking on a cell
    $('html').on('click', '.cell', function(e) {
      e.preventDefault();
      var action = 'reveal';
      var $cell = $(this);

      if (e.altKey || e.which === 3) {
        action = 'flag';
      } else if ($cell.is('.revealed') || e.which === 1 & e.which === 3) {
        action = 'clear';
      }

      if ($cell.is('.flagged') && !e.altKey) {
        return;
      }

      if ($cell.is('.zero')) {
        zeroClick($cell);
      }

      cellClick($cell, action);
    });

    // Mouse down on a cell
    $('html').on('mousedown', '.cell:not(.revealed,.flagged)', function(e) {
      if (!e.altKey && e.which !== 3) {
        $(this).addClass('mousedown');
      }
    }).on('mouseup mouseleave', '.cell.mousedown', function() {
      $(this).removeClass('mousedown');
    });

    // Scoreboard functionality
    function resetHighScore(level, winTime) {
      if (localStorage.getItem(level)) {
        if (winTime < localStorage.getItem(level)) {
          localStorage.setItem(level, winTime);
          populateHighScore(level, winTime, true);
        }
      } else {
        localStorage.setItem(level, winTime);
        populateHighScore(level, winTime, true);
      }
    }

    function populateHighScore(level, highScore, highlight) {
      if (!$('#leaderboard').length) {
        $board.find('.bottom').append('<div id="leaderboard"><h4>High Scores</h4><ul><li class="beginner"></li><li class="intermediate"></li><li class="expert"></li></ul><div><button id="score-reset" class="score-reset">Clear Scores</button></div></div>');
      }
      if (highlight === true) {
        $('#leaderboard .highlight:not(.'+level+')').removeClass('highlight');
        $('#leaderboard .'+level).addClass('highlight');
      }
      var highScoreDisplay = parseInt(highScore,10);
      $('#leaderboard .'+level).html('<span>'+level+'</span>: '+highScoreDisplay+' seconds');
    }

    function clearScores() {
      localStorage.clear();
      $('#leaderboard').remove();
    }

    // Clicking on score reset to clear scores
    $('html').on('click', '#score-reset', clearScores);
  }

  _init();
});
              
            
!
999px

Console