forked from rolling-scopes-school/tic-tac-toe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·58 lines (43 loc) · 1.22 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const TicTacToe = require('./src/tic-tac-toe.js');
window.game = new TicTacToe();
resetBtn.addEventListener('click', () => {
window.game = new TicTacToe();
render();
});
function render() {
let html = '';
for (let i = 0; i < 3; i++) {
html += '<div class="row">';
for (let j = 0; j < 3; j++) {
html += `<div class="column">${game.getFieldValue(i, j) || ''}</div>`;
}
html += '</div>';
}
gameCanvas.innerHTML = html;
}
render();
gameCanvas.addEventListener('click', e => {
if (!e.target.classList.contains('column')) {
return;
}
const rowIndex = Array.from(gameCanvas.children).indexOf(e.target.parentNode);
const colIndex = Array.from(e.target.parentNode.children).indexOf(e.target);
game.nextTurn(rowIndex, colIndex);
const winner = game.getWinner();
const isDraw = game.isDraw();
render();
if (winner) {
setTimeout(() => {
alert(`${winner} won!`);
window.game = new TicTacToe();
render();
}, 10)
}
if (isDraw) {
setTimeout(() => {
alert(`It's a draw`);
window.game = new TicTacToe();
render();
}, 10);
}
})