1
+ // TIC TAC TOE
2
+ const tic_tac_toe = {
3
+
4
+ // ATTRIBUTES
5
+ board : [ '' , '' , '' , '' , '' , '' , '' , '' , '' ] ,
6
+ symbols : {
7
+ options : [ 'O' , 'X' ] ,
8
+ turn_index : 0 ,
9
+ change ( ) {
10
+ this . turn_index = ( this . turn_index === 0 ? 1 :0 ) ;
11
+ }
12
+ } ,
13
+ container_element : null ,
14
+ gameover : false ,
15
+ winning_sequences : [
16
+ [ 0 , 1 , 2 ] ,
17
+ [ 3 , 4 , 5 ] ,
18
+ [ 6 , 7 , 8 ] ,
19
+ [ 0 , 3 , 6 ] ,
20
+ [ 1 , 4 , 7 ] ,
21
+ [ 2 , 5 , 8 ] ,
22
+ [ 0 , 4 , 8 ] ,
23
+ [ 2 , 4 , 6 ]
24
+ ] ,
25
+
26
+ // FUNCTIONS
27
+ init ( container ) {
28
+ this . container_element = container ;
29
+ } ,
30
+
31
+ make_play ( position ) {
32
+ if ( this . gameover || this . board [ position ] !== '' ) return false ;
33
+
34
+ const currentSymbol = this . symbols . options [ this . symbols . turn_index ] ;
35
+ this . board [ position ] = currentSymbol ;
36
+ this . draw ( ) ;
37
+
38
+ const winning_sequences_index = this . check_winning_sequences ( currentSymbol ) ;
39
+ if ( this . is_game_over ( ) ) {
40
+ this . game_is_over ( ) ;
41
+ }
42
+ if ( winning_sequences_index >= 0 ) {
43
+ this . game_is_over ( ) ;
44
+ this . stylize_winner_sequence ( this . winning_sequences [ winning_sequences_index ] ) ;
45
+ } else {
46
+ this . symbols . change ( ) ;
47
+ }
48
+
49
+ return true ;
50
+ } ,
51
+
52
+ stylize_winner_sequence ( winner_sequence ) {
53
+ winner_sequence . forEach ( ( position ) => {
54
+ this
55
+ . container_element
56
+ . querySelector ( `div:nth-child(${ position + 1 } )` )
57
+ . classList . add ( 'winner' ) ;
58
+ } ) ;
59
+ } ,
60
+
61
+ check_winning_sequences ( symbol ) {
62
+
63
+ for ( i in this . winning_sequences ) {
64
+ if ( this . board [ this . winning_sequences [ i ] [ 0 ] ] == symbol &&
65
+ this . board [ this . winning_sequences [ i ] [ 1 ] ] == symbol &&
66
+ this . board [ this . winning_sequences [ i ] [ 2 ] ] == symbol ) {
67
+ console . log ( 'winning sequences INDEX:' + i ) ;
68
+ return i ;
69
+ }
70
+ } ;
71
+ return - 1 ;
72
+ } ,
73
+
74
+ game_is_over ( ) {
75
+ this . gameover = true ;
76
+ console . log ( 'GAME OVER' ) ;
77
+ } ,
78
+
79
+ is_game_over ( ) {
80
+ return ! this . board . includes ( '' ) ;
81
+ } ,
82
+
83
+ start ( ) {
84
+ this . board . fill ( '' ) ;
85
+ this . draw ( ) ;
86
+ this . gameover = false ;
87
+ } ,
88
+
89
+ restart ( ) {
90
+ if ( this . is_game_over ( ) || this . gameover ) {
91
+ this . start ( ) ;
92
+ console . log ( 'this game has been restarted!' )
93
+ } else if ( confirm ( 'Are you sure you want to restart this game?' ) ) {
94
+ this . start ( ) ;
95
+ console . log ( 'this game has been restarted!' )
96
+ }
97
+ } ,
98
+
99
+ draw ( ) {
100
+ this . container_element . innerHTML = this . board . map ( ( element , index ) => `<div onclick="tic_tac_toe.make_play('${ index } ')"> ${ element } </div>` ) . reduce ( ( content , current ) => content + current ) ;
101
+ } ,
102
+ } ;
0 commit comments