diff --git a/README.md b/README.md index f4353d5..e1038de 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,18 @@ The status can simply be retrieved after any move with the code below: Status status = game.getStatus(); ``` +### Captured pieces + +The easy way to get the captured pieces of a game is simple to use the `JChessGame.getCaptured` method: + +```java +JChessGame game = JChessGame.newGame(); +game.play("e4", "d5", "exd5"); + +game.getCaptured(Color.WHITE); //empty +game.getCaptured(Color.BLACK); //contains 1 Pawn entity +``` + ### Import games from PGN files It is possible to import basic [PGN](https://en.wikipedia.org/wiki/Portable_Game_Notation) files diff --git a/src/main/java/ch/astorm/jchess/JChessGame.java b/src/main/java/ch/astorm/jchess/JChessGame.java index 273b1cb..c814096 100644 --- a/src/main/java/ch/astorm/jchess/JChessGame.java +++ b/src/main/java/ch/astorm/jchess/JChessGame.java @@ -312,6 +312,18 @@ public List back(int nbMoves) { return dropped; } + /** + * Returns the captured pieces of the specified {@code Color} based on the current + * position move histoy. + */ + public List getCaptured(Color color) { + return position.getMoveHistory().stream(). + map(m -> m.getCapturedEntity()). + filter(m -> m!=null). + filter(m -> m.getColor()==color). + collect(Collectors.toList()); + } + /** * Returns the {@link Color} that has the move. */ diff --git a/src/test/java/ch/astorm/jchess/JChessGameTest.java b/src/test/java/ch/astorm/jchess/JChessGameTest.java index 73738b1..b08b12c 100644 --- a/src/test/java/ch/astorm/jchess/JChessGameTest.java +++ b/src/test/java/ch/astorm/jchess/JChessGameTest.java @@ -9,6 +9,7 @@ import ch.astorm.jchess.core.entities.Bishop; import ch.astorm.jchess.core.entities.King; import ch.astorm.jchess.core.entities.Knight; +import ch.astorm.jchess.core.entities.Pawn; import ch.astorm.jchess.core.entities.Queen; import ch.astorm.jchess.core.entities.Rook; import ch.astorm.jchess.core.rules.RuleManager; @@ -37,6 +38,8 @@ public void testInitialPosition() { JChessGame game = JChessGame.newGame(); assertNull(game.get("e5")); assertNotNull(game.get("a1")); + assertTrue(game.getCaptured(Color.WHITE).isEmpty()); + assertTrue(game.getCaptured(Color.BLACK).isEmpty()); assertEquals(20, game.getAvailableMoves().size()); @@ -204,4 +207,17 @@ public void testDrawByStalemate() { assertEquals(Status.DRAW_STALEMATE, game.play("Qg6")); assertThrows(IllegalStateException.class, () -> game.play("Qg5")); } + + @Test + public void testCapturedPieces() { + JChessGame game = JChessGame.newGame(); + game.play("e4", "d5", "exd5"); + + assertTrue(game.getCaptured(Color.WHITE).isEmpty()); + + List capturedBlack = game.getCaptured(Color.BLACK); + assertEquals(1, capturedBlack.size()); + assertEquals(Color.BLACK, capturedBlack.get(0).getColor()); + assertTrue(capturedBlack.get(0) instanceof Pawn); + } }