-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtic-tac-toe-ui.js
80 lines (67 loc) · 1.56 KB
/
tic-tac-toe-ui.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
window.onload = onLoaded;
let cells;
let board;
let side;
let announce;
function onLoaded() {
cells = document.querySelectorAll('td');
announce = document.querySelector('div.announce');
for (let i = 0; i < 9; i++) {
cells[i].onclick = () => {
onClickCell(i);
};
}
restartGame();
}
function restartGame() {
board = [0,0,0,0,0,0,0,0,0];
side = 1;
displayBoard(board);
announce.textContent = '';
}
function checkGame() {
let winner = hasWon(board);
if (winner !==0) {
let mark = winner === 1 ? 'X' : 'O';
announce.textContent = `${mark} wins!`;
return;
}
if (isFull(board)) {
announce.textContent = 'Draw!';
}
}
function computerMoves() {
let bestMove = findBestMove(board, side);
if (bestMove.pos !== undefined) {
board[bestMove.pos] = side;
side = -side;
displayBoard(board);
}
checkGame();
}
function onClickCell(i) {
console.log(`Number ${i} got clicked!`);
if (isFull(board) || hasWon(board) !== 0) {
console.log(`Game is over - stop playing!=`);
return;
}
if (board[i] !== 0) {
console.log('Cell already taken!');
return;
}
board[i] = side;
side = -side;
displayBoard(board);
computerMoves();
}
function displayBoard(board) {
for (let i = 0; i < 9; i++) {
let value = ' ';
if (board[i] == -1) {
value = 'O';
} else if (board[i] == 1) {
value = 'X';
}
cells[i].textContent = value;
}
}