-
Notifications
You must be signed in to change notification settings - Fork 0
/
Battleship.py
428 lines (310 loc) · 14.2 KB
/
Battleship.py
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# hi, this code isnt great, just sayin, its in no way a good example to follow
import functools
import itertools
from typing import List, Union, Literal, Optional
SHIP_SIZES = [5, 3, 3, 2, 2]
BOARD_SIZE = 10
class GameState:
def __init__(self):
self.board = Board()
self.remaining_ship_sizes = SHIP_SIZES.copy()
self.pending_remove_ship_sizes = []
class Coordinate:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
@staticmethod
def from_hm_style(coord: (int, int)):
return Coordinate(coord[0] - 1, coord[1] - 1)
def to_hm_style(self):
return self.x + 1, self.y + 1
def is_valid(self):
return 0 <= self.x < BOARD_SIZE and 0 <= self.y < BOARD_SIZE
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __hash__(self):
return hash((self.x, self.y))
def __str__(self):
return f"{chr(65 + self.x)}{self.y + 1}"
def __repr__(self):
return str(self)
class BoardCell:
def __init__(self):
self.checked = False
self.hit = False
self.confirmed_ship = False
def set_checked(self, hit: bool = False):
self.checked = True
self.hit = hit
def set_hit(self):
self.checked = True
self.hit = True
class Board:
def __init__(self):
self.board = [[BoardCell() for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
def get_cell(self, coordinate: Coordinate) -> BoardCell:
return self.board[coordinate.y][coordinate.x]
def register_latest_move(game_state: GameState, shot_sequence: List[tuple[int, int]], did_previous_shot_hit: bool):
game_state.board.get_cell(Coordinate.from_hm_style(shot_sequence[-1])).set_checked(did_previous_shot_hit)
def set_probability(board: Board, probability_table: List[List[int]], ship_size: int, x: int, y: int,
inverted: bool = False):
is_possible_placement = True
for i in range(ship_size):
if inverted:
cell = board.get_cell(Coordinate(x, y + i))
else:
cell = board.get_cell(Coordinate(x + i, y))
if cell.checked and (not cell.hit or cell.confirmed_ship):
is_possible_placement = False
break
if is_possible_placement:
for i in range(ship_size):
if inverted:
cell = board.get_cell(Coordinate(x, y + i))
else:
cell = board.get_cell(Coordinate(x + i, y))
if cell.checked:
continue
if inverted:
probability_table[y + i][x] += 1
else:
probability_table[y][x + i] += 1
def get_probability_table(board: Board, ship_sizes_to_check: List[int]) -> List[List[int]]:
probability_table = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
for ship_size in ship_sizes_to_check:
coords_to_check = list(range(BOARD_SIZE - ship_size + 1))
for x in coords_to_check:
for y in range(BOARD_SIZE):
set_probability(board, probability_table, ship_size, x, y)
set_probability(board, probability_table, ship_size, y, x, True)
return probability_table
def adjacent_coords(coordinate: Coordinate, filter_valid: bool = False, x_axis: bool = True, y_axis: bool = True) -> \
List[Coordinate]:
coords = []
if x_axis:
coords += [
Coordinate(coordinate.x - 1, coordinate.y),
Coordinate(coordinate.x + 1, coordinate.y),
]
if y_axis:
coords += [
Coordinate(coordinate.x, coordinate.y - 1),
Coordinate(coordinate.x, coordinate.y + 1),
]
if filter_valid:
coords = [x for x in coords if x.is_valid()]
return coords
def weight_adjacent_cells(probability_table: List[List[int]], board: Board):
coordinate_list = probability_table_to_sorted_coordinate_list(probability_table)
coordinate_list = [x for x in coordinate_list if
board.get_cell(x[0]).hit and not board.get_cell(x[0]).confirmed_ship]
print("weight_adjacent_cells coordinate_list: ", coordinate_list)
for coordinate, _ in coordinate_list:
coords_to_check = adjacent_coords(coordinate, True)
print("coords_to_check: ", coords_to_check)
coords_to_apply_weight_to = [x for x in coords_to_check if
not board.get_cell(x).checked and probability_table[x.y][
x.x] != 0]
print("coords_to_apply_weight_to: ", coords_to_apply_weight_to)
for coord in coords_to_apply_weight_to:
probability_table[coord.y][coord.x] += 20
def probability_table_to_sorted_coordinate_list(probability_table: List[List[int]]) -> List[tuple[Coordinate, int]]:
coordinate_list = []
for y in range(len(probability_table)):
for x in range(len(probability_table[y])):
coordinate_list.append((Coordinate(x, y), probability_table[y][x]))
coordinate_list.sort(key=lambda x: x[1], reverse=True)
return coordinate_list
def get_grouped_coordinates(game_state: GameState, coordinate: Coordinate, axis: Literal["x", "y"],
ignore_list: set[Coordinate] = set()) -> set[Coordinate]:
ret = {coordinate}
adjacent = adjacent_coords(coordinate, True, axis == "x", axis == "y")
# print(adjacent)
adjacent = [x for x in adjacent if x not in ignore_list and game_state.board.get_cell(x).hit]
# print(adjacent)
for coord in adjacent:
ret = ret.union(get_grouped_coordinates(game_state, coord, axis, ret))
return ret
def can_any_ship_fit_with_group(game_state: GameState, group_coords: set[Coordinate], ship_size_to_check: int,
axis: Literal["x", "y"]) -> bool:
group_coords_length = len(group_coords)
sorted_group_coords = list(group_coords)
sorted_group_coords.sort(key=lambda x: x.x if axis == "x" else x.y)
left_bound_space = 0
right_bound_space = 0
left_bound_hit = False
right_bound_hit = False
for i in range(1, ship_size_to_check - group_coords_length + 1):
if axis == "x":
cord = Coordinate(sorted_group_coords[0].x - i, sorted_group_coords[0].y)
if not left_bound_hit and cord.is_valid() and not game_state.board.get_cell(
cord).checked:
left_bound_space += 1
else:
left_bound_hit = True
cord = Coordinate(sorted_group_coords[-1].x + i, sorted_group_coords[0].y)
if not right_bound_hit and cord.is_valid() and not game_state.board.get_cell(
cord).checked:
right_bound_space += 1
else:
right_bound_hit = True
else:
cord = Coordinate(sorted_group_coords[0].x, sorted_group_coords[0].y - i)
if not left_bound_hit and cord.is_valid() and not game_state.board.get_cell(cord).checked:
left_bound_space += 1
else:
left_bound_hit = True
cord = Coordinate(sorted_group_coords[0].x, sorted_group_coords[-1].y + i)
if not right_bound_hit and cord.is_valid() and not game_state.board.get_cell(
cord).checked:
right_bound_space += 1
else:
right_bound_hit = True
return left_bound_space + right_bound_space + group_coords_length >= ship_size_to_check
def get_possible_placements_including(board: Board, ship_size: int, group_coords: set[Coordinate], x: int, y: int,
inverted: bool = False) -> Optional[set[Coordinate]]:
uses_group_coord = False
is_possible_placement = True
cords = set()
for i in range(ship_size):
if inverted:
cord = Coordinate(x, y + i)
else:
cord = Coordinate(x + i, y)
if not uses_group_coord and cord in group_coords:
uses_group_coord = True
cords.add(cord)
cell = board.get_cell(cord)
if cell.checked and (not cell.hit or cell.confirmed_ship):
is_possible_placement = False
break
if is_possible_placement and uses_group_coord and not cords.issubset(group_coords):
return cords
return None
def possible_combination_utilizing_all_group_cells(game_state: GameState, group_coords: set[Coordinate]) -> bool:
placements = []
group_size = len(group_coords)
for ship_size in set(game_state.remaining_ship_sizes):
coords_to_check = list(range(BOARD_SIZE - ship_size + 1))
for x in coords_to_check:
for y in range(BOARD_SIZE):
kill_me1 = get_possible_placements_including(game_state.board, ship_size, group_coords, x, y)
kill_me2 = get_possible_placements_including(game_state.board, ship_size, group_coords, y, x, True)
if kill_me1:
placements.append(kill_me1)
if kill_me2:
placements.append(kill_me2)
combinations = []
for i in range(2, group_size + 1):
combinations += list(itertools.combinations(placements, i))
for combination in combinations:
combination_length = functools.reduce(lambda count, l: count + len(l), combination, 0)
aaa = set.union(*combination)
# xd = len()
if combination_length == len(aaa) and group_coords.issubset(aaa):
print("possible_combination: ", combination)
return True
return False
def confirm_ships(game_state: GameState):
all_coordinates = [Coordinate(x, y) for x in range(BOARD_SIZE) for y in range(BOARD_SIZE)]
hit_coords = [x for x in all_coordinates if
game_state.board.get_cell(x).hit and not game_state.board.get_cell(x).confirmed_ship]
groups: List[tuple[Literal["x", "y"], set[Coordinate]]] = []
skip_coords_x = []
skip_coords_y = []
for coordinate in hit_coords:
if coordinate not in skip_coords_x:
bla = get_grouped_coordinates(game_state, coordinate, "x")
skip_coords_x += list(bla)
groups.append(("x", bla))
if coordinate not in skip_coords_y:
bla = get_grouped_coordinates(game_state, coordinate, "y")
skip_coords_y += list(bla)
groups.append(("y", bla))
groups = [x for x in groups if len(x[1]) > 1]
groups.sort(key=lambda x: len(x[1]), reverse=True)
print("groups: ", groups)
for axis, group in groups:
cond1 = None
try:
min_ship_size = min([x for x in game_state.remaining_ship_sizes if x > len(group)])
except ValueError:
cond1 = True
else:
cond1 = not can_any_ship_fit_with_group(game_state, group,
min_ship_size,
axis)
cond2 = not possible_combination_utilizing_all_group_cells(game_state, group)
print("cond1: ", cond1, " | cond2: ", cond2)
if cond1 and cond2:
print("confirmed ship: ", group)
group_size = len(group)
intersects_with_other_groups = False
for _, other_group in groups:
if len(other_group.intersection(group)) != 0:
intersects_with_other_groups = True
break
print("group ", group, " intersects_with_other_groups: ", intersects_with_other_groups)
# Kinda unlikely to intersect (i think) but just a precautionary so I don't screw the whole thing up lmao
if not intersects_with_other_groups:
if group_size in [2, 3]:
game_state.remaining_ship_sizes.remove(group_size)
if group_size == 4:
game_state.remaining_ship_sizes.remove(2)
game_state.remaining_ship_sizes.remove(2)
if group_size == 5:
game_state.pending_remove_ship_sizes.append(5)
if game_state.remaining_ship_sizes.count(2) == 0 or game_state.remaining_ship_sizes.count(
3) == 0 and 5 in game_state.pending_remove_ship_sizes:
game_state.remaining_ship_sizes.remove(5)
for coord in group:
game_state.board.get_cell(coord).confirmed_ship = True
confirm_ships(game_state)
break
def get_next_move(game_state: GameState) -> Coordinate:
try:
confirm_ships(game_state)
except Exception() as e:
print("confirm_ships error: ", e)
probability_table = get_probability_table(game_state.board, game_state.remaining_ship_sizes)
weight_adjacent_cells(probability_table, game_state.board)
coordinate_list = probability_table_to_sorted_coordinate_list(probability_table)
print(coordinate_list)
print("remaining_ship_sizes: ", game_state.remaining_ship_sizes)
return coordinate_list[0][0]
def ShipLogic(round_number: int, ship_map, enemy_hp: int, hp: int, # Why not snake_case? :(
shot_sequence: List[tuple[int, int]],
did_previous_shot_hit: bool, storage: List) -> tuple[tuple[int, int], List]:
try:
game_state = None
if len(storage) > 0 and storage[0] is not None:
game_state = storage[0]
else:
game_state = GameState()
storage.append(game_state)
if len(shot_sequence) > 0:
register_latest_move(game_state, shot_sequence, did_previous_shot_hit)
move = get_next_move(game_state)
return move.to_hm_style(), storage
except Exception:
return (1, 1), storage # Will prompt a random move if an unexpected error occurs
def main():
game_state = GameState()
while True:
move = get_next_move(game_state)
print(f"\u001b[31m-> {move}\u001b[0m")
user_input = input("Hit (h) / Miss (m) / Quit (q): ")
was_hit = None
match user_input.strip().lower():
case "h":
was_hit = True
case "m":
was_hit = False
case "q":
exit(0)
case other:
print(f"{other} not recognised, please try again.")
continue
game_state.board.get_cell(move).set_checked(was_hit)
if __name__ == "__main__":
main()