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

              
                <script type="x-template" id="board-checker-template">
  <transition
    @enter="enter"
    :css="false">
    <circle
      :cx="centerX"
      :cy="centerY"
      :r="checkerRadius"
      :fill="adjustedColor"
      :fill-opacity="opacity"
      />
  </transition>
</script>

<script type="x-template" id="board-column-template">
  <svg :x="col * cellSize" y="0">
    <g @click="drop(col)" class="column">
      <board-checker
        v-for="checker in checkers"
        :key="key(checker)"
        :checker="checker"
        :cellSize="cellSize"
        :rowCount="rowCount"
        :checkerRadius="checkerRadius"
        :status="status"
        @land="land"
        />
      <rect
        :class="status"
        :key="col"
        :col="col"
        :width="cellSize"
        :height="boardHeight"
        :fill="color"
        :fill-opacity="opacity"
        :mask="mask"
        />
    </g>
  </svg>
</script>

<script type="x-template" id="game-board-template">
  <svg :viewBox="`0 0 ${boardWidth} ${boardHeight}`"
    xmlns="http://www.w3.org/2000/svg"
    class="game-board" stroke="none">
    <defs>
      <pattern :id="patternId" patternUnits="userSpaceOnUse" :width="cellSize" :height="cellSize">
        <circle :cx="cellSize / 2" :cy="cellSize / 2" :r="checkerRadius" fill="black"></circle>
      </pattern>
      <mask :id="maskId">
        <rect :width="cellSize" :height="boardHeight" fill="white"></rect>
        <rect :width="cellSize" :height="boardHeight" :fill="pattern"></rect>
      </mask>
    </defs>
    <board-column
      v-for="col in cols"
      :key="col"
      :checkers="colCheckers(col)"
      :col="col"
      :color="'cadetblue'"
      :cellSize="cellSize"
      :checkerRadius="checkerRadius"
      :boardHeight="boardHeight"
      :rowCount="rowCount"
      :mask="mask"
      :status="status"
      @drop="drop"
      @land="land"
      />
  </svg>
</script>

<script type="x-template" id="game-container-template">
  <div>
    <p>
      {{ instructions }}  
    </p>
    <game-board
      :checkers="checkers"
      :rowCount="rowCount"
      :colCount="colCount"
      :status="status"
      @drop="drop"
      @land="land"
      ></game-board>
    <p v-if="gameOver">
      {{ overMessage }}
      <a href="#" @click="reset">Play again</a>
    </p>
    <p v-else>
      {{ whoseTurn }}
    </p>
  </div>    
</script>

<div id="app">
  <h3>Connect Four</h3>
  <game-container></game-container>
</div>
              
            
!

CSS

              
                body {
  background-color: azure;
}

a {
  text-decoration: none;
}

.logo h3 {
  margin: 0;
}

.game-board {
  border: 5px cadetblue solid;

  width: 350px;
  margin: 0 auto;
}

.column {
  cursor: pointer;
}

.column rect.play:hover {
  fill-opacity: 0.75;
}

#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}
              
            
!

JS

              
                const range = num => [...Array(num).keys()];

const key = (row, col) => `${row}${col}`;
const cssUrl = id => `url(#${id})`;
const titleize = text => text[0].toUpperCase() + text.slice(1, text.length)
const min = num => Math.max(num - 3, 0);
const max = (num, max) => Math.min(num + 3, max);

const RED = 'red';
const BLACK = 'black';
const GREEN = 'green';
const EMPTY = 'empty';
const OVER = 'over';
const PLAY = 'play';

