Ta bort try-catch och byt ut mot gamla goda if-statements

This commit is contained in:
loveb 2022-04-28 19:56:45 +02:00
parent d1d453b0b0
commit 6afee98235

View File

@ -66,44 +66,42 @@ public abstract class Piece {
} }
} }
protected boolean addMovesIfCan(Point pos, ArrayList movable, Piece[][] pieces, boolean isSelected) { protected boolean addMovesIfCan(Point pos, ArrayList<Point> movable, Piece[][] pieces, boolean isSelected) {
// Instead of checking index and null, try-catch // Ifall vi är utanför brädet ge tillbaka false
try { if (pos.x > 7 || pos.x < 0 || pos.y > 7 || pos.y < 0) {
// Ifall vi kollar utanför brädet kommer detta att faila return false;
Piece p = pieces[pos.x][pos.y]; }
// Ifall pjäsen här har samma färg som oss, break Piece pieceToCheck = pieces[pos.x][pos.y];
// Ifall det inte är någon pjäs här kommer det att ner till
// catch(NullPointerException) och lägger vi till detta drag i listan
if (p.white == this.white) {
return true;
} else {
// Detta betyder att det är en med motsatts pjäs här
// Vi kan ta men inte längre.
if (!isSelected) {
movable.add(pos);
} else {
tryToMoveAndCheckIfCheck(pieces, movable, pos);
}
return true;
} // Detta är en tom plats
} catch (NullPointerException npe) { if (pieceToCheck == null) {
// Detta är en tom plats, vi ska inte breaka
if (!isSelected) { if (!isSelected) {
movable.add(pos); movable.add(pos);
return false; } else {
tryToMoveAndCheckIfCheck(pieces, movable, pos);
} }
// Fortsätt att
tryToMoveAndCheckIfCheck(pieces, movable, pos);
return false; return false;
} catch (IndexOutOfBoundsException ioobe) {
// This means that the player is at the edge
} catch (Exception e) {
// For good meassure
} }
return false;
/**
* Ifall det är en pjäs i motståndarlaget här kan vi ta den men inte
* längre Ifall det är samma färg som oss betyder det att vi inte kan
* lägga till den
*/
if (pieceToCheck.isWhite() != this.white) {
/**
* Detta betyder att det är en motsatts pjäs här, vi kan ta men inte
* längre
*/
if (!isSelected) {
movable.add(pos);
} else {
tryToMoveAndCheckIfCheck(pieces, movable, pos);
}
}
return true;
} }