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

              
                <div id="errors" style="
  background: #c00;
  color: #fff;
  display: none;
  margin: -20px -20px 20px;
  padding: 20px;
  white-space: pre-wrap;
"></div>
<div id="root"></div>
<script>
window.addEventListener('mousedown', function(e) {
  document.body.classList.add('mouse-navigation');
  document.body.classList.remove('kbd-navigation');
});
window.addEventListener('keydown', function(e) {
  if (e.keyCode === 9) {
    document.body.classList.add('kbd-navigation');
    document.body.classList.remove('mouse-navigation');
  }
});
window.addEventListener('click', function(e) {
  if (e.target.tagName === 'A' && e.target.getAttribute('href') === '#') {
    e.preventDefault();
  }
});
window.onerror = function(message, source, line, col, error) {
  var text = error ? error.stack || error : message + ' (at ' + source + ':' + line + ':' + col + ')';
  errors.textContent += text + '\n';
  errors.style.display = '';
};
console.error = (function(old) {
  return function error() {
    errors.textContent += Array.prototype.slice.call(arguments).join(' ') + '\n';
    errors.style.display = '';
    old.apply(this, arguments);
  }
})(console.error);
</script>

              
            
!

CSS

              
                body {
  font: 14px "Century Gothic", Futura, sans-serif;
  margin: 20px;
}

ol, ul {
  padding-left: 30px;
}

.board-row:after {
  clear: both;
  content: "";
  display: table;
}

.sort-button {
  margin-bottom: 10px;
}

.status {
  margin-bottom: 10px;
}

.square {
  background: #fff;
  border: 2px solid #777;
  float: left;
  font-size: 24px;
  line-height: 34px;
  height: 34px;
  margin: 1px;
  padding: 0;
  text-align: center;
  width: 34px;
}

.square:focus {
  outline: none;
}

.kbd-navigation .square:focus {
  background: #ddd;
}

.game {
  display: flex;
  text-align: center;
  flex-direction: row;
}

.game-info {
  margin-left: 20px;
}

              
            
!

JS

              
                function Square(props) {
  return (
      <button className="square" onClick={props.onClick} id={props.index+100} key={props.index}>
        {props.value}
      </button>
    );
}

class Board extends React.Component {  
  renderSquare(i) {
    return (
      <Square 
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
        index={i}
        key={i}
        />
    );
  }
  
  createBoard() {
    var div = [];
    for (let i = 0; i < 3; i++) {
      let children = [];
        for (let j = 0; j < 3; j++) {
          children.push(this.renderSquare( i * 3 + j));
        }
      
      div.push(<div className="board-row" key={i}>{children}</div>);
    }
    
    return div;
  }
  
  render() {  
    return (
      <div>{this.createBoard()}</div>
    );
  }
}

function SortButton(props) {
  return (
    <button 
      className="sort-button" 
      onClick={props.onClick} >
      {props.isSortedAsc ? 'Sort Ascending' : 'Sort Descending'}
    </button>
  );
}

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [{
        squares: Array(9).fill(null),
        lastMoveIndex: {
          x: -1,
          y: -1,
        },
      }],
      stepNumber: 0,
      xIsNext: true,
      isSortedAsc: true,
    }
    this.handleSortClick = this.handleSortClick.bind(this);
  }
  
  handleSortClick() {    
    let id = Math.abs(this.state.history.length - 1 - this.state.stepNumber);
    
    this.setState({
      isSortedAsc: !this.state.isSortedAsc,
    });
    
    const buttons = document.getElementsByTagName('button');
    for (let i = 0; i < buttons.length; i++) {
      buttons[i].style.fontWeight = 'normal';
    }
    document.getElementById(id).style.fontWeight = 'bold';
  }
  
  handleClick(i) {
    const history = this.state.history.slice(0, this.state.stepNumber + 1);
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    
    if (calculateWinner(squares) || squares[i]) {
      return;
    }
    
    squares[i] = this.state.xIsNext ? 'X' : 'O';
    
    this.setState({
      history: history.concat([
        {
          squares: squares,
          lastMoveIndex: {
            x: i % 3 + 1,
            y: 3 - Math.floor(i / 3),
          }
        }
      ]),
      stepNumber: history.length,
      xIsNext: !this.state.xIsNext,
    });
  }
  
  jumpTo(step) {
    const buttons = document.getElementsByTagName('button');
    for (let i = 0; i < buttons.length; i++) {
      buttons[i].style.fontWeight = 'normal';
    }
    document.getElementById(step).style.fontWeight = 'bold';
    
    this.setState({
      stepNumber: (step),
      xIsNext: (step % 2) === 0,
    })
    
    console.log(this.state.stepNumber);
  }
  
  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);
    let moves = [];
    
    if (this.state.isSortedAsc) {
      moves = history.map((step, move) => {
        const desc = move ?
          'Go to move #' + move + ' (' + history[move].lastMoveIndex.x  + ',' + history[move].lastMoveIndex.y + ')':
          'Go to game start';
        return (
          <li key={move}>
              <button onClick={() => this.jumpTo(move)} id={move}>{desc}</button>
          </li>  
        )
      })
    } else {
      const historyReversed = history.slice().reverse();
      moves = historyReversed.map((step, move) => {
        const desc = historyReversed.length - 1 - move ?
          'Go to move #' + (historyReversed.length - 1 - move) + ' (' + historyReversed[move].lastMoveIndex.x  + ',' + historyReversed[move].lastMoveIndex.y + ')':
          'Go to game start';
        return (
          <li key={move}>
              <button onClick={() => this.jumpTo(historyReversed.length - 1 - move)} id={historyReversed.length - 1 - move}>{desc}</button>
          </li>  
        )      
      })
    }
    
    let status;
    if (winner) {
      const winnerPlayer = winner[0];
      const winSquares = winner[1];
      
      status = 'Winner: ' + winnerPlayer;
      for(let i = 0; i < winSquares.length; i++) {
        document.getElementById(winSquares[i]+100).style.backgroundColor = 'aqua';
      }
    } else {
      let isBoardFull = true;
      status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
      
      const squares = document.getElementsByClassName('square');            
      for (let i = 0; i < squares.length; i++) {
        squares[i].style.backgroundColor = 'white';
        isBoardFull = isBoardFull && squares[i];  
      }
      
      for (let i = 0; i < current.squares.length; i++) {
        isBoardFull = isBoardFull && current.squares[i];
        
      }
      
      if (isBoardFull){
        status = 'We have a draw!';
        const squares = document.getElementsByClassName('square');            
        for (let i = 0; i < squares.length; i++) {
            squares[i].style.backgroundColor = 'pink';
        }
      } 
    }
    
    return (
      <div className="game">
        <div className="game-board">
          <Board 
            squares={current.squares}
            onClick={(i) => this.handleClick(i)}
          />
        </div>
        <div className="game-info">
          <div>{status}</div> 
          <SortButton 
            isSortedAsc={this.state.isSortedAsc}
            onClick={this.handleSortClick}
          />
          <ol>{moves}</ol>
        </div>
      </div>
    );
  }
}

function colorWinnerSquare(square1, square2, square3) {
  document.getElementById(square1).style.backgroundColor = 'blue';
  document.getElementById(square2).style.backgroundColor = 'blue';
  document.getElementById(square3).style.backgroundColor = 'blue';

}

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
  ];
  
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] 
        && squares[a] === squares[b] 
        && squares[b] === squares[c]) {
      
      return [squares[a], [a, b, c]];
    }
  }
}

// ========================================

ReactDOM.render(
  <Game />,
  document.getElementById('root')
);

            
              
            
!
999px

Console