Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
OOP solution in Clear category for Pawn Brotherhood by TrangOul
import dataclasses
import abc
import enum
_COLS = 'abcdefgh'
_COL_SYMBOL_TO_INDEX = {ch : _COLS.index(ch)+ 1 for ch in _COLS}
_COL_INDEX_TO_SYMBOL = {v : k for k, v in _COL_SYMBOL_TO_INDEX.items()}
#We'll define a class to handle positions (by index instead of by chess notation).
@dataclasses.dataclass(frozen=True)
class Position:
col: int
row: int
#We'll define an enum to store possible sides (colors).
class Color(enum.Enum):
WHITE = enum.auto()
BLACK = enum.auto()
class Piece(metaclass=abc.ABCMeta):
def __init__(self, color:Color, pos:str):
self.color = color
col, row = pos
self.pos = Position(_COL_SYMBOL_TO_INDEX[col], int(row))
@property
@abc.abstractmethod
def attack(self) -> set[Position]:
'''
Return fields attacked by this piece.
'''
pass
@property
def col(self) -> int:
return self.pos.col
@property
def row(self) -> int:
return self.pos.row
class Pawn(Piece):
@property
def attack(self) -> set[Position]:
'''
Return fields attacked by this piece.
'''
if self.color == Color.WHITE:
return {Position(self.col - 1, self.row + 1), Position(self.col + 1, self.row + 1)}
def safe_pawns(pawns: set[str]) -> int:
pawns = {Pawn(Color.WHITE, p) for p in pawns} #color is fixed for this challenge
def is_safe(pawn:Pawn, pawns:set[Pawn]) -> bool:
return any(pawn.pos in p.attack for p in pawns)
return sum(is_safe(p, pawns) for p in pawns)
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert safe_pawns({"b4", "d4", "f4", "c3", "e3", "g5", "d2"}) == 6
assert safe_pawns({"b4", "c4", "d4", "e4", "f4", "g4", "e5"}) == 1
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
Nov. 23, 2021