battleship-back/battleship/utils.py
2022-08-23 23:45:40 +03:00

98 lines
3.5 KiB
Python

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