def find_borders(x, y, p, horizontal): if horizontal: borders = [ (x - 1, y - 1), (x, y - 1), (x + 1, y - 1), (x - 1, y + p), (x, y + p), (x + 1, y + p) ] for i in range(p): borders.extend([ (x - 1, y + i), (x + 1, y + i) ]) else: borders = [ (x - 1, y - 1), (x - 1, y), (x - 1, y + 1), (x + p, y - 1), (x + p, y), (x + p, y + 1) ] for i in range(p): borders.extend([ (x + i, y - 1), (x + i, y + 1) ]) for a, b in borders: if 0 <= a <= 9 and 0 <= b <= 9: yield a, b def check_field(field): if field.count('o') != 20: return False cells = list(field) cells = [cells[x * 10: (x + 1) * 10] for x in range(0, 10)] ships = [1, 1, 1, 1, 2, 2, 2, 3, 3, 4] while ships: found = False for i in range(10): for j in range(10): if cells[i][j] == 'o': i1, j1 = i, j if j1 == 9 or cells[i1][j1 + 1] == ' ': # если вертикальный if i1 == 9 or cells[i1 + 1][j1] == ' ': # если 1 палуба p = 1 elif i1 + 1 == 9 or cells[i1 + 2][j1] == ' ': # если 2 палубы p = 2 elif i1 + 2 == 9 or cells[i1 + 3][j1] == ' ': # если 3 палубы p = 3 elif i1 + 3 != 9 and cells[i1 + 4][j1] == 'o': return False else: p = 4 if p in ships: ships.remove(p) else: return False for k in range(p): cells[i1 + k][j1] = ' ' borders = find_borders(i1, j1, p, False) for x, y in borders: if cells[x][y] == 'o': return False else: if j1 == 9 or cells[i1][j1 + 1] == ' ': # если 1 палуба p = 1 elif j1 + 1 == 9 or cells[i1][j1 + 2] == ' ': # если 2 палубы p = 2 elif j1 + 2 == 9 or cells[i1][j1 + 3] == ' ': # если 3 палубы p = 3 elif j1 + 3 != 9 and cells[i1][j1 + 4] == 'o': return False else: p = 4 if p in ships: ships.remove(p) else: return False for k in range(p): cells[i1][j1 + k] = ' ' borders = find_borders(i1, j1, p, True) for x, y in borders: if cells[x][y] == 'o': return False found = True if found: break if found: break if not found: return False return True def kill_field(field): cells = list(field) cells = [cells[x * 10: (x + 1) * 10] for x in range(0, 10)] for i in range(10): for j in range(10): if cells[i][j] == '+': ship = [(i, j)] queue = [(i, j)] killed = True while queue: x, y = queue[0] queue = queue[1:] if x > 0: if cells[x - 1][y] == 'o': killed = False break elif cells[x - 1][y] == '+': if (x - 1, y) not in ship: queue.append((x - 1, y)) ship.append((x - 1, y)) if x < 9: if cells[x + 1][y] == 'o': killed = False break elif cells[x + 1][y] == '+': if (x + 1, y) not in ship: ship.append((x + 1, y)) queue.append((x + 1, y)) if y > 0: if cells[x][y - 1] == 'o': killed = False break elif cells[x][y - 1] == '+': if (x, y - 1) not in ship: ship.append((x, y - 1)) queue.append((x, y - 1)) if y < 9: if cells[x][y + 1] == 'o': killed = False break elif cells[x][y + 1] == '+': if (x, y + 1) not in ship: ship.append((x, y + 1)) queue.append((x, y + 1)) if killed: for x, y in ship: cells[x][y] = 'x' for x, y in find_borders(ship[0][0], ship[0][1], len(ship), bool(ship[-1][1] - ship[0][1])): cells[x][y] = '.' return ''.join([''.join(arr) for arr in cells])