1
+ let gameBoard = document . querySelector ( '.game-board' ) ;
2
+ let squares = document . querySelectorAll ( '.square' ) ;
3
+ let currentPlayer = 'X' ;
4
+ let gameOver = false ;
5
+
6
+ gameBoard . addEventListener ( 'click' , ( e ) => {
7
+ if ( e . target . classList . contains ( 'square' ) && ! gameOver ) {
8
+ let square = e . target ;
9
+ if ( square . textContent === '' ) {
10
+ square . textContent = currentPlayer ;
11
+ currentPlayer = currentPlayer === 'X' ? 'O' : 'X' ;
12
+ checkWinner ( ) ;
13
+ }
14
+ }
15
+ } ) ;
16
+
17
+ document . getElementById ( 'reset' ) . addEventListener ( 'click' , ( ) => {
18
+ squares . forEach ( ( square ) => {
19
+ square . textContent = '' ;
20
+ } ) ;
21
+ currentPlayer = 'X' ;
22
+ gameOver = false ;
23
+ document . getElementById ( 'turn' ) . textContent = 'Turn: X' ;
24
+ document . getElementById ( 'result' ) . textContent = '' ;
25
+ } ) ;
26
+
27
+ function checkWinner ( ) {
28
+ const winningCombinations = [
29
+ [ 'top-left' , 'top-middle' , 'top-right' ] ,
30
+ [ 'middle-left' , 'middle-middle' , 'middle-right' ] ,
31
+ [ 'bottom-left' , 'bottom-middle' , 'bottom-right' ] ,
32
+ [ 'top-left' , 'middle-left' , 'bottom-left' ] ,
33
+ [ 'top-middle' , 'middle-middle' , 'bottom-middle' ] ,
34
+ [ 'top-right' , 'middle-right' , 'bottom-right' ] ,
35
+ [ 'top-left' , 'middle-middle' , 'bottom-right' ] ,
36
+ [ 'top-right' , 'middle-middle' , 'bottom-left' ]
37
+ ] ;
38
+
39
+ for ( let combination of winningCombinations ) {
40
+ if (
41
+ document . getElementById ( combination [ 0 ] ) . textContent === currentPlayer &&
42
+ document . getElementById ( combination [ 1 ] ) . textContent === currentPlayer &&
43
+ document . getElementById ( combination [ 2 ] ) . textContent === currentPlayer
44
+ ) {
45
+ gameOver = true ;
46
+ document . getElementById ( 'result' ) . textContent = `Player ${ currentPlayer } wins!` ;
47
+ break ;
48
+ }
49
+ }
50
+
51
+ if ( ! gameOver && Array . from ( squares ) . every ( ( square ) => square . textContent !== '' ) ) {
52
+ gameOver = true ;
53
+ document . getElementById ( 'result' ) . textContent = 'It\'s a draw!' ;
54
+ }
55
+
56
+ document . getElementById ( 'turn' ) . textContent = `Turn: ${ currentPlayer } ` ;
57
+ }
0 commit comments