-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
78 lines (66 loc) · 1.5 KB
/
main.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
let currentPlayer = 'X';
let gameState = ['','','','','','','','',''];
let winner =document.getElementById('winner');
let winnerDeclared = false;
const winConditions = [
[0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[0,4,8],
[2,4,6]
]
//handle my click
function handleClick()
{
let td = event.target;
let index = td.getAttribute('index');
//check if empty
if(td.innerHTML == '')
{
//writing the symbol
td.innerHTML = currentPlayer;
gameState[index] = currentPlayer;
//check for winner
checkWinner();
checkDraw();
changePlayer();
}
}
function changePlayer()
{
currentPlayer = currentPlayer == 'X' ? 'O' : 'X';
}
//check for winner
function checkWinner (){
for (let i = 0;i<8 ;i++)
{
var a = winConditions[i][0];
var b = winConditions[i][1];
var c = winConditions[i][2];
if(gameState[a] == currentPlayer &&
gameState[b] == currentPlayer &&
gameState[c] == currentPlayer){
winnerDeclared =true;
winner.innerHTML = "Winner is "+currentPlayer;
}
}
}
function checkDraw ()
{
if(!gameState.includes('') && winnerDeclared == false)
{
winner.innerHTML = 'Game is Tied';
}
}
//check for draw
function init() {
var tdCells = document.getElementsByTagName('td');
for( let i = 0 ;i<9;i++)
{
tdCells[i].addEventListener('click',handleClick);
}
}
init();