예제 #1
0
class ShipBoard(PrintableBoard):
    """A board to track a fleet of ships"""

    def __init__(self, fleet):
        super(ShipBoard, self).__init__()
        self.fleet = fleet
        self.grid = Grid()
        self.recordedStrikes = set()

        if type(fleet) is not Fleet:
            raise Exception("Expected a Fleet of ships, and instead got: ", type(fleet))

        for ship in fleet:
            self.addShip(ship)

    def addShip(self, ship):
        for point in ship:
            x, y = point.x, point.y
            ok = self.grid.Put(x, y, ship)
            if not ok:
                raise Exception("Unable to place ship at", x, y, ". Grid contains", self.grid.Get(x, y))

    """True iff we've received a strike for every ship in the fleet.
    """
    def IsFleetSunk(self):
        for ship in self.fleet:
            for point in ship:
                if point not in self.recordedStrikes:
                    return False
        return True

    """ Receive a strike at the given coordinates:
    Args:
        x - a valid x coordinate
        y - a valid y coordinate
    Returns:
        True iff the point corresponds to a hit ship.
    """
    def RecordStrike(self, x, y):
        strike = Point(x, y)
        self.recordedStrikes.add(strike)

        value = self.grid.Get(x, y)
        return (value is not None)


    def getPositionType(self, point):
        isStrike = point in self.recordedStrikes
        gridValue = self.grid.Get(point.x, point.y)
        isShip = type(gridValue) == Ship

        if isStrike and isShip:
            return STRUCK_SHIP
        elif isShip and not isStrike:
            return SHIP
        elif not isShip and isStrike:
            return STRIKE
        else:
            return NONE
예제 #2
0
 def test_Grid_Get(self):
     g = Grid()
     self.assertIsNone(g.Get(1, "A"))
     self.assertTrue(g.Put(1, "A", "value"))
     self.assertEqual("value", g.Get(1, "A"))