11package chess .pieces ;
22
33import boardgame .Board ;
4+ import boardgame .Position ;
45import chess .ChessPiece ;
56import chess .Color ;
67
7- public class King extends ChessPiece {
8+ public class King extends ChessPiece {
89
910 public King (Board board , Color color ) {
1011 super (board , color );
@@ -15,9 +16,65 @@ public String toString() {
1516 return "K" ;
1617 }
1718
19+ private boolean canMove (Position position ) {
20+ ChessPiece p = (ChessPiece ) getBoard ().piece (position );
21+ return p == null || p .getColor () != getColor ();
22+ }
23+
1824 @ Override
1925 public boolean [][] possibleMoves () {
2026 boolean [][] mat = new boolean [getBoard ().getRows ()][getBoard ().getColumns ()];
27+
28+ Position p = new Position (0 , 0 );
29+
30+ // above
31+ p .setValue (position .getRow () - 1 , position .getColumn ());
32+ if (getBoard ().positionExists (p ) && canMove (p )) {
33+ mat [p .getRow ()][p .getColumn ()] = true ;
34+ }
35+
36+ // below
37+ p .setValue (position .getRow () + 1 , position .getColumn ());
38+ if (getBoard ().positionExists (p ) && canMove (p )) {
39+ mat [p .getRow ()][p .getColumn ()] = true ;
40+ }
41+
42+ // left
43+ p .setValue (position .getRow (), position .getColumn () - 1 );
44+ if (getBoard ().positionExists (p ) && canMove (p )) {
45+ mat [p .getRow ()][p .getColumn ()] = true ;
46+ }
47+
48+ // right
49+ p .setValue (position .getRow (), position .getColumn () + 1 );
50+ if (getBoard ().positionExists (p ) && canMove (p )) {
51+ mat [p .getRow ()][p .getColumn ()] = true ;
52+ }
53+
54+ // nw
55+ p .setValue (position .getRow () - 1 , position .getColumn () - 1 );
56+ if (getBoard ().positionExists (p ) && canMove (p )) {
57+ mat [p .getRow ()][p .getColumn ()] = true ;
58+ }
59+
60+ // ne
61+ p .setValue (position .getRow () - 1 , position .getColumn () + 1 );
62+ if (getBoard ().positionExists (p ) && canMove (p )) {
63+ mat [p .getRow ()][p .getColumn ()] = true ;
64+ }
65+
66+ // sw
67+ p .setValue (position .getRow () + 1 , position .getColumn () - 1 );
68+ if (getBoard ().positionExists (p ) && canMove (p )) {
69+ mat [p .getRow ()][p .getColumn ()] = true ;
70+ }
71+
72+ // se
73+ p .setValue (position .getRow () + 1 , position .getColumn () + 1 );
74+ if (getBoard ().positionExists (p ) && canMove (p )) {
75+ mat [p .getRow ()][p .getColumn ()] = true ;
76+ }
77+
2178 return mat ;
2279 }
2380}
0 commit comments