How to use the chess.Piece function in chess

To help you get started, we’ve selected a few chess examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github SamRagusa / Batch-First / code_testing.py View on Github external
        lambda p: piece_to_filter_fn(chess.Piece(p.piece_type, not p.color) if p else None),
        piece_to_filter_fn]
github niklasf / python-chess / tests / test_position.py View on Github external
def test_get_set(self):
        """Tests the get and set methods."""
        pos = chess.Position()
        self.assertEqual(pos["b1"], chess.Piece("N"))

        del pos["e2"]
        self.assertEqual(pos[chess.Square("e2")], None)

        pos[chess.Square("e4")] = chess.Piece("r")
        self.assertEqual(pos["e4"], chess.Piece("r"))
github niklasf / python-chess / tests / test_piece.py View on Github external
def test_equality(self):
        """Tests the overriden equality behavior of the Piece class."""
        a = chess.Piece.from_color_and_type("w", "b")
        b = chess.Piece.from_color_and_type("b", "k")
        c = chess.Piece.from_color_and_type("w", "k")
        d = chess.Piece.from_color_and_type("w", "b")

        self.assertEqual(a, d)
        self.assertEqual(d, a)

        self.assertEqual(repr(a), repr(d))

        self.assertNotEqual(a, b)
        self.assertNotEqual(b, c)
        self.assertNotEqual(b, d)
        self.assertNotEqual(a, c)

        self.assertNotEqual(a, None)
        self.assertFalse(a == None)
github BarakOshri / ConvChess / src / util.py View on Github external
def convert_image_to_bitboard(im):
	board = chess.Bitboard()
	board.clear()
	for i in xrange(BOARD_SIZE[0]):
		for j in xrange(BOARD_SIZE[1]):
			index_piece = np.where(im[(i,j)] != 0)
			index_piece = index_piece[0]
			new_coords = flatten_coord2d((7 - i, j))
			if index_piece.shape != (0,):
				piece = INDEX_TO_PIECE[index_piece[0]]
				if im[(i,j,index_piece[0])] == -1:
					piece = piece.lower()
				board.set_piece_at(new_coords, chess.Piece.from_symbol(piece))

	return board
github niklasf / python-chess / chess / position.py View on Github external
rank=4 if self.turn == "b" else 5, file=file)
        opposite_color_pawn = chess.Piece.from_color_and_type(
            color=chess.opposite_color(self.turn), type="p")
        if self[pawn_square] != opposite_color_pawn:
            return False

        # Check the square below is empty.
        square_below = chess.Square.from_rank_and_file(
            rank=3 if self.turn == "b" else 6, file=file)
        if self[square_below]:
            return False

        # Check there is a pawn of the other color on a neighbor file.
        f = ord(file) - ord("a")
        p = chess.Piece("p")
        P = chess.Piece("P")
        if self.turn == "b":
            if f > 0 and self[chess.Square.from_x_and_y(f - 1, 3)] == p:
                return True
            elif f < 7 and self[chess.Square.from_x_and_y(f + 1, 3)] == p:
                return True
        else:
            if f > 0 and self[chess.Square.from_x_and_y(f - 1, 4)] == P:
                return True
            elif f < 7 and self[chess.Square.from_x_and_y(f + 1, 4)] == P:
                return True
        return False
github niklasf / python-chess / chess / position.py View on Github external
have that castling right.
        """
        if not type in ["K", "Q", "k", "q"]:
            raise KeyError(
                "Expected 'K', 'Q', 'k' or 'q' as a castling type, got: %s."
                    % repr(type))
        # TODO: Support Chess960.
        if type == "K" or type == "Q":
            if self["e1"] != chess.Piece("K"):
                return False
            if type == "K":
                return self["h1"] == chess.Piece("R")
            elif type == "Q":
                return self["a1"] == chess.Piece("R")
        elif type == "k" or type == "q":
            if self["e8"] != chess.Piece("k"):
                return False
            if type == "k":
                return self["h8"] == chess.Piece("r")
            elif type == "q":
                return self["a8"] == chess.Piece("r")
github thomasahle / fastchess / fastchess.py View on Github external
# Parse remaining words
        piece_to_vec = defaultdict(lambda: 0)
        castling = {}
        for w, v in zip(ft.words[1:], vectors[1:]):
            sq = getattr(chess, w[:2].upper())
            if w.endswith('-Occ'):
                self.occ = True
                for color in chess.COLORS:
                    for piece_type in chess.PIECE_TYPES:
                        piece_to_vec[piece_type, color, sq] += np.hstack([[0], v])
            elif w.endswith('-C'):
                e = 0  # Castling rights don't currently have a value
                castling[sq] = np.hstack([[e], v])
            else:
                piece = chess.Piece.from_symbol(w[2])
                e = self.get_piece_eval(piece.piece_type, piece.color, sq)
                piece_to_vec[piece.piece_type, piece.color, sq] += np.hstack([[e], v])

        # Convert to two-colours
        # We keep a record of the board from both perspectives
        piece_to_vec2 = {}
        for (piece_type, color, sq), v in piece_to_vec.items():
            inv = piece_to_vec[piece_type, not color, chess.square_mirror(sq)]
            piece_to_vec2[piece_type, color, sq] = np.vstack([v, inv])

        self.bias = np.vstack([bias, bias])
        self.piece_to_vec = piece_to_vec2
        self.castling = {sq: np.vstack([v, castling[chess.square_mirror(sq)]])
                         for sq, v in castling.items()}

        # Parse labels
github niklasf / python-chess / chess / position.py View on Github external
:param file:
            The file to check as a letter between `"a"` and `"h"`.

        :return:
            A boolean indicating whether the player could theoretically
            have that en-passant move.
        """
        if not file in ["a", "b", "c", "d", "e", "f", "g", "h"]:
            raise KeyError(
                "Expected a letter between 'a' and 'h' for the file, got: %s."
                    % repr(file))

        # Check there is a pawn.
        pawn_square = chess.Square.from_rank_and_file(
            rank=4 if self.turn == "b" else 5, file=file)
        opposite_color_pawn = chess.Piece.from_color_and_type(
            color=chess.opposite_color(self.turn), type="p")
        if self[pawn_square] != opposite_color_pawn:
            return False

        # Check the square below is empty.
        square_below = chess.Square.from_rank_and_file(
            rank=3 if self.turn == "b" else 6, file=file)
        if self[square_below]:
            return False

        # Check there is a pawn of the other color on a neighbor file.
        f = ord(file) - ord("a")
        p = chess.Piece("p")
        P = chess.Piece("P")
        if self.turn == "b":
            if f > 0 and self[chess.Square.from_x_and_y(f - 1, 3)] == p:
github thomasahle / fastchess / fastchess.py View on Github external
def get_piece_eval(self, piece_type, color, square):
        symbol = chess.Piece(piece_type, color).symbol().upper()
        if color == chess.WHITE:
            return pst.piece[symbol] + pst.pst[symbol][chess.square_mirror(square)]
        else:
            return - (pst.piece[symbol] + pst.pst[symbol][square])

chess

A chess library with move generation and validation, Polyglot opening book probing, PGN reading and writing, Gaviota tablebase probing, Syzygy tablebase probing, and XBoard/UCI engine communication.

GPL-3.0
Latest version published 10 months ago

Package Health Score

74 / 100
Full package analysis