def addShip(self, coordinates, player: int): """ Adds a ship to the game for the specified player at the given coordinates. The rest of the board is unmodified If all the ships are places, subsequent calls to this function replace the ships that already exist :param coordinates: The coordinates of the ship squares in the form C1L1C2L2C3L3 :param player: The player that adds the ship :raises CoordinateInvalid: If the given string do not represent coordinates or the coordinates are out of the board or the ship intersects with another ship In case an exception is thrown, the board remains unmodified """ if len(coordinates) != 6: raise CoordinateInvalid() coordinate1 = coordinates[0:2] coordinate2 = coordinates[2:4] coordinate3 = coordinates[4:6] shipCoordinates = [coordinate1, coordinate2, coordinate3] Validator.validateCoordinate(coordinate1) Validator.validateCoordinate(coordinate2) Validator.validateCoordinate(coordinate3) Validator.validateShip(coordinate1, coordinate2, coordinate3) board = self.boardRepository.getBoard(player, 1) bonusShip = None if self.shipRepository.length(player) == 2: # remove ship to be replaced bonusShip = self.shipRepository.getShip( self.shipRepository.shipIndex[player], player) for coordinate in bonusShip.coordinates: board.markAtCoordinate(coordinate, ".") for coordinate in shipCoordinates: if board.getMark(coordinate) != ".": if bonusShip is not None: # put the bonus ship back for bonusShipCoordinates in bonusShip.coordinates: board.markAtCoordinate(bonusShipCoordinates, "+") raise CoordinateInvalid() for coordinate in shipCoordinates: board.markAtCoordinate(coordinate, "+") ship = Ship(coordinate1, coordinate2, coordinate3) if self.shipRepository.length(player) != 2: self.shipRepository.addShip(ship, player) else: self.shipRepository.putShip(ship, self.shipRepository.shipIndex[player], player)
def testShipValidatoin(self): Validator.validateShip("A1", "A2", "A3") Validator.validateShip("B0", "B1", "B2") Validator.validateShip("A1", "B1", "C1") Validator.validateShip("D2", "E2", "F2") with self.assertRaises(CoordinateInvalid): Validator.validateShip("D1", "E2", "F2") with self.assertRaises(CoordinateInvalid): Validator.validateShip("A1", "A5", "A3") with self.assertRaises(CoordinateInvalid): Validator.validateShip("D1", "D2", "F2") with self.assertRaises(CoordinateInvalid): Validator.validateShip("A1", "B2", "C1")