-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
103 lines (77 loc) · 2.76 KB
/
game.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
class Game{
constructor(playerX,playerO){
this.playerX = playerX
this.playerO = playerO
this.current_player= playerX
}
changePlayer(){
if (this.current_player.char==='X'){
this.current_player=this.playerO
}
else{
this.current_player = this.playerX
}
}
}
class Player{
constructor(char,clr){
this.char = char
this.clr = clr
}
}
function play(e){
if (isGameContinue){
let position
for(var key of BoardItems.keys()) {
if (e.target === BoardItems.item(key)){
position = key
break
}
}
let row=Math.floor(position/3) //floor division by 3
let column=(position%3)
if (board[row][column]===0){
e.target.innerHTML=`${g.current_player.char}`
e.target.style.color=g.current_player.clr
board[row][column]=g.current_player.char
if (checkWinner()){
console.log(checkWinner())
document.getElementById('currentPlayer').innerHTML=`Player ${g.current_player.char} won`
isGameContinue=false
}
else{
g.changePlayer()
document.getElementById('currentPlayer').innerHTML=`Player ${g.current_player.char}'s Turn`
}
}
}
}
function checkWinner(){
for (var i=0;i<=3;i++){
if (board[0][i]===board[1][i] && board[1][i]===board[2][i] && board[0][i]!=0){
return board[0][i]
}
else if (board[i][0]===board[i][1] && board[i][1]===board[i][2] && board[i][0]!=0){
// #Checking row
return board[i][0]
}
else {
if (board[0][0]===board[1][1] && board[1][1]===board[2][2] && board[1][1]!=0){
return board[1][1]
}
else if (board[0][2]===board[1][1] && board[2][0]===board[1][1] && board[1][1]!=0){
return board[1][1]
}
else {
continue
}
}
}
}
let isGameContinue = true;
playerX=new Player('X', 'red')
playerO=new Player('O', 'blue')
g= new Game(playerX,playerO)
board=[ [0,0,0] , [0,0,0] , [0,0,0] ]
const BoardItems =document.querySelectorAll('.board-item')
BoardItems.forEach( function (boardItem){boardItem.addEventListener('click', play)})