загружаю первый вариант дз

This commit is contained in:
ehermakov 2024-02-11 21:01:06 +03:00
parent 23fd823e50
commit 0210d7f31e
4 changed files with 71 additions and 2 deletions

View File

@ -1 +1 @@
main.py ShipField.py

View File

@ -2,7 +2,6 @@ from main import ShootResult
class ShipField: class ShipField:
field = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', field = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
@ -55,3 +54,65 @@ class ShipField:
return ShootResult.DAMAGED return ShootResult.DAMAGED
else: else:
return ShootResult.UNDEFINED return ShootResult.UNDEFINED
def check_possible(self, row, col, ship_size, ship_direction):
# Функция должна возвращать True, если можно поставить сюда корабль,
# в противном случае - False
if self.ship_direction == 0:
# Здесь мы знаем, что корабль помещается на поле.
if self.field_size - row >= self.ship_size:
# Теперь нужно проверить, не заблокировано ли какое-то из полей,
for r in range(row, row + self.ship_size):
if not self.check_blocked(self, r, col):
return False
return True
if ship_direction == 1:
if self.field_size - col >= self.ship_size:
for c in range(col, col + self.ship_size):
if not self.check_blocked(self, row, c):
return False
return True
return False
def check_blocked(self, row, col):
# Функция возвращает True, если все клетки вокруг клетки с координатами row, col
# либо находятся за пределами поля, либо в них нет корабля/они пустые
for r in range(row - 1, row + 2):
for c in range(col - 1, col + 2):
if 0 <= r < self.field_size and 0 <= c < self.field_size:
cell = (self.field[r * self.field_size + c]).strip()
if cell != '' and cell != 'p':
return False
return True
def set_ship_size(self, value):
if value.isnumeric():
number = int(value)
if 1 <= number <= 4:
self.ship_size = number
def set_ship_direction(self, value):
if value.isnumeric() == 0 or value.isnumeric() == 1:
self.ship_direction = value
def toggle_field_mode(self):
if self.field_mode == 0:
self.field_mode = 1
else:
self.field_mode = 0
def print_field(self):
for r in range(0, self.field_size):
blocked_string = ""
ship_string = ""
for c in range(0, self.field_size):
blocked_string += str(self.check_blocked(self, r, c))[0] + ", "
ship_string += self.field[r * self.field_size + c] + ', '
print(blocked_string[:-2] + ' ' + ship_string[:-2])
print("********************************************************************")

View File

@ -0,0 +1,8 @@
from main import ShootResult
from ShipField import ShipField
ship_field = ShipField()
ship_field.set_ship_size(3)
ship_field.set_ship_direction(0)
ship_field.set_ship(1, 1)
ship_field.print_field()