틱택토 게임 (html / js)

yun·2023년 3월 12일
0

틱택토 게임을 만들어 보겠습니다.

절차

프로그래밍 사고

-칸 9개를 그려준다
-대기
-칸 한 곳을 클릭한다.
-첫 번째는 O로 표시한다. 그 다음은 X로 해서 대결하게 한다.
-칸을 검사해서 가로,세로,대각선이 같은 값 3개가 들어있으면 승리로 한다.
-모든 칸이 다 채워져도 승리가 안나오면 비긴 것으로 한다.


코드

  • 칸 9개를 그려준다
const { body } = document;
const $table = document.createElement('table');
const $result = document.createElement('div');
const rows = [];
for (let i = 1; i <= 3; i++) {
  const $tr = document.createElement('tr');
  const cells = [];
  for (let j = 1; j <= 3; j++) {
    const $td = document.createElement('td');
    cells.push($td);
    $tr.append($td);
  }
  rows.push(cells);
  $table.append($tr);
}
body.append($table);
  • 칸 한 곳을 클릭한다.
    첫 번째는 O로 표시한다. 그 다음은 X로 해서 대결하게 한다
let turn = 'O';
const callback = (event) => {
  if (event.target.textContent !== '') {
    return;
  }
  event.target.textContent = turn;
  const hasWinner = checkWinner(event.target);
  turn = turn === 'X' ? 'O' : 'X';
};
$table.addEventListener('click', callback);
  • 칸을 검사해서 가로,세로,대각선이 같은 값 3개가 들어있으면 승리로 한다.
const checkWinner = (target) => {
  const rowIndex = target.parentNode.rowIndex;
  const cellIndex = target.cellIndex;

  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 hasWinner = checkWinner(event.target);
if (hasWinner) {
  $result.textContent = `${turn}님이 승리!`;
  $table.removeEventListener('click', callback);
  return;
}
  • 모든 칸이 다 채워져도 승리가 안나오면 비긴 것으로 한다.
const draw = rows.flat().every((cell) => cell.textContent);
if (draw) {
  $result.textContent = `무승부`;
  return;
}

더 나아가기

  1. 컴퓨터가 랜덤으로 선택하기
if (turn === 'X') {
  const emptyCells = rows.flat().filter((v) => !v.textContent);
  const randomCell = emptyCells[Math.floor(Math.random() * emptyCells.length)];
  clickable = false;
  setTimeout(() => {
    randomCell.textContent = 'X';
    checkWinnerAndDraw(randomCell);
    clickable = true;
  }, 1000);
}

화면


소스코드(github)
링크텍스트

출처 "ZeroCho TV"
링크텍스트

profile
날아오르고 싶은 애벌레입니다.

0개의 댓글

관련 채용 정보