Next / Previous / Contents / Shipman's homepage

59. Slot.findCoord(): Puzzle position to slot position

kkck
# - - -   S l o t . f i n d C o o r d

    def findCoord ( self, coord ):
        '''What position in this slot corresponds to a given coord?
        '''

We are trying to determine the offset within the slot of a given puzzle coordinate, and we must also insure that the coordinate is actually within the slot. There are two cases, depending on the slot's orientation.

We must also insure that the offset is in the half-open interval [0, self.length), or raise IndexError because coord is outside this slot.

Since the Coord class defines subtraction on coordinates, we start by finding the offset between the slot's origin and coord. See Section 75, “class Coord: One location in the grid”.

kkck
        #-- 1 --
        # [ offset  :=  distance coord is to the right of and
        #       below self.origin, as a Coord instance ]
        offset = coord - self.origin

        #-- 2 --
        if (offset[0] < 0) or (offset[1] < 0):
            raise IndexError

Next comes the check that the offset does not exceed the length of the slot in the slot's orientation, and that the offset is exactly zero in the opposite direction.

kkck
        #-- 3 --
        # [ if self.isV ->
        #     rowLimit  :=  0
        #     colLimit  :=  self.length
        #   else ->
        #     rowLimit  :=  self.length
        #     colLimit  :=  0 ]
        rowLimit, colLimit = 1, self.length
        if self.isV:
            rowLimit, colLimit = colLimit, rowLimit

        #-- 4 --
        if ( (offset[0] >= rowLimit) or
             (offset[1] >= colLimit) ):
            raise IndexError

All that remains is to return the appropriate part of the offset: the column offset for horizontal slots, the row offset for vertical slots.

kkck
        #-- 5 --
        # [ if self.isV ->
        #     return offset[1]
        #   else ->
        #     return offset[0] ]
        return offset[perpendicular(self.isV)]