From 0c40eba66fe49e2de4fd0c33cf31385ff1c3b646 Mon Sep 17 00:00:00 2001 From: ElnuDev Date: Wed, 15 Mar 2023 23:40:45 -0700 Subject: [PATCH] Add queen promotion, fix pawn taking two squares ahead --- src/Board.java | 7 +++++-- src/Move.java | 1 + src/Pawn.java | 12 ++++++++---- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/Board.java b/src/Board.java index 2bf3dba..e04fd3b 100644 --- a/src/Board.java +++ b/src/Board.java @@ -131,9 +131,11 @@ public class Board { // White pieces disappear if new move isn't created, don't know why Move copiedMove = new Move(new BoardCoordinate(move.from.x, move.from.y), new BoardCoordinate(move.to.x, move.to.y), get(move.to.x, move.to.y)); copiedMove.submove = move.submove; + copiedMove.isPromotion = move.isPromotion; moveHistory.add(copiedMove); // moveHistory.add(move); - set(move.to, get(move.from)); + Piece movedPiece = get(move.from); + set(move.to, move.isPromotion ? new Queen(movedPiece.black, panel) : movedPiece); set(move.from, null); move(move.submove); if (move.submove != null) moveHistory.pop(); @@ -148,7 +150,8 @@ public class Board { void undoMove(Move move) { if (move == null) return; - set(move.from, get(move.to)); + Piece movedPiece = get(move.to); + set(move.from, move.isPromotion ? new Pawn(movedPiece.black, panel) : movedPiece); set(move.to, move.captured); } diff --git a/src/Move.java b/src/Move.java index 13bbd1f..e45d013 100644 --- a/src/Move.java +++ b/src/Move.java @@ -6,6 +6,7 @@ public class Move { public Piece captured; // e.g. castling, castle move. Done after. public Move submove; + public boolean isPromotion; public Move(BoardCoordinate from, BoardCoordinate to) { this.from = from; diff --git a/src/Pawn.java b/src/Pawn.java index 44e2068..5058adc 100644 --- a/src/Pawn.java +++ b/src/Pawn.java @@ -13,8 +13,10 @@ public class Pawn extends Piece { ArrayList possibleMoves = new ArrayList<>(); if (this.black) { if (board.get(position.x, position.y + 1) == null) { - possibleMoves.add(new Move(position, new BoardCoordinate(position.x, position.y + 1))); - if (!moved) { + Move oneForward = new Move(position, new BoardCoordinate(position.x, position.y + 1)); + oneForward.isPromotion = position.y + 1 == Board.BOARD_SIZE - 1; + possibleMoves.add(oneForward); + if (!moved && board.get(position.x, position.y + 2) == null) { possibleMoves.add(new Move(position, new BoardCoordinate(position.x, position.y + 2))); } } @@ -27,8 +29,10 @@ public class Pawn extends Piece { } else { if (board.get(position.x, position.y - 1) == null) { - possibleMoves.add(new Move(position, new BoardCoordinate(position.x, position.y - 1))); - if (!moved) { + Move oneForward = new Move(position, new BoardCoordinate(position.x, position.y - 1)); + oneForward.isPromotion = position.y - 1 == 0; + possibleMoves.add(oneForward); + if (!moved && board.get(position.x, position.y - 2) == null) { possibleMoves.add(new Move(position, new BoardCoordinate(position.x, position.y - 2))); } }