Hackbright Code Challenges

Battleship!: Solution

Battleship!: Solution

Problem

Battleship!

Challenge

Harder

Concepts

Object Orientation, Reading Code

Download

battleship-solution.zip


Our Ship.place method:

class Ship(object):  # ...
    def place(self, col, row, direction):
        """Place ship.

        Given a row and column and direction, determine coordinates
        ship will occupy and update it's coordinates property.

        Raises an exception for an illegal direction.

        This is meant to be an abstract class--you should subclass it
        for individual ship types.

            >>> class TestShip(Ship):
            ...     _length = 3
            ...     name = "Test Ship"

        Let's make a ship and place it:

            >>> ship = TestShip()

            >>> ship.place(1, 2, "H")
            >>> ship.coords
            [(1, 2), (2, 2), (3, 2)]

            >>> ship.place(1, 2, "V")
            >>> ship.coords
            [(1, 2), (1, 3), (1, 4)]

        Illegal directions raise an error:

            >>> ship.place(1, 2, "Z")
            Traceback (most recent call last):
            ...
            ValueError: Illegal direction
        """

        # START SOLUTION

        if direction == "H":
            self.coords = [(c, row) for c in range(col, col + self._length)]

        elif direction == "V":
            self.coords = [(col, r) for r in range(row, row + self._length)]

        else:
            raise ValueError("Illegal direction")

Our Player.is_dead method uses the all function, but you could write it out in a loop, too:

class Player(object):  # ...
    def is_dead(self):
        """Is player dead (out of ships)?

            >>> player = Player('Jane')

        Since they have no placed ships, they're technically dead:

            >>> player.is_dead()
            True

        Let's place some ships:

            >>> destroyer = Destroyer()
            >>> player.place_ship(destroyer, 1, 2, "V")
            >>> player.is_dead()
            False

        And we'll hit a ship:

            >>> player.handle_shot(1, 2)
            Hit!

            >>> player.is_dead()
            False

        And destroy it (and it's their only ship, too1)

            >>> player.handle_shot(1, 3)
            Hit!
            You sunk my Destroyer

            >>> player.is_dead()
            True
        """

        # START SOLUTION

        return all(ship.is_sunk() for ship in self._ships)