-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
106 lines (88 loc) · 2.73 KB
/
script.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// constants
const STARTED = 0
const ENDED = 1
// HTML elements
const playerSpan = document.getElementById('player')
const gameTable = document.getElementById('game')
const game = {
state: STARTED,
turn: 'X',
move: 0
}
function endGame(winner) {
if (winner) {
alert('Game Over | Winner = ' + winner)
} else {
alert('Game Over | Draw')
}
game.state = ENDED
}
function restartGame() {
if (Math.random() > 0.5) game.turn = 'O'
else game.turn = 'X'
game.state = STARTED
game.move = 0
//if we played some but move != 9 and restart is clicked so we clear all cell.
Array.from(document.getElementsByTagName('td')).forEach(cell => {
cell.textContent = ''
})
}
function nextTurn() {
if (game.state === ENDED) return
game.move++
if (game.turn === 'X') game.turn = 'O'
else game.turn = 'X'
if (game.move == 9) {
//alert('Game Over')
endGame()
}
// change content of text which is in span with id=player
playerSpan.textContent = game.turn
}
function isSeqCaptured(arrayOf3Cells) {
let winnningCombo = game.turn + game.turn + game.turn
// map(i => i.textContent) give table row or col content
if (arrayOf3Cells.map(i => i.textContent).join('') === winnningCombo) {
endGame(game.turn)
}
}
function isRowCaptured(row) {
let tableRow = Array.from(gameTable.children[0].children[row - 1].children)
isSeqCaptured(tableRow)
}
function isColCaptured(col) {
let tableCol = [
gameTable.children[0].children[0].children[col - 1],
gameTable.children[0].children[1].children[col - 1],
gameTable.children[0].children[2].children[col - 1]
]
isSeqCaptured(tableCol)
}
function isDiagCaptured(row, col) {
if (row !== col && (row + col) !== 4) return
let diag1 = [
gameTable.children[0].children[0].children[0],
gameTable.children[0].children[1].children[1],
gameTable.children[0].children[2].children[2]
]
let diag2 = [
gameTable.children[0].children[0].children[2],
gameTable.children[0].children[1].children[1],
gameTable.children[0].children[2].children[0]
]
isSeqCaptured(diag1)
isSeqCaptured(diag2)
}
function boxClicked(row, col) {
if (game.state === ENDED) {
alert('Game Ended | Restart to Play Again')
return
}
console.log('box clicked = ', row, col)
let clickedBox = gameTable.children[0].children[row - 1].children[col - 1] // as per array term
clickedBox.textContent = game.turn
isRowCaptured(row)
isColCaptured(col)
isDiagCaptured(row, col)
nextTurn()
}