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

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;
}

.status {
  margin-bottom: 10px;
}

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

.square:focus {
  outline: none;
}

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

.game {
  display: flex;
  flex-direction: row;
}

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

              
            
!

JS

              
                function Square({ value, onClick, backgroundColor }) {
  return (
    <button 
      className="square" 
      onClick={onClick}
      style={{backgroundColor}}>
      {value}
    </button>
  );
}

class Board extends React.Component {
  renderSquare(i) {
    const isWinningIndex = this.props.winningIndex && this.props.winningIndex.indexOf(i) !== -1
    return (
      <Square 
        key={`button-${i}`}
        value={this.props.squares[i]} 
        onClick={() => this.props.onClick(i)}
        backgroundColor={isWinningIndex && "deepskyblue"}
      />
    );
  }
  
  render() {
    // 3. 사각형들을 만들 때 하드코딩 대신에 두 개의 반복문을 사용하도록 Board를 다시 작성해주세요.
    const boardRows = [];
    for(let i = 0, len = Math.sqrt(this.props.squares.length); i < len; i++) {
      const innerCols = [];
      for(let j = 0; j < len; j++) {
        innerCols.push(this.renderSquare((i * len) + j));
      }
      boardRows.push(
       <div className="board-row" key={`row-${i}`}>
          {innerCols}
       </div> 
      );
    }
    
    return (
      <div>
        {boardRows}
      </div>
    );
  }
}

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [{
        squares: Array(9).fill(null),
        currentSquareIndex: null, // question 1
      }],
      stepNumber: 0,
      xIsNext: true,
      isDisplayOrderByAsc: true, // question 4
    }
  }
  
  
  handleClick(i) {
    const history = this.state.history.slice(0, this.state.stepNumber + 1);
    const current = history[history.length - 1];
    // square 배열의 복사본 생성 (불변성)
    const squares = current.squares.slice();
    
    if(calculateWinner(squares) || squares[i]) {
      return
    }
    
    squares[i] = this.state.xIsNext ? 'X' : 'O';
    
    this.setState({
      history: history.concat([{ 
        squares,
        currentSquareIndex: i
      }]),
      stepNumber: history.length,
      xIsNext: !this.state.xIsNext,
    });
  }
  
  jumpTo(step) {
    this.setState({
      stepNumber: step,
      xIsNext: (step % 2) === 0,
    });
  }
  
  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);
    
    const moves = history.map((step, move) => {
      // 1. 이동 기록 목록에서 특정 형식(행, 열)으로 각 이동의 위치를 표시해주세요.
      const { x, y } = getCoordBySquareIndex(step.currentSquareIndex); // 1
      const desc = move ?
            `Go to move #${move} - (${x}, ${y})` :
            'Go to game start';
      // *2. 이동 목록에서 현재 선택된 아이템을 굵게 표시해주세요.
      return (
        <li key={move}>
          <button 
            onClick={() => this.jumpTo(move)}
            style={ {"fontWeight": (this.state.stepNumber === move ? "bold" : "normal")} }>
            {desc}
          </button>
        </li>
      );
    });
    
    if(!this.state.isDisplayOrderByAsc) {
      moves.reverse()
    }
    
    // 4. 오름차순이나 내림차순으로 이동을 정렬하도록 토글버튼을 추가해주세요.
    const toggleMoves = () => {
      this.setState({
        isDisplayOrderByAsc: !this.state.isDisplayOrderByAsc
      })
    }
    
    let status;
    let winningIndex; // 이기게 된 원인이 된 스퀘어 번호들
    // null 아니고 O, X 인 경우
    // 6. 승자가 없는 경우 무승부라는 메시지를 표시해주세요.
    if (winner) {
      status = `Winner: ${winner.player}`;

      // 5. 승자가 정해지면 승부의 원인이 된 세 개의 사각형을 강조해주세요.
      winningIndex = winner.winningIndex

    } else if (this.state.stepNumber !== current.squares.length) {
      status = `Next player: ${this.state.xIsNext ? 'X' : 'O'}`
    } else {
      status = "Draw game!"
    }
    
    return (
      <div className="game">
        <div className="game-board">
          <Board 
            squares={current.squares}
            onClick={(i) => this.handleClick(i)}
            winningIndex={winningIndex}
          />
        </div>
        <div className="game-info">
          <div>{status}</div>
          <div>
            <button onClick={toggleMoves}>
              {this.state.isDisplayOrderByAsc ? "오름차순 ▲" : "내림차순 ▼"}
            </button>
          </div>
          <ol>{moves}</ol>
        </div>
      </div>
    );
  }
}

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

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];
    // 한 라인이 O , X 일치하는 경우
    if (squares[a]  && 
        squares[a] === squares[b] && 
        squares[a] === squares[c]) {
      return {
        player: squares[a],
        winningIndex: [a, b, c]
      };
    }
  }
  return null;
}

// 문제 1
function getCoordBySquareIndex(i) {
  return {
    x: Math.floor(i / 3),
    y: i % 3, 
  }
}

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

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

              
            
!
999px

Console