From 822d81677aecfde7c005bacc2fa4a06431c813e6 Mon Sep 17 00:00:00 2001 From: Administrator Date: Tue, 23 Aug 2022 23:45:40 +0300 Subject: [PATCH] check field correct --- battleship/utils.py | 42 +++++++++++++++++++++++++++++++++++++++++ battleship/views.py | 6 ++++++ battleship_back/urls.py | 3 ++- 3 files changed, 50 insertions(+), 1 deletion(-) diff --git a/battleship/utils.py b/battleship/utils.py index 3911257..69574a9 100644 --- a/battleship/utils.py +++ b/battleship/utils.py @@ -1,3 +1,37 @@ +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 @@ -27,6 +61,10 @@ def check_field(field): 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 @@ -44,6 +82,10 @@ def check_field(field): 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 diff --git a/battleship/views.py b/battleship/views.py index 854abc6..a6c019e 100644 --- a/battleship/views.py +++ b/battleship/views.py @@ -104,3 +104,9 @@ def check_status(request): 'my_turn': player.game.turn == player.number, 'game_finished': 'o' not in player.field or 'o' not in player2.field }) + + +def check_field_correct(request): + return JsonResponse({ + 'correct': check_field(request.POST['field']) + }) diff --git a/battleship_back/urls.py b/battleship_back/urls.py index d8ca9e0..db009bd 100644 --- a/battleship_back/urls.py +++ b/battleship_back/urls.py @@ -25,5 +25,6 @@ urlpatterns = [ path('api/check_opponent', views.check_opponent), path('api/attend_game', views.attend_game), path('api/place_ships', views.place_ships), - path('api/shoot', views.shoot) + path('api/shoot', views.shoot), + path('api/check_field_correct', views.check_field_correct) ]