Next / Previous / Contents / Shipman's homepage

75. class Coord: One location in the grid

Each instance of this class represents the intersection of a row and column, where a cell may occur (or not, if that location is blank in the framework).

kkck
# - - - - -   c l a s s   C o o r d

class Coord(object):
    '''Represents one location in the puzzle grid.

      Exports:
        Coord ( row, column ):
          [ (row is a nonnegative row number) and
            (column is a nonnegative column number) ->
              return a new Coord representing the intersection of
              row (row) and column (column) ]
        .rc:
          [ a two-tuple (self[0], self[1]); read-only ]
        .__cmp__(self, other):
          [ define an ordering with row number as the primary key
            and column number as the secondary key ]
        .__getitem__(self, isCol):
          [ isCol is 0 ->
              return self's row
            isCol is 1 ->
              return self's column ]
        .__setitem__(self, isCol, value):
          [ isCol is 0 ->
              self[0] := value
            isCol is 1 ->
              self[1] := value ]
        .__add__(self, other):
          [ return a new Coord with row (self[0]+other[0]) and
            column (self[1]+other[1]) ]
        .__sub__(self, other):
          [ return a new Coord with row (self[0]-other[0]) and
            column (self[1]-other[1]) ]
        .__str__(self): [ return a textual representation of self ]
    '''
    def __init__ ( self, row, col ):
        self.rc = [row, col]

    def __cmp__ ( self, other ):
        return cmp ( self.rc, other.rc )

    def __getitem__(self, isCol):
        return self.rc[isCol]

    def __setitem__(self, isCol, value):
        self.rc[isCol] = value

    def __add__ ( self, other ):
        return Coord ( self[0]+other[0], self[1]+other[1] )

    def __sub__ ( self, other ):
        return Coord ( self[0]-other[0], self[1]-other[1] )

    def __str__ ( self ):
        return "(%d,%d)" % (self[0], self[1])