How to use the chess.Move 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
board_creator_fn, and the second being a size 3 ndarray representing a move. The function must return a
     boolean value, indicating if the move is legal
    :param board_creator_fn: A function which takes as input a Python-Chess Board object, and outputs the board in the
     representation to be used when testing move legality.
    :param fens_to_test: An iterable of strings, each a FEN representation of a board.
    :param moves_to_test: A uint8 ndarray of size [num_moves_to_test, 3], representing the moves to test for each
     testing fen
    :return: True if all tests were passed, False if not
    """
    for cur_fen in fens_to_test:
        cur_board = chess.Board(cur_fen)

        cur_testing_board = board_creator_fn(cur_board)
        for j in range(len(moves_to_test)):
            if move_legality_tester(cur_testing_board, moves_to_test[j]) != cur_board.is_legal(
                    chess.Move(*moves_to_test[j]) if moves_to_test[j, 2] != 0 else chess.Move(*moves_to_test[j, :2])):
                return False

    return True
github niklasf / python-chess / tests / test_position.py View on Github external
"""Tests the scholars mate."""
        pos = chess.Position()
        self.assertTrue(pos.has_queenside_castling_right("b"))

        e4 = chess.Move.from_uci('e2e4')
        self.assertTrue(e4 in pos.get_legal_moves())
        pos.make_move(e4)
        self.assertTrue(pos.has_queenside_castling_right("b"))

        e5 = chess.Move.from_uci('e7e5')
        self.assertTrue(e5 in pos.get_legal_moves())
        self.assertFalse(e4 in pos.get_legal_moves())
        pos.make_move(e5)
        self.assertTrue(pos.has_queenside_castling_right("b"))

        Qf3 = chess.Move.from_uci('d1f3')
        self.assertTrue(Qf3 in pos.get_legal_moves())
        pos.make_move(Qf3)
        self.assertTrue(pos.has_queenside_castling_right("b"))

        Nc6 = chess.Move.from_uci('b8c6')
        self.assertTrue(Nc6 in pos.get_legal_moves())
        pos.make_move(Nc6)
        self.assertTrue(pos.has_queenside_castling_right("b"))

        Bc4 = chess.Move.from_uci('f1c4')
        self.assertTrue(Bc4 in pos.get_legal_moves())
        pos.make_move(Bc4)
        self.assertTrue(pos.has_queenside_castling_right("b"))

        Rb8 = chess.Move.from_uci('a8b8')
        self.assertTrue(Rb8 in pos.get_legal_moves())
github FTdiscovery / 64CrazyhouseDeepLearning / ChessEnvironment.py View on Github external
def makeMove(self, move):
        if chess.Move.from_uci(move) in self.board.legal_moves:
            self.board.push(chess.Move.from_uci(move))

            # update boards
            for i in range(8):
                for j in range(8):
                    if self.board.piece_at(8*i+j) != None:
                        self.arrayBoard[7-i][j] = self.board.piece_at(8*i+j).symbol()
                    else:
                        self.arrayBoard[7-i][j] = ' '

                # update pockets
                self.whiteCaptivePieces = [0, 0, 0, 0, 0]
                self.blackCaptivePieces = [0, 0, 0, 0, 0]
                whitePocket = list(str(self.board.pockets[0]))
                blackPocket = list(str(self.board.pockets[1]))

                for k in range(len(whitePocket)):
github fsmosca / Python-Easy-Chess-GUI / python_easy_chess_gui.py View on Github external
user_move = None
                            
                            # Get the fr_sq and to_sq of the move from user, based from this info
                            # we will create a move based from python-chess format.
                            # Note chess.square() and chess.Move() are from python-chess module
                            fr_row, fr_col = move_from
                            fr_sq = chess.square(fr_col, 7-fr_row)
                            to_sq = chess.square(to_col, 7-to_row)
    
                            # If user move is a promote
                            if self.relative_row(to_sq, board.turn) == RANK_8 and \
                                    moved_piece == chess.PAWN:
                                is_promote = True
                                pyc_promo, psg_promo = self.get_promo_piece(
                                        user_move, board.turn, True)
                                user_move = chess.Move(fr_sq, to_sq, promotion=pyc_promo)
                            else:
                                user_move = chess.Move(fr_sq, to_sq)
                            
                            # Check if user move is legal
                            if user_move in board.legal_moves:
                                # Update rook location if this is a castle move
                                if board.is_castling(user_move):
                                    self.update_rook(str(user_move))
                                    
                                # Update board if e.p capture
                                elif board.is_en_passant(user_move):
                                    self.update_ep(user_move, board.turn)                                
                                    
                                # Empty the board from_square, applied to any types of move
                                self.psg_board[move_from[0]][move_from[1]] = BLANK
github niklasf / python-chess / chess / variant.py View on Github external
def generate_pseudo_legal_moves(self, from_mask: chess.Bitboard = chess.BB_ALL, to_mask: chess.Bitboard = chess.BB_ALL) -> Iterator[chess.Move]:
        for move in super().generate_pseudo_legal_moves(from_mask, to_mask):
            # Add king promotions.
            if move.promotion == chess.QUEEN:
                yield chess.Move(move.from_square, move.to_square, chess.KING)

            yield move
github FTdiscovery / 64CrazyhouseDeepLearning / NNHumanCompetition.py View on Github external
print("Win Probability: {:.4f} %".format(100*ValueEvaluation.positionEval(sim, bestNet.neuralNet)))
            if playouts > 0 and bestNet.childrenStateSeen[directory][index]>0:
                mctsWinRate = 100*bestNet.childrenStateWin[directory][index]/bestNet.childrenStateSeen[directory][index]
                print("MCTS Win Probability: {:.4f} %".format(mctsWinRate))
                totalWinRate = (100*ValueEvaluation.positionEval(sim, bestNet.neuralNet)+mctsWinRate)/2
                print("Total Win Probability: {:.4f} %".format(totalWinRate))
            print("-----")

            sim.makeMove(move)
            sim.gameResult()
        elif sim.plies % 2 == 0:
            legal = False
            while not legal:
                move = input("Enter move: ")
                if len(move) == 4 or len(move) == 5:
                    if chess.Move.from_uci(move) in sim.board.legal_moves:
                        legal = True
                    else:
                        print("Illegal move! Try again:")
                else:
                    print("Illegal move! Try again:")
            print(move)
            sim.makeMove(move)
            sim.gameResult()

        if sim.plies == 1:
            node = PGN.add_variation(chess.Move.from_uci(move))
        else:
            node = node.add_variation(chess.Move.from_uci(move))

        print(sim.board)
        print("WHITE POCKET")
github fsmosca / Python-Easy-Chess-GUI / python_easy_chess_gui.py View on Github external
# Get the fr_sq and to_sq of the move from user, based from this info
                            # we will create a move based from python-chess format.
                            # Note chess.square() and chess.Move() are from python-chess module
                            fr_row, fr_col = move_from
                            fr_sq = chess.square(fr_col, 7-fr_row)
                            to_sq = chess.square(to_col, 7-to_row)
    
                            # If user move is a promote
                            if self.relative_row(to_sq, board.turn) == RANK_8 and \
                                    moved_piece == chess.PAWN:
                                is_promote = True
                                pyc_promo, psg_promo = self.get_promo_piece(
                                        user_move, board.turn, True)
                                user_move = chess.Move(fr_sq, to_sq, promotion=pyc_promo)
                            else:
                                user_move = chess.Move(fr_sq, to_sq)
                            
                            # Check if user move is legal
                            if user_move in board.legal_moves:
                                # Update rook location if this is a castle move
                                if board.is_castling(user_move):
                                    self.update_rook(str(user_move))
                                    
                                # Update board if e.p capture
                                elif board.is_en_passant(user_move):
                                    self.update_ep(user_move, board.turn)                                
                                    
                                # Empty the board from_square, applied to any types of move
                                self.psg_board[move_from[0]][move_from[1]] = BLANK
                                
                                # Update board to_square if move is a promotion
                                if is_promote:
github linrock / chess-puzzle-maker / puzzlemaker / puzzle_exporter.py View on Github external
def export(self, pgn_headers=None) -> Game:
        """ pgn_headers - PGN headers to include in the exported PGN
        """
        fen = self.puzzle.initial_board.fen()
        board = chess.Board(fen)
        game = Game().from_board(board)
        game_node = game
        game_node.comment = "score: %s -> %s" % (
            _score_to_str(self.puzzle.initial_score),
            _score_to_str(self.puzzle.final_score)
        )
        comment = self._candidate_moves_annotations(self.puzzle.analyzed_moves)
        for position in self.puzzle.positions:
            game_node = game_node.add_variation(
                chess.Move.from_uci(position.initial_move.uci())
            )
            if comment:
                game_node.comment = comment
            comment = self._candidate_moves_annotations(position.candidate_moves)
        if pgn_headers:
            for h in pgn_headers:
                if h == "FEN":
                    continue
                game.headers[h] = pgn_headers[h]
        game.headers['PuzzleCategory'] = self.puzzle.category()
        puzzle_winner = self.puzzle.winner()
        if puzzle_winner:
            game.headers['PuzzleWinner'] = puzzle_winner
        game.headers['PuzzleEngine'] = AnalysisEngine.name()
        game.headers['PuzzleMakerVersion'] = __version__
        return game
github Assios / Bottios / atomic_engine.py View on Github external
break

	return (best_value, best_move)


if __name__ == "__main__":
	board = chess.variant.AtomicBoard()
	moves = []
	book = None
	#pickle.dump(book, open("penguinbook.p", "wb"))

	c = 0
	while not board.is_variant_end():
		if c%2==0:
			move = input("move: \n\n")
			move = chess.Move.from_uci(move)
			if not move in board.legal_moves:
				continue
		else:
			start_time = time.time()

			#book_move = book.get_moves(moves)
			book_move = None
			if book_move:
				move = random.choice(book_move)
				move = chess.Move.from_uci(move)
			else:
				move = search(board, color=-1, variant="atomic", depth=DEPTH)
			elapsed = time.time() - start_time
			print("--- %s moves ---" % (len(list(board.legal_moves))))
			print("--- number of nodes: %s --" % poscount)
			print("--- %s seconds ---" % (elapsed))

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 1 month ago

Package Health Score

82 / 100
Full package analysis