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