const BoardChecker = Vue.component('board-checker', {
  template: '#board-checker-template',
  props: ['checker', 'cellSize', 'rowCount', 'checkerRadius', 'status'],

  data() {
    return {
      colorHexes: {
        red: '#FC7E69',
        black: '#254689',
        green: 'green',
      },
    };
  },

  computed: {
    row() { return this.checker.row; },
    col() { return this.checker.col; },
    color() { return this.checker.color; },
    isWinner() { return this.checker.isWinner; },

    adjustedColor() {
      return this.colorHexes[this.color];
    },
    
    opacity() {
      return (this.status === OVER && !this.isWinner) ? 0.25 : 1.0; 
    },

    centerX() {
      return (this.cellSize / 2);
    },

    centerY() {
      return (this.cellSize / 2) + (this.cellSize * (this.rowCount - 1 - this.row));
    },

    fromY() {
      return -1 * (this.centerY + this.cellSize);
    },

    destY() {
      return 0;
    },

    percentage() {
      return (this.rowCount - this.row) / this.rowCount;
    },

    duration() {
      return 0.2 + 0.4 * this.percentage;
    },
  },

  methods: {
    enter(el, done) {
      const fromParams = { y: this.fromY };
      const destParams = {
        y: this.destY,
        ease: Bounce.easeOut,
        onComplete: () => {
          this.$emit('land');
          done();
        },
      };

      return TweenMax.fromTo(el, this.duration, fromParams, destParams);
    },
  },
});

const BoardColumn = Vue.component('board-column', {
  template: '#board-column-template',
  props: ['checkers', 'col', 'color', 'cellSize', 'boardHeight', 'checkerRadius', 'rowCount', 'mask', 'status'],

  components: {
    BoardChecker,
  },

  computed: {
    // Find the current max occupied row and add 1
    nextOpenRow() {
      return Math.max(...this.checkers.map(c => c.row).concat(-1)) + 1;
    },
    
    opacity() {
      return (this.status === OVER) ? 0.2 : 1.0;
    },
  },

  methods: {
    key({ row, col }) {
      return `${row}${col}`;
    },
    
    land() {
      this.$emit('land');
    },

    drop(col) {
      const row = this.nextOpenRow;

      if (row < this.rowCount) {
        this.$emit('drop', { row, col });
      } else {
        console.log('cannot drop', { row, col });
      }
    },
  },
});

const GameBoard = Vue.component('game-board', {
  template: '#game-board-template',
  props: ['checkers', 'rowCount', 'colCount', 'status'],
  components: {
    BoardColumn,
  },

  data() {
    return {
      patternId: 'cell-pattern',
      maskId: 'cell-mask',
      cellSize: 100,
    };
  },

  computed: {
    pattern() { return cssUrl(this.patternId); },
    mask() { return cssUrl(this.maskId); },

    rows() { return range(this.rowCount); },
    cols() { return range(this.colCount); },

    boardWidth() { return this.colCount * this.cellSize; },
    boardHeight() { return this.rowCount * this.cellSize; },
    checkerRadius() { return this.cellSize * 0.45; },
  },

  methods: {
    colCheckers(col) {
      return Object.values(this.checkers).filter(c => c.col === col)
              .sort((a, b) => a.row - b.row);
    },
    drop(data) {
      this.$emit('drop', data);
    },
    land() {
      this.$emit('land');
    },
  },
});

const GameContainer = Vue.component('game-container', {
  template: "#game-container-template",
  
  components: {
    GameBoard,
  },
  
  data() {
    return {
      checkers: {},
      isLocked: false,
      playerColor: RED,
      rowCount: 6,
      colCount: 7,
      status: PLAY,
      instructions: 'Click columns to add checkers',
      winner: undefined,
    };
  },
  
  computed: {
    overMessage() {
      if (this.winner) {
        return `${titleize(this.winner.color)} wins!`;
      } else {
        return `It's a draw!`;
      }
    },
    
    moves() {
      return Object.values(this.checkers);
    },
    
    whoseTurn() {
      return `${titleize(this.playerColor)} goes ${this.moves.length === 0 ? 'first' : 'next'}`;
    },
    
    gameOver() {
      return this.status === OVER;
    },
  },

  methods: {
    key,

    reset() {
      this.winner = undefined;
      this.isLocked = false;
      this.status = PLAY;
      this.checkers = {};
    },

    toggleColor() {
      if (this.playerColor === RED) {
        this.playerColor = BLACK;
      } else {
        this.playerColor = RED;
      }
    },
    
    setChecker({ row, col }, attrs = {}) {
      const checker = this.getChecker({ row, col });
      return Vue.set(this.checkers, key(row, col), { ...checker, ...attrs });
    },
    
    getChecker({ row, col }) {
      return this.checkers[key(row, col)] || { row, col, color: 'empty' };
    },
    
    drop({ col, row }) {
      if (this.isLocked) return;
      
      this.isLocked = true;
      const color = this.playerColor;
      
      console.log('setting checker', key(row, col), { row, col, color });
      this.setChecker({ row, col }, { color });
      
      this.checkForDraw() || this.checkForWinFrom({ row, col });
      this.toggleColor(); 
    },
    
    land() {
      if (this.isDraw) return this.displayDraw();
      
      if (this.winner) {
        this.displayWin(this.winner);
      } else {
        this.isLocked = false;
      }
    },
    
    checkForDraw() {
      this.isDraw = Object.keys(this.checkers).length === this.rowCount * this.colCount;
    },
    
    getWinner(...segment) {
      if (segment.length !== 4) return false;
      const checkers = segment.map(([row, col]) => this.getChecker({row, col}));
      const color = checkers[0].color;
      if (color === EMPTY) return false;
      if (checkers.every(c => c.color === color)) return { color, checkers };
      return false;
    },
    
    checkHorizontalSegments({ focalRow, minCol, maxCol }) {
      for (let row = focalRow, col = minCol; col <= maxCol; col++) {
        const winner = this.getWinner([row, col], [row, col+1], [row, col+2], [row, col+3]);
        if (winner) return winner;
      }    
    },
    
    checkVerticalSegments({ focalRow, focalCol, minRow, maxRow }) {
      for (let col = focalCol, row = minRow; row <= focalRow; row++) {
        const winner = this.getWinner([row, col], [row+1, col], [row+2, col], [row+3, col]);
        if (winner) return winner;
      }
    },
    
    checkForwardSlashSegments({ focalRow, focalCol, minRow, minCol, maxRow, maxCol }) {
      const startForwardSlash = (row, col) => {
        while(row > minRow && col > minCol) { row--; col--; }
        return [row, col]
      }
      for (let [row, col] = startForwardSlash(focalRow, focalCol); row <= maxRow && col <= maxCol; row++, col++) {
        const winner = this.getWinner([row, col], [row+1, col+1], [row+2, col+2], [row+3, col+3]);
        if (winner) return winner;
      }
    },

    checkBackwardSlashSegments({ focalRow, focalCol, minRow, minCol, maxRow, maxCol }) {
      const startBackwardSlash = (row, col) => {
        while(row < maxRow && col > minCol) { row++; col--; }
        return [row, col]
      }
      for (let [row, col] = startBackwardSlash(focalRow, focalCol); row >= minRow && col <= maxCol; row--, col++) {
        const winner = this.getWinner([row, col], [row-1, col+1], [row-2, col+2], [row-3, col+3]);
        if (winner) return winner;
      }
    },

    checkForWinFrom(lastChecker) {
      if (!lastChecker) return;
      const { row: focalRow, col: focalCol } = lastChecker;
      const minCol = min(focalCol);
      const maxCol = max(focalCol, this.colCount-1);
      const minRow = min(focalRow);
      const maxRow = max(focalRow, this.rowCount-1);
      const coords = { focalRow, focalCol, minRow, minCol, maxRow, maxCol };
      
      this.winner = this.checkHorizontalSegments(coords) ||
        this.checkVerticalSegments(coords) ||
        this.checkForwardSlashSegments(coords) ||
        this.checkBackwardSlashSegments(coords);
    },
    
    displayDraw() {
      this.status = OVER;
    },
       
    displayWin(winner) {
      this.winner = winner;
      this.status = OVER;
      this.winner.checkers.forEach((checker) => {
        this.setChecker(checker, {isWinner: true});
      }); 
      console.log('Win!', winner);
    },

  },
});


new Vue({
  el: '#app',
});
              
            
!
999px

Console