diff --git a/src/schack/King.java b/src/schack/King.java index 61f524d..466f4d8 100644 --- a/src/schack/King.java +++ b/src/schack/King.java @@ -4,6 +4,7 @@ import java.awt.Point; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashSet; +import javax.swing.text.Position; public final class King extends PieceKnownIfMoved { @@ -18,6 +19,69 @@ public final class King extends PieceKnownIfMoved { return true; } + private void addCastlingIfCan(Piece[][] pieces, LinkedHashSet movable, Point toMove, Point selected) { + if (hasMoved) { + return; + } + + // Vänster + boolean nothingInBetween = true; + for (int loopX = this.position.x - 1; loopX >= 0; loopX--) { + + // Kolla ifall vi kollar tornet och inget är emellan + if (loopX == 0 && nothingInBetween) { + movable.add(new Point(2, this.position.y)); + } + + // Kolla ifall det är tomt emellan kung och torn + if (pieces[loopX][this.position.y] != null) { + nothingInBetween = false; + } + + } + + // Höger + for (int loopX = this.position.x + 1; loopX <= 7; loopX++) { + + // Kolla ifall vi kollar tornet och inget är emellan + if (loopX == 7 && nothingInBetween) { + movable.add(new Point(6, this.position.y)); + } + + // Kolla ifall det är tomt emellan kung och torn + if (pieces[loopX][this.position.y] != null) { + nothingInBetween = false; + } + } + + } + + private void castle(Piece[][] pieces, boolean left) { + + Piece rook = pieces[left ? 0 : 7][this.position.y]; + Piece king = this; + + // Null där de stod + pieces[king.position.x][king.position.y] = null; + pieces[rook.position.x][rook.position.y] = null; + // Uppdatera internt minne + king.position.x = left ? 2 : 6; + rook.position.x = left ? 3 : 5; + // Uppdatera brädet + pieces[king.position.x][king.position.y] = king; + pieces[rook.position.x][rook.position.y] = rook; + } + + @Override + public void move(Piece[][] pieces, Point toMove, Point selected) { + if (Math.abs(selected.x - toMove.x) == 2) { + castle(pieces, isWhite); + } else { + super.move(pieces, toMove, selected); + } + + } + @Override public LinkedHashSet validMoves(Piece[][] pieces) { LinkedHashSet movable = new LinkedHashSet<>(); @@ -31,6 +95,7 @@ public final class King extends PieceKnownIfMoved { } } + addCastlingIfCan(pieces, movable, position, position); return movable; } diff --git a/src/schack/Piece.java b/src/schack/Piece.java index 3044abd..4868214 100644 --- a/src/schack/Piece.java +++ b/src/schack/Piece.java @@ -58,7 +58,7 @@ public abstract class Piece { } } - + protected boolean addMovesIfCan(Point pos, LinkedHashSet movable, Piece[][] pieces) { // Instead of checking index and null, try-catch try { diff --git a/src/schack/PieceKnownIfMoved.java b/src/schack/PieceKnownIfMoved.java index 50500d4..6ee0718 100644 --- a/src/schack/PieceKnownIfMoved.java +++ b/src/schack/PieceKnownIfMoved.java @@ -22,4 +22,8 @@ public abstract class PieceKnownIfMoved extends Piece { hasMoved = true; } + public boolean hasMoved() { + return hasMoved; + } + }