-
Notifications
You must be signed in to change notification settings - Fork 755
Expand file tree
/
Copy pathmain.py
More file actions
68 lines (61 loc) · 2.12 KB
/
main.py
File metadata and controls
68 lines (61 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class Deck:
def __init__(self, row: int, column: int, is_alive: bool = True) -> None:
self.row = row
self.column = column
self.is_alive = is_alive
class Ship:
def __init__(
self,
start: tuple,
end: tuple,
is_drowned: bool = False
) -> None:
if start[0] == end[0] and start[1] <= end[1]:
self.decks = [
Deck(start[0], i) for i in range(start[1], end[1] + 1)
]
elif start[0] == end[0] and start[1] > end[1]:
self.decks = [
Deck(start[0], i) for i in range(end[1], start[1] + 1)
]
elif start[1] == end[1] and start[0] <= end[0]:
self.decks = [
Deck(i, start[1]) for i in range(start[0], end[0] + 1)
]
elif start[1] == end[1] and start[0] > end[0]:
self.decks = [
Deck(i, start[1]) for i in range(end[0], start[0] + 1)
]
self.is_drowned = is_drowned
def get_deck(self, row: int, column: int) -> Deck | None:
for deck in self.decks:
if deck.column == column and deck.row == row:
return deck
return None
def fire(self, row: int, column: int) -> None:
deck_shot = self.get_deck(row, column)
if deck_shot is None:
return
deck_shot.is_alive = False
count = 0
for deck in self.decks:
if deck.is_alive is False:
count += 1
if len(self.decks) == count:
self.is_drowned = True
class Battleship:
def __init__(self, ships: list) -> None:
self.field = {}
for ship_tuple in ships:
ship_obj = Ship(ship_tuple[0], ship_tuple[1])
for deck in ship_obj.decks:
self.field[(deck.row, deck.column)] = ship_obj
def fire(self, location: tuple) -> str:
if location not in self.field:
return "Miss!"
ship = self.field[location]
ship.fire(location[0], location[1])
if ship.is_drowned:
return "Sunk!"
else:
return "Hit!"