@@ -24,22 +24,75 @@ class Board {
2424 for ( let y = 0 ; y < size ; y ++ ) {
2525 const row = [ ] ;
2626 for ( let x = 0 ; x < size ; x ++ ) {
27- row . push ( new Square ( ) ) ;
27+ row . push ( new Square ( x , y ) ) ;
2828 }
2929 this . board . push ( row ) ;
3030 }
3131 }
3232
3333 move ( color , x , y ) {
34- const square = this . board [ y ] [ x ] ;
34+ const square = this . get ( x , y ) ;
3535
36- if ( square . isEmpty ( ) ) {
36+ if ( square && square . isEmpty ( ) ) {
3737 square . set ( color ) ;
38+
39+ this . turnPieces ( square ) ;
40+ this . checkWinner ( ) ;
41+
42+ } else {
43+ throw new Error ( `Illegal move. This square already has a piece on (${ x } , ${ y } )` ) ;
44+ }
45+ }
46+
47+ get ( x , y ) {
48+ if ( x < this . size && y < this . size ) {
49+ return this . board [ y ] [ x ] ;
3850 } else {
39- // throw new Error(`Illegal move. This square already has a piece on (${x}, ${y})` );
51+ return new Square ( ) ;
4052 }
4153 }
4254
55+ getAdjacents ( square ) {
56+ const x = square . x ;
57+ const y = square . y ;
58+
59+ return {
60+ top : this . get ( x , y - 1 ) ,
61+ bottom : this . get ( x , y + 1 ) ,
62+ right : this . get ( x + 1 , y ) ,
63+ left : this . get ( x - 1 , y )
64+ } ;
65+ }
66+
67+ turnPieces ( square ) {
68+ // check adjacent pieces of other color
69+ const adjacents = this . getAdjacents ( square ) ;
70+
71+ // check if the adjacent piece is preceded by other piece of different color
72+ Object . values ( adjacents ) . forEach ( ( adj ) => {
73+ if ( ! adj . isEmpty ( ) && adj . color !== square . color ) {
74+ if ( this . isSurrounded ( adj ) ) {
75+ adj . color = square . color ;
76+ }
77+ }
78+ } ) ;
79+ }
80+
81+ isSurrounded ( square ) {
82+ const adjacents = this . getAdjacents ( square ) ;
83+ const left = adjacents . left . color ;
84+ const right = adjacents . right . color ;
85+ const top = adjacents . top . color ;
86+ const bottom = adjacents . bottom . color ;
87+
88+ return ( left && left === right && square . color !== left ) ||
89+ ( top && top === bottom && square . color !== top ) ;
90+ }
91+
92+ checkWinner ( ) {
93+
94+ }
95+
4396 toString ( ) {
4497 let string = '' ;
4598
@@ -66,12 +119,14 @@ class Player {
66119}
67120
68121class Square {
69- constructor ( ) {
122+ constructor ( x , y ) {
70123 this . color = null ;
124+ this . x = x ;
125+ this . y = y ;
71126 }
72127
73128 isEmpty ( ) {
74- return this . color === null ;
129+ return ! this . color ;
75130 }
76131
77132 set ( color ) {
@@ -90,10 +145,14 @@ function main() {
90145
91146 // default play
92147 p1 . play ( 3 , 3 ) ;
93- p1 . play ( 4 , 4 ) ;
94148 p2 . play ( 3 , 4 ) ;
149+ p1 . play ( 4 , 4 ) ;
95150 p2 . play ( 4 , 3 ) ;
96151
152+ // Players game
153+ p1 . play ( 5 , 3 ) ;
154+ p2 . play ( 3 , 2 ) ;
155+
97156 console . log ( game . board . toString ( ) ) ;
98157}
99158
0 commit comments