Skriv bort try-catch

This commit is contained in:
loveb 2022-05-03 15:46:04 +02:00
parent 0adba36150
commit 828cc7ed5b

View File

@ -84,38 +84,17 @@ public class Pawn extends PieceKnownIfMoved {
} }
@Override @Override
protected boolean addMovesIfCan(Point pos, ArrayList movable, Piece[][] pieces, boolean isSelected) { protected boolean addMovesIfCan(Point pos, ArrayList<Point> movable, Piece[][] pieces, boolean isSelected) {
if (pos.x < 0 || pos.x > 7 || pos.y < 0 || pos.y > 7) { if (pos.x < 0 || pos.x > 7 || pos.y < 0 || pos.y > 7) {
return false; return false;
} }
// Instead of checking index and null, try-catch
try {
// Ifall vi kollar utanför brädet kommer detta att faila
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 if (pieceToCheck != null) {
// catch(NullPointerException) och lägger vi till detta drag i listan return true;
// Ifall det är inte är en pjäs här, kasta ett NullPointerException } else {
// Detta är för att vara lik super-implementationen som möjligt
if (p == null) {
throw new NullPointerException();
} else {
// Detta betyder att det finns en pjäs här
// Vi kan ta men inte längre.
return true;
}
} catch (NullPointerException npe) {
// This is an empty spot
tryToMoveAndCheckIfCheck(pieces, movable, pos); tryToMoveAndCheckIfCheck(pieces, movable, pos);
} catch (IndexOutOfBoundsException ioobe) { return false;
// This means that the player is at the edge
System.out.println(pos);
} catch (Exception e) {
// For good meassure
} }
return false;
} }
} }