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' #526

Closed
wants to merge 1 commit into from
Closed
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
127 changes: 102 additions & 25 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,111 @@
from typing import List, Tuple, Dict, Optional

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The import statement is incorrect due to the use of a forward slash instead of a comma. It should be from typing import List, Tuple, Dict, Optional.



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


class Ship:
def __init__(self, start, end, is_drowned=False):
# Create decks and save them to a list `self.decks`
pass
def __init__(self, start: Tuple[int, int], end: Tuple[int, int]) -> None:
self.decks: List[Deck] = self._create_decks(start, end)
self.is_drowned: bool = False

def get_deck(self, row, column):
# Find the corresponding deck in the list
pass
def _create_decks(
self,
start: Tuple[int, int],
end: Tuple[int, int]
) -> List[Deck]:
decks: List[Deck] = []
if start[0] == end[0]: # Horizontal ship
for col in range(start[1], end[1] + 1):
decks.append(Deck(start[0], col))
elif start[1] == end[1]: # Vertical ship
for row in range(start[0], end[0] + 1):
decks.append(Deck(row, start[1]))
return decks

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 get_deck(self, row: int, column: int) -> Optional[Deck]:
for deck in self.decks:
if deck.row == row and deck.column == column:
return deck
return None

def fire(self, row: int, column: int) -> bool:
deck = self.get_deck(row, column)
if deck and deck.is_alive:
deck.is_alive = False
self.is_drowned = all(not d.is_alive for d in self.decks)
return True
return False


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.ships: List[Ship] = [Ship(start, end) for start, end in ships]
self.field: Dict[Tuple[int, int], Ship] = {}
self._initialize_field()
self._validate_field()

def _initialize_field(self) -> None:
for ship in self.ships:
for deck in ship.decks:
self.field[(deck.row, deck.column)] = ship

def fire(self, location: Tuple[int, int]) -> str:
if location not in self.field:
return "Miss!"

ship = self.field[location]
hit = ship.fire(*location)
if hit:
return "Sunk!" if ship.is_drowned else "Hit!"
return "Miss!"

def print_field(self) -> None:
field: List[List[str]] = [["~" for _ in range(10)] for _ in range(10)]
for (row, col), ship in self.field.items():
deck = ship.get_deck(row, col)
if deck.is_alive:
field[row][col] = "□" # Alive deck
elif ship.is_drowned:
field[row][col] = "x" # Drowned deck
else:
field[row][col] = "*" # Hit deck of alive ship

for row in field:
print(" ".join(row))

def _validate_field(self) -> None:
ship_lengths: List[int] = [len(ship.decks) for ship in self.ships]
if len(ship_lengths) != 10:
raise ValueError("There must be exactly 10 ships.")
Comment on lines +86 to +87

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The condition len(ship_lengths) != 10 might not be correct if the task requires a specific number of ships with specific lengths. Ensure that the number of ships and their lengths match the task requirements.


counts: Dict[int, int] = {
1: 0,
2: 0,
3: 0,
4: 0
}

for length in ship_lengths:
if length > 4:
raise ValueError("Ship lengths cannot exceed 4.")
counts[length] += 1

if (counts[1] != 4 or counts[2] != 3
or counts[3] != 2 or counts[4] != 1):
raise ValueError("Invalid ship configuration.")
Comment on lines +101 to +103

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The validation logic for ship configuration assumes a specific distribution of ship lengths. Ensure this matches the task requirements. If the task specifies a different configuration, adjust the counts accordingly.


for ship in self.ships:
for deck in ship.decks:
for row in range(deck.row - 1, deck.row + 2):
for col in range(deck.column - 1, deck.column + 2):
if ((row, col) in self.field
and self.field[(row, col)] != ship):
raise ValueError("Ships cannot be adjacent.")
Loading