틱택토 게임을 만들어 보겠습니다.
-칸 9개를 그려준다
-대기
-칸 한 곳을 클릭한다.
-첫 번째는 O로 표시한다. 그 다음은 X로 해서 대결하게 한다.
-칸을 검사해서 가로,세로,대각선이 같은 값 3개가 들어있으면 승리로 한다.
-모든 칸이 다 채워져도 승리가 안나오면 비긴 것으로 한다.
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);
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);
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;
}
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"
링크텍스트