[js]틱택토 게임 만들기

babypig·2023년 1월 14일
1

javascript

목록 보기
7/12
post-thumbnail

<body>
<script>
  const { body } = document;
  const $table = document.createElement('table');
  const $result = document.createElement('div');
  const rows = []
  let turn = '⭕'

  const  checkWinner = (target) => {
    const rowIndex = target.parentNode.rowIndex;
    const cellIndex = target.cellIndex;

    // rows.forEach((row, ri) => {
    //   row.forEach((cell, ci) => {
    //     if((cell === target)) {
    //       rowIndex = ri;
    //       cellIndex = ci;
    //     }
    //   })
    // })

    let hasWinner = false;

    // 가로줄 검사
    if (
        rows[rowIndex][0].textContent === turn &&
        rows[rowIndex][1].textContent === turn &&
        rows[rowIndex][2].textContent === turn
    ) {
      hasWinner = true;
    }
    // 세로줄 검사
    if (
        rows[0][cellIndex].textContent === turn &&
        rows[1][cellIndex].textContent === turn &&
        rows[2][cellIndex].textContent === turn
    ) {
      hasWinner = true;
    }
    // 대각선 검사
    if (
        rows[0][0].textContent === turn &&
        rows[1][1].textContent === turn &&
        rows[2][2].textContent === turn
    ) {
      hasWinner = true;
    }
    if (
        rows[0][2].textContent === turn &&
        rows[1][1].textContent === turn &&
        rows[2][0].textContent === turn
    ) {
      hasWinner = true;
    }
    return hasWinner;
  }

  const callback = (e) => {
    if(e.target.textContent) {
      return;
    }
    e.target.textContent = turn;
   if(checkWinner(e.target)) {
     $result.textContent = `${turn} 님이 승리`
     $table.removeEventListener('click', callback)
     return;
   }

   const draw = rows.flat().every(cell => cell.textContent);

   // let draw = true;
   // rows.forEach((row) => {
   //   row.forEach((cell) => {
   //     if(!cell.textContent) {
   //       draw = false;
   //     }
   //   })
   // })

    if(draw) {
      $result.textContent = '무승부';
      return;
    }
    turn = turn === '⭕' ? '❌' : '⭕';
  }

  for (let i = 0; i < 3; i++) {
    const $tr = document.createElement('tr');
    const cells = [];
    for (let j = 0; j < 3; j++) {
      const $td = document.createElement('td');
      cells.push($td);
      $tr.append($td);
    }
    rows.push(cells);
    $table.append($tr);
  }
  $table.addEventListener('click', callback);
  body.append($table);
  body.append($result);
</script>
</body>
profile
babypig

0개의 댓글