private void removeAnyCapturedPieces(Move move, CheckersBoard nextState) { int takenPieceXCoord = (move.getFrom().getXCoord() + move.getTo().getXCoord()) / 2; int takenPieceYCoord = (move.getFrom().getYCoord() + move.getTo().getYCoord()) / 2; Position takenPosition = new Position(takenPieceXCoord, takenPieceYCoord); if (!move.getFrom().equals(takenPosition) && !move.getTo() .equals( takenPosition)) { // neither the from or the 2 are the calculated middle position // then it has moved more then one place. Thus we must be // capturing a piece for (Piece<CheckersPieceDescription> removedPiece : nextState.getPiecesAtPlacement(takenPosition)) { nextState.removePiece( removedPiece); // no need to check whether this is an opponents piece as this move will // become invalidated in the game service. } } }
public CheckersBoard playMove(Iterable<Move> moves) throws GameFinishedException { CheckersBoard board = gameService.getCurrentState(); CheckersBoard nextState = new CheckersBoard(boardIdService.nextId(), board); Iterable<Move> reverseStack = Lists.reverse(Lists.newArrayList(moves)); for (Move move : reverseStack) { Piece<CheckersPieceDescription> piece = getPieceAtPossition(move.getFrom(), nextState); if (!board.isValidBoardPosition(move.getTo())) { throw new IllegalArgumentException( "The move to: " + move.getTo() + " is not within the confines of the board"); } nextState.removePiece(piece); CheckersPieceDescription pieceToPlace = upgradePieceIfRequired(piece.getPiece(), move.getTo(), nextState); Piece<CheckersPieceDescription> nextPiece = new Piece<CheckersPieceDescription>(move.getTo(), pieceToPlace); nextState.addPiece(nextPiece); // create new state from current state // remove any opponents that might have been captured with this move removeAnyCapturedPieces(move, nextState); } gameService.playNextMove(nextState); return gameService.getCurrentState(); }