Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solution #440

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 54 additions & 26 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,62 @@
from typing import List, Tuple


class Deck:
def __init__(self, row, column, is_alive=True):
pass
def __init__(self, row: int, col: int, alive: bool = True) -> None:
self.row = row
self.col = col
self.alive = alive


class Ship:
def __init__(self, start, end, is_drowned=False):
# Create decks and save them to a list `self.decks`
pass

def get_deck(self, row, column):
# Find the corresponding deck in the list
pass
def __init__(self, start: Tuple[int, int], end: Tuple[int, int]) -> None:
self.decks = []
self.drowned = False
row_step = start[0] == end[0]
for i in range(start[row_step], end[row_step] + 1):
pos = (start[0], i) if row_step else (i, start[1])
self.decks.append(Deck(*pos))

def fire(self, row, column):
# Change the `is_alive` status of the deck
# And update the `is_drowned` value if it's needed
pass
def fire(self, row: int, col: int) -> str:
deck = next(
(d for d in self.decks
if d.row == row and d.col == col and d.alive),
None)
if deck:
deck.alive = False
if all(not d.alive for d in self.decks):
self.drowned = True
return "Sunk!"
return "Hit!"
return None


class Battleship:
def __init__(self, ships):
# Create a dict `self.field`.
# Its keys are tuples - the coordinates of the non-empty cells,
# A value for each cell is a reference to the ship
# which is located in it
pass

def fire(self, location: tuple):
# This function should check whether the location
# is a key in the `self.field`
# If it is, then it should check if this cell is the last alive
# in the ship or not.
pass
def __init__(
self, ships: List[Tuple[Tuple[int, int], Tuple[int, int]]]
) -> None:
self.field = {
(d.row, d.col): ship
for start, end in ships
for ship in [Ship(start, end)]
for d in ship.decks
}

def fire(self, loc: Tuple[int, int]) -> str:
ship = self.field.get(loc)
return ship.fire(*loc) if ship else "Miss!"

def print_field(self) -> None:
for row in range(10):
line = "".join(self.cell_symbol(row, col) for col in range(10))
print(line)

def cell_symbol(self, row: int, col: int) -> str:
if (row, col) in self.field:
ship = self.field[(row, col)]
if ship.decks[0].alive:
return "□ "
elif ship.drowned:
return "x "
return "* "
return "~ "
Loading