def __init__(self, position, move): resulting_position = position.copy().make_move(move) captured = position._pieces[move.target._x88] piece = position._pieces[move.source._x88] ocolor = Piece.opposite_color(position.fen._to_move) # Pawn moves. enpassant = False if Piece.klass(piece) == PAWN: # En-passant. if move.target.file != move.source.file and not captured: enpassant = True captured = Piece.from_klass_and_color(PAWN, ocolor) # Castling. # TODO: Support Chess960. # TODO: Validate the castling move. if Piece.klass(piece) == KING: self.is_king_side_castle = move.target.x - move.source.x == 2 self.is_queen_side_castle = move.target.x - move.source.x == -2 else: self.is_king_side_castle = self.is_queen_side_castle = False # Checks. self.is_check = resulting_position.is_check() self.is_checkmate = resulting_position.is_checkmate() self.move = move self.piece = piece self.captured = captured self.is_enpassant = enpassant self._set_text(position)
def __init__(self, position, move): resulting_position = position.copy().make_move(move) captured = position._pieces[move.target._x88] piece = position._pieces[move.source._x88] ocolor = Piece.opposite_color(position.fen._to_move) # Pawn moves. enpassant = False if Piece.klass(piece) == PAWN: # En-passant. if move.target.file != move.source.file and not captured: enpassant = True captured = Piece.from_klass_and_color(PAWN, ocolor) # Castling. # TODO: Support Chess960. # TODO: Validate the castling move. if Piece.klass(piece) == KING: self.is_king_side_castle = move.target.x - move.source.x == 2 self.is_queen_side_castle = move.target.x - move.source.x == -2 else: self.is_king_side_castle = self.is_queen_side_castle = False # Checks. self.is_check = resulting_position.is_check() self.is_checkmate = resulting_position.is_checkmate() self.move = move self.piece = piece self.captured = captured self.is_enpassant = enpassant self._set_text(position)
def get_piece_counts(self, colors=[WHITE, BLACK]): """Counts the pieces on the board. :param color: list of colors to check. Defualts to black and white :return: A dictionary of piece counts, keyed by lowercase piece type letters. """ #if not color in ["w", "b", "wb", "bw"]: # raise KeyError( # "Expected color filter to be one of 'w', 'b', 'wb', 'bw', " # "got: %s." % repr(color)) counts = { PAWN: 0, BISHOP: 0, KNIGHT: 0, ROOK: 0, KING: 0, QUEEN: 0, } for piece in self._pieces: if piece and Piece.color(piece) in colors: counts[Piece.klass(piece)] += 1 return counts
def get_piece_counts(self, colors=[WHITE, BLACK]): """Counts the pieces on the board. :param color: list of colors to check. Defualts to black and white :return: A dictionary of piece counts, keyed by lowercase piece type letters. """ #if not color in ["w", "b", "wb", "bw"]: # raise KeyError( # "Expected color filter to be one of 'w', 'b', 'wb', 'bw', " # "got: %s." % repr(color)) counts = { PAWN: 0, BISHOP: 0, KNIGHT: 0, ROOK: 0, KING: 0, QUEEN: 0, } for piece in self._pieces: if piece and Piece.color(piece) in colors: counts[Piece.klass(piece)] += 1 return counts
def get_attackers(self, color, square): """Gets the attackers of a specific square. :param color: Filter attackers by this piece color. :param square: The square to check for. :yield: Source squares of the attack. """ if not color in [BLACK, WHITE]: raise KeyError("Invalid color: %s." % repr(color)) for x88, source in Square._x88_squares.iteritems(): piece = self._pieces[x88] if not piece or Piece.color(piece) != color: continue difference = x88 - square._x88 index = difference + X88.ATTACKER_DIFF klass = Piece.klass(piece) if X88.ATTACKS[index] & (1 << X88.SHIFTS[klass]): # Handle pawns. if klass == PAWN: if difference > 0: if Piece.color(piece) == WHITE: yield source else: if Piece.color(piece) == BLACK: yield source continue # Handle knights and king. if klass in [KNIGHT, KING]: yield source # Handle the others. offset = X88.RAYS[index] j = source._x88 + offset blocked = False while j != square._x88: if self._pieces[j]: blocked = True break j += offset if not blocked: yield source
def get_attackers(self, color, square): """Gets the attackers of a specific square. :param color: Filter attackers by this piece color. :param square: The square to check for. :yield: Source squares of the attack. """ if not color in [BLACK, WHITE]: raise KeyError("Invalid color: %s." % repr(color)) for x88, source in Square._x88_squares.iteritems(): piece = self._pieces[x88] if not piece or Piece.color(piece) != color: continue difference = x88 - square._x88 index = difference + X88.ATTACKER_DIFF klass = Piece.klass(piece) if X88.ATTACKS[index] & (1 << X88.SHIFTS[klass]): # Handle pawns. if klass == PAWN: if difference > 0: if Piece.color(piece) == WHITE: yield source else: if Piece.color(piece) == BLACK: yield source continue # Handle knights and king. if klass in [KNIGHT, KING]: yield source # Handle the others. offset = X88.RAYS[index] j = source._x88 + offset blocked = False while j != square._x88: if self._pieces[j]: blocked = True break j += offset if not blocked: yield source
def to_move(cls, position, san): san = str(san) # Castling moves. if san == "O-O" or san == "O-O-O": # TODO: Support Chess960, check the castling moves are valid. rank = 1 if position.fen.turn == "w" else 8 if san == "O-O": return Move( source=Square.from_rank_and_file(rank, 'e'), target=Square.from_rank_and_file(rank, 'g')) else: return Move( source=Square.from_rank_and_file(rank, 'e'), target=Square.from_rank_and_file(rank, 'c')) # Regular moves. else: matches = cls.san_regex.match(san) if not matches: raise ValueError("Invalid SAN: %s." % repr(san)) if matches.group(1): klass = Piece.klass(matches.group(1).lower()) else: klass = PAWN piece = Piece.from_klass_and_color(klass, position.fen._to_move) target = Square(matches.group(4)) source = None for m in position.get_legal_moves(): if position._pieces[m.source._x88] != piece or m.target != target: continue if matches.group(2) and matches.group(2) != m.source.file: continue if matches.group(3) and matches.group(3) != str(m.source.rank): continue # Move matches. Assert it is not ambiguous. if source: raise MoveError( "Move is ambiguous: %s matches %s and %s." % san, source, m) source = m.source if not source: raise MoveError("No legal move matches %s." % san) return Move(source, target, matches.group(5) or None)
def to_move(cls, position, san): san = str(san) # Castling moves. if san == "O-O" or san == "O-O-O": # TODO: Support Chess960, check the castling moves are valid. rank = 1 if position.fen.turn == "w" else 8 if san == "O-O": return Move(source=Square.from_rank_and_file(rank, 'e'), target=Square.from_rank_and_file(rank, 'g')) else: return Move(source=Square.from_rank_and_file(rank, 'e'), target=Square.from_rank_and_file(rank, 'c')) # Regular moves. else: matches = cls.san_regex.match(san) if not matches: raise ValueError("Invalid SAN: %s." % repr(san)) if matches.group(1): klass = Piece.klass(matches.group(1).lower()) else: klass = PAWN piece = Piece.from_klass_and_color(klass, position.fen._to_move) target = Square(matches.group(4)) source = None for m in position.get_legal_moves(): if position._pieces[ m.source._x88] != piece or m.target != target: continue if matches.group(2) and matches.group(2) != m.source.file: continue if matches.group(3) and matches.group(3) != str(m.source.rank): continue # Move matches. Assert it is not ambiguous. if source: raise MoveError( "Move is ambiguous: %s matches %s and %s." % san, source, m) source = m.source if not source: raise MoveError("No legal move matches %s." % san) return Move(source, target, matches.group(5) or None)
def is_insufficient_material(self): """Checks if there is sufficient material to mate. Mating is impossible in: * A king versus king endgame. * A king with bishop versus king endgame. * A king with knight versus king endgame. * A king with bishop versus king with bishop endgame, where both bishops are on the same color. Same goes for additional bishops on the same color. Assumes that the position is valid and each player has exactly one king. :return: Whether there is insufficient material to mate. """ piece_counts = self.get_piece_counts() # King versus king. if sum(piece_counts.values()) == 2: return True # King and knight or bishop versus king. elif sum(piece_counts.values()) == 3: if piece_counts["b"] == 1 or piece_counts["n"] == 1: return True # Each player with only king and any number of bishops, # where all bishops are on the same color. elif sum(piece_counts.values()) == 2 + piece_counts[BISHOP]: white_has_bishop = self.get_piece_counts([WHITE])[BISHOP] != 0 black_has_bishop = self.get_piece_counts([BLACK])[BISHOP] != 0 if white_has_bishop and black_has_bishop: color = None for square in Square.get_all(): p = self._pieces[square._x88] if p and Piece.klass(p) == BISHOP: if color and color != square.is_light(): return False color = square.is_light() return True return False
def is_insufficient_material(self): """Checks if there is sufficient material to mate. Mating is impossible in: * A king versus king endgame. * A king with bishop versus king endgame. * A king with knight versus king endgame. * A king with bishop versus king with bishop endgame, where both bishops are on the same color. Same goes for additional bishops on the same color. Assumes that the position is valid and each player has exactly one king. :return: Whether there is insufficient material to mate. """ piece_counts = self.get_piece_counts() # King versus king. if sum(piece_counts.values()) == 2: return True # King and knight or bishop versus king. elif sum(piece_counts.values()) == 3: if piece_counts["b"] == 1 or piece_counts["n"] == 1: return True # Each player with only king and any number of bishops, # where all bishops are on the same color. elif sum(piece_counts.values()) == 2 + piece_counts[BISHOP]: white_has_bishop = self.get_piece_counts([WHITE])[BISHOP] != 0 black_has_bishop = self.get_piece_counts([BLACK])[BISHOP] != 0 if white_has_bishop and black_has_bishop: color = None for square in Square.get_all(): p = self._pieces[square._x88] if p and Piece.klass(p) == BISHOP: if color and color != square.is_light(): return False color = square.is_light() return True return False
def _set_text(self, position): move = self.move piece_klass = Piece.klass(self.piece) # Generate the SAN. san = "" if self.is_king_side_castle: san += "O-O" elif self.is_queen_side_castle: san += "O-O-O" else: if piece_klass != PAWN: san += Piece.from_klass_and_color(piece_klass, WHITE) if position: san += self._get_disambiguator(move, position) if self.captured: if piece_klass == PAWN: san += move.source.file san += "x" san += move.target.name if move.promotion: san += "=" san += move.promotion.upper() if self.is_checkmate: san += "#" elif self.is_check: san += "+" if self.is_enpassant: san += " (e.p.)" self._text = san
def _set_text(self, position): move = self.move piece_klass = Piece.klass(self.piece) # Generate the SAN. san = "" if self.is_king_side_castle: san += "O-O" elif self.is_queen_side_castle: san += "O-O-O" else: if piece_klass != PAWN: san += Piece.from_klass_and_color(piece_klass, WHITE) if position: san += self._get_disambiguator(move, position) if self.captured: if piece_klass == PAWN: san += move.source.file san += "x" san += move.target.name if move.promotion: san += "=" san += move.promotion.upper() if self.is_checkmate: san += "#" elif self.is_check: san += "+" if self.is_enpassant: san += " (e.p.)" self._text = san
def test_klass(self): self.assertEqual(piece.PAWN, Piece.klass('P'))
def make_move(self, move, validate=True): """Makes a move. :param move: The move to make. :param validate: Defaults to `True`. Whether the move should be validated. :return: Making a move changes the position object. The same (changed) object is returned for chainability. :raise MoveError: If the validate parameter is `True` and the move is not legal in the position. """ #if validate: if validate: if move not in self.get_legal_moves(source=move.source): raise MoveError( "%s is not a legal move in the position %s." % (move, self.fen)) piece = self._pieces[move._source_x88] capture = self._pieces[move._target_x88] target = move.target source = move.source # Move the piece. self._pieces[move._target_x88] = piece self._pieces[move._source_x88] = None # It is the next players turn. ocolor = Piece.opposite_color(self.fen._to_move) self.fen._to_move = ocolor # Pawn moves. self._ep = None if Piece.klass(piece) == PAWN: # En-passant. if target.x != source.x and not capture: offset = 16 if self.fen._to_move == WHITE else -16 self._pieces[target.x88() + offset] = None capture = True # If big pawn move, set the en-passant file. if abs(target.y - source.y) == 2: if self.get_theoretical_ep_right(target.x): self._ep = move.target # Promotion. if move.promotion: self._pieces[move.target._x88] = move.promotion # Potential castling. if Piece.klass(piece) == KING: steps = move.target.x - move.source.x if abs(steps) == 2: # Queen-side castling. if steps == -2: rook_target = move.target.x88 + 1 rook_source = move.target.x88 - 2 # King-side castling. else: rook_target = move.target.x88 - 1 rook_source = move.target.x88 + 1 self._pieces[rook_target] = self._pieces[rook_source] self._pieces[rook_source] = None # Update castling rights. for klass in self.fen._castle_rights: if not self.get_theoretical_castling_right(klass): self.fen._castle_rights.remove(klass) # XXX Castling rights can only be removed #self.set_castling_right(klass, False) # Increment the 50 move half move counter. if Piece.klass(piece) == PAWN or capture: self.fen._fifty_move = 0 else: self.fen._fifty_move += 1 # Increment the move number. if self.fen._to_move == WHITE: self.fen._full_move += 1 return self
def get_pseudo_legal_moves(self, source=None): """:yield: Pseudo legal moves in the current position. :param source: The source square to limit moves or None for all possible moves. """ tomove = self.fen._to_move for x88 in [ x88 for x88 in Square._x88_squares.keys() if self._pieces[x88] and Piece.color(self._pieces[x88]) == tomove and (source is None or x88 == source._x88) ]: piece = self._pieces[x88] klass = Piece.klass(piece) # pawn moves if klass == PAWN: single, double, capleft, capright = X88.PAWN_OFFSETS[tomove] # Single square ahead. Do not capture. offset = x88 + single if not self._pieces[offset]: # Promotion. if X88.is_backrank(offset, tomove): for promote_to in Piece.promote_to: yield Move.from_x88(x88, offset, promote_to) else: yield Move.from_x88(x88, offset) # Two squares ahead. Do not capture. if X88.is_secondrank(x88, tomove): offset = x88 + double if not self._pieces[offset]: yield Move.from_x88(x88, offset) # Pawn captures. for cap in [capleft, capright]: offset = x88 + cap if offset & X88.X88: continue target = self._pieces[offset] if target and Piece.color(target) != tomove: # Promotion. if X88.is_backrank(offset, tomove): for promote_to in Piece.promote_to: yield Move.from_x88(x88, offset, promote_to) else: yield Move.from_x88(x88, offset) # En-passant. elif not target and offset == self.fen._ep: yield Move.from_x88(target, self.fen._ep) #piece moves else: # for each a direction a piece moves in for offset in X88.PIECE_OFFSETS[Piece.klass(piece)]: t_x88 = x88 + offset # while we do not fall off the board while not t_x88 & 0x88: # if there was not piece to attack then yield a quiet move if not self._pieces[t_x88]: yield Move.from_x88(x88, t_x88) # do not break out # else there is a piece there else: # if we can attack generate a move if Piece.color(self._pieces[t_x88]) != tomove: yield Move.from_x88(x88, t_x88) # we hit something so break out break # Knight and king do not go multiple times in their direction. if klass in [KNIGHT, KING]: break # travel down the board in the direction t_x88 += offset # castling moves opponent = Piece.opposite_color(tomove) ok = True # get possible castling for the side to move for castle in [ c for c in self.fen._castle_rights if Piece.color(c) == tomove ]: (square, enum), _ = Piece.castle_squares[castle] king = Square(square) if Piece.klass(castle) == KING: direc = 1 else: direc = -1 # for offset in the squares the king will travel for offset in range(0, 3): s = Square.from_x88(king._x88 + (offset * direc)) # if we are not the king square and we are occuppied if offset and self._pieces[s._x88]: ok = False break # if we are trying to travel through check if self.is_attacked(opponent, s): ok = False break # kludge: we have to check occupancy for one more square on the queen side if direc == -1 and self._pieces[s._x88 - 1]: ok = False if ok: yield Move(king, s)
def get_pseudo_legal_moves(self, source=None): """:yield: Pseudo legal moves in the current position. :param source: The source square to limit moves or None for all possible moves. """ tomove = self.fen._to_move for x88 in [ x88 for x88 in Square._x88_squares.keys() if self._pieces[x88] and Piece.color(self._pieces[x88]) == tomove and (source is None or x88 == source._x88)]: piece = self._pieces[x88] klass = Piece.klass(piece) # pawn moves if klass == PAWN: single, double, capleft, capright = X88.PAWN_OFFSETS[tomove] # Single square ahead. Do not capture. offset = x88 + single if not self._pieces[offset]: # Promotion. if X88.is_backrank(offset, tomove): for promote_to in Piece.promote_to: yield Move.from_x88(x88, offset, promote_to) else: yield Move.from_x88(x88, offset) # Two squares ahead. Do not capture. if X88.is_secondrank(x88, tomove): offset = x88 + double if not self._pieces[offset]: yield Move.from_x88(x88, offset) # Pawn captures. for cap in [capleft, capright]: offset = x88 + cap if offset & X88.X88: continue target = self._pieces[offset] if target and Piece.color(target) != tomove: # Promotion. if X88.is_backrank(offset, tomove): for promote_to in Piece.promote_to: yield Move.from_x88(x88, offset, promote_to) else: yield Move.from_x88(x88, offset) # En-passant. elif not target and offset == self.fen._ep: yield Move.from_x88(target, self.fen._ep) #piece moves else: # for each a direction a piece moves in for offset in X88.PIECE_OFFSETS[Piece.klass(piece)]: t_x88 = x88 + offset # while we do not fall off the board while not t_x88 & 0x88: # if there was not piece to attack then yield a quiet move if not self._pieces[t_x88]: yield Move.from_x88(x88, t_x88) # do not break out # else there is a piece there else: # if we can attack generate a move if Piece.color(self._pieces[t_x88]) != tomove: yield Move.from_x88(x88, t_x88) # we hit something so break out break # Knight and king do not go multiple times in their direction. if klass in [KNIGHT, KING]: break # travel down the board in the direction t_x88 += offset # castling moves opponent = Piece.opposite_color(tomove) ok = True # get possible castling for the side to move for castle in [c for c in self.fen._castle_rights if Piece.color(c) == tomove]: (square, enum), _ = Piece.castle_squares[castle] king = Square(square) if Piece.klass(castle) == KING: direc = 1 else: direc = -1 # for offset in the squares the king will travel for offset in range(0, 3): s = Square.from_x88(king._x88 + (offset * direc)) # if we are not the king square and we are occuppied if offset and self._pieces[s._x88]: ok = False break # if we are trying to travel through check if self.is_attacked(opponent, s): ok = False break # kludge: we have to check occupancy for one more square on the queen side if direc == -1 and self._pieces[s._x88 - 1]: ok = False if ok: yield Move(king, s)
def make_move(self, move, validate=True): """Makes a move. :param move: The move to make. :param validate: Defaults to `True`. Whether the move should be validated. :return: Making a move changes the position object. The same (changed) object is returned for chainability. :raise MoveError: If the validate parameter is `True` and the move is not legal in the position. """ #if validate: if validate: if move not in self.get_legal_moves(source=move.source): raise MoveError("%s is not a legal move in the position %s." % (move, self.fen)) piece = self._pieces[move._source_x88] capture = self._pieces[move._target_x88] target = move.target source = move.source # Move the piece. self._pieces[move._target_x88] = piece self._pieces[move._source_x88] = None # It is the next players turn. ocolor = Piece.opposite_color(self.fen._to_move) self.fen._to_move = ocolor # Pawn moves. self._ep = None if Piece.klass(piece) == PAWN: # En-passant. if target.x != source.x and not capture: offset = 16 if self.fen._to_move == WHITE else -16 self._pieces[target.x88() + offset] = None capture = True # If big pawn move, set the en-passant file. if abs(target.y - source.y) == 2: if self.get_theoretical_ep_right(target.x): self._ep = move.target # Promotion. if move.promotion: self._pieces[move.target._x88] = move.promotion # Potential castling. if Piece.klass(piece) == KING: steps = move.target.x - move.source.x if abs(steps) == 2: # Queen-side castling. if steps == -2: rook_target = move.target.x88 + 1 rook_source = move.target.x88 - 2 # King-side castling. else: rook_target = move.target.x88 - 1 rook_source = move.target.x88 + 1 self._pieces[rook_target] = self._pieces[rook_source] self._pieces[rook_source] = None # Update castling rights. for klass in self.fen._castle_rights: if not self.get_theoretical_castling_right(klass): self.fen._castle_rights.remove(klass) # XXX Castling rights can only be removed #self.set_castling_right(klass, False) # Increment the 50 move half move counter. if Piece.klass(piece) == PAWN or capture: self.fen._fifty_move = 0 else: self.fen._fifty_move += 1 # Increment the move number. if self.fen._to_move == WHITE: self.fen._full_move += 1 return self