File tree Expand file tree Collapse file tree 1 file changed +100
-0
lines changed
src/07-object-oriented-design Expand file tree Collapse file tree 1 file changed +100
-0
lines changed Original file line number Diff line number Diff line change 1+ class Othello {
2+ constructor ( ) {
3+ this . board = new Board ( 8 ) ;
4+ this . player1 = new Player ( Piece . WHITE , this . board ) ;
5+ this . player2 = new Player ( Piece . BLACK , this . board ) ;
6+ }
7+ }
8+
9+ class Piece {
10+
11+ }
12+
13+ // Piece.WHITE = Symbol('x');
14+ // Piece.BLACK = Symbol('o');
15+ Piece . WHITE = 'x' ;
16+ Piece . BLACK = 'o' ;
17+
18+
19+ class Board {
20+ constructor ( size ) {
21+ this . size = size ;
22+ this . board = [ ] ;
23+
24+ for ( let y = 0 ; y < size ; y ++ ) {
25+ const row = [ ] ;
26+ for ( let x = 0 ; x < size ; x ++ ) {
27+ row . push ( new Square ( ) ) ;
28+ }
29+ this . board . push ( row ) ;
30+ }
31+ }
32+
33+ move ( color , x , y ) {
34+ const square = this . board [ y ] [ x ] ;
35+
36+ if ( square . isEmpty ( ) ) {
37+ square . set ( color ) ;
38+ } else {
39+ // throw new Error(`Illegal move. This square already has a piece on (${x}, ${y})`);
40+ }
41+ }
42+
43+ toString ( ) {
44+ let string = '' ;
45+
46+ for ( let y = 0 ; y < this . size ; y ++ ) {
47+ for ( let x = 0 ; x < this . size ; x ++ ) {
48+ string += `\t${ this . board [ y ] [ x ] . toString ( ) } ` ;
49+ }
50+ string += '\n' ;
51+ }
52+
53+ return string ;
54+ }
55+ }
56+
57+ class Player {
58+ constructor ( color , board ) {
59+ this . color = color ;
60+ this . board = board ;
61+ }
62+
63+ play ( x , y ) {
64+ this . board . move ( this . color , x , y ) ;
65+ }
66+ }
67+
68+ class Square {
69+ constructor ( ) {
70+ this . color = null ;
71+ }
72+
73+ isEmpty ( ) {
74+ return this . color === null ;
75+ }
76+
77+ set ( color ) {
78+ this . color = color ;
79+ }
80+
81+ toString ( ) {
82+ return this . color ? this . color . toString ( ) : '.' ;
83+ }
84+ }
85+
86+ function main ( ) {
87+ const game = new Othello ( ) ;
88+ const p1 = game . player1 ;
89+ const p2 = game . player2 ;
90+
91+ // default play
92+ p1 . play ( 3 , 3 ) ;
93+ p1 . play ( 4 , 4 ) ;
94+ p2 . play ( 3 , 4 ) ;
95+ p2 . play ( 4 , 3 ) ;
96+
97+ console . log ( game . board . toString ( ) ) ;
98+ }
99+
100+ main ( ) ;
You can’t perform that action at this time.
0 commit comments