This commit is contained in:
Administrator 2022-08-28 18:57:17 +03:00
parent 542ddb282d
commit a475f6c68f
2 changed files with 53 additions and 6 deletions

View File

@ -95,3 +95,49 @@ def check_field(field):
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] == '+':
ship.append((x - 1, y))
queue.append((x - 1, y))
if x < 9:
if cells[x + 1][y] == 'o':
killed = False
break
elif cells[x + 1][y] == '+':
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] == '+':
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] == '+':
ship.append((x, y + 1))
queue.append((x, y + 1))
if killed:
for x, y in ship:
cells[x][y] = 'x'
return ''.join([''.join(arr) for arr in cells])

View File

@ -6,7 +6,7 @@ from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from battleship.models import Game, Player
from battleship.utils import check_field
from battleship.utils import check_field, kill_field
@csrf_exempt
@ -92,21 +92,22 @@ def shoot(request):
h = data['h']
v = data['v']
pos = h * 10 + v
if player2.field[pos] == 'x' or player2.field[pos] == '.':
if player2.field[pos] == 'x' or player2.field[pos] == '.' or player2.field[pos] == '+':
return JsonResponse({}, status=403)
if player2.field[pos] == 'o':
new_symb = 'x'
new_symb = '+'
else:
new_symb = '.'
player.game.turn = (1 - player.game.turn)
player.game.last_move_ts = timezone.now()
player.game.save()
player.game.turn = (1 - player.game.turn)
player.game.last_move_ts = timezone.now()
player.game.save()
if pos == 0:
player2.field = new_symb + player2.field[1:]
elif pos == 99:
player2.field = player2.field[:99] + new_symb
else:
player2.field = player2.field[:pos] + new_symb + player2.field[pos + 1:]
player2.field = kill_field(player2.field)
player2.save()
game_finish = 'o' not in player2.field
if game_finish: