<jupyter_start><jupyter_text>Chess * https://github.com/niklasf/python-chess/tree/v1.3.0* https://jupyter.brynmawr.edu/services/public/dblank/CS371%20Cognitive%20Science/2016-Fall/Programming%20a%20Chess%20Player.ipynb* https://en.wikipedia.org/wiki/Chess_strategy* https://www.chessprogramming.org/Main_Page*https://www.chessprogramming.org/Simplified_Evaluation_FunctionPiece_Values<jupyter_code>import chess
import random
import time
import math
from IPython.display import display, HTML, clear_output
def who(player):
    return "White" if player == chess.WHITE else "Black"

def display_board(board, use_svg):
    if use_svg:
        return board._repr_svg_()
    else:
        return "<pre>" + str(board) + "</pre>"
    
def random_player(board):
    move = random.choice(list(board.legal_moves))
    return move.uci()
def human_player(board):
    uci = get_move("%s's move [q to quit]> " % who(board.turn))
    legal_uci_moves = [move.uci() for move in board.legal_moves]
    while uci not in legal_uci_moves:
        print("Legal moves: " + (",".join(sorted(legal_uci_moves))))
        uci = get_move("%s's move[q to quit]> " % who(board.turn))
    return uci
def get_move(prompt):
    uci = input(prompt)
    if uci and uci[0] == "q":
        raise KeyboardInterrupt()
    try:
        chess.Move.from_uci(uci)
    except:
        uci = None
    return uci   
def player1(board):
    global moves
    move,moves = minimaxRoot(maxDepth,board,True)
    moves.sort(key=lambda move: move.score, reverse=True)
    return move.uci()
def player2(board):
    global moves
    move,moves = minimaxRoot(maxDepth,board,False)
    moves.sort(key=lambda move: move.score)
    return move.uci()
def play_game(player1, player2, visual="svg", pause=0.2):
    """
    playerN1, player2: functions that takes board, return uci move
    visual: "simple" | "svg" | None
    """
    use_svg = (visual == "svg")
    board = chess.Board()
    try:
        while not board.is_game_over(claim_draw=True):
            if board.turn == chess.WHITE:
                uci = player1(board)
            else:
                uci = player2(board)
            name = who(board.turn)
            board.push_uci(uci)
            if len(board.pieces(chess.QUEEN,board.turn)) + len(board.pieces(chess.QUEEN,not board.turn)) < 2:
                global kingmid
                kingmid = kingend
            
            board_stop = display_board(board, use_svg)
            html = """<span style=\"text-align: center;background: #212121;
            padding: 2px;display: inline-block;width: 110px;\">%s %s: %s </span> <br>
            %s <div>%s</div>""" % (len(board.move_stack), name, uci , board_stop ,[(str(move),move.score) for move in moves[:8]])
            if visual is not None:
                if visual == "svg":
                    clear_output(wait=True)
                display(HTML(html))
                if visual == "svg":
                    time.sleep(pause)
    except KeyboardInterrupt:
        msg = "Game interrupted!"
        return (None, msg, board)
    result = None
    if board.is_checkmate():
        msg = "checkmate: " + who(not board.turn) + " wins!"
        result = not board.turn
    elif board.is_stalemate():
        msg = "draw: stalemate"
    elif board.is_fivefold_repetition():
        msg = "draw: 5-fold repetition"
    elif board.is_insufficient_material():
        msg = "draw: insufficient material"
    elif board.can_claim_draw():
        msg = "draw: claim"
    if visual is not None:
        print(msg)
    return (result, msg, board)
pawn = [(0,  0,  0,  0,  0,  0,  0,  0 ),
        (50, 50, 50, 50, 50, 50, 50, 50),
        (10, 10, 20, 30, 30, 20, 10, 10),
        (5,  5, 10, 25, 25, 10,  5,  5 ),
        (0,  0,  0, 20, 20,  0,  0,  0 ),
        (5, -5,-10,  0,  0,-10, -5,  5 ),
        (5, 10, 10,-20,-20, 10, 10,  5 ),
        (0,  0,  0,  0,  0,  0,  0,  0 )]

knight=[(-50,-40,-30,-30,-30,-30,-40,-50),
        (-40,-20,  0,  0,  0,  0,-20,-40),
        (-30,  0, 10, 15, 15, 10,  0,-30),
        (-30,  5, 15, 20, 20, 15,  5,-30),
        (-30,  0, 15, 20, 20, 15,  0,-30),
        (-30,  5, 10, 15, 15, 10,  5,-30),
        (-40,-20,  0,  5,  5,  0,-20,-40),
        (-50,-40,-30,-30,-30,-30,-40,-50)]

bishop= [(-20,-10,-10,-10,-10,-10,-10,-20),
         (-10,  0,  0,  0,  0,  0,  0,-10),
         (-10,  0,  5, 10, 10,  5,  0,-10),
         (-10,  5,  5, 10, 10,  5,  5,-10),
         (-10,  0, 10, 10, 10, 10,  0,-10),
         (-10, 10, 10, 10, 10, 10, 10,-10),
         (-10,  5,  0,  0,  0,  0,  5,-10),
         (-20,-10,-10,-10,-10,-10,-10,-20)]

rook = [(0,  0,  0,  0,  0,  0,  0,  0 ),
        (5, 10, 10, 10, 10, 10, 10,  5 ),
        (-5,  0,  0,  0,  0,  0,  0, -5),
        (-5,  0,  0,  0,  0,  0,  0, -5),
        (-5,  0,  0,  0,  0,  0,  0, -5),
        (-5,  0,  0,  0,  0,  0,  0, -5),
        (-5,  0,  0,  0,  0,  0,  0, -5),
        (0,  0,  0,  5,  5,  0,  0,  0)]

queen =[(-20,-10,-10, -5, -5,-10,-10,-20),
        (-10,  0,  0,  0,  0,  0,  0,-10),
        (-10,  0,  5,  5,  5,  5,  0,-10),
        (-5,  0,  5,  5,  5,  5,  0, -5),
        (0,  0,  5,  5,  5,  5,  0, -5),
        (-10,  5,  5,  5,  5,  5,  0,-10),
        (-10,  0,  5,  0,  0,  0,  0,-10),
        (-20,-10,-10, -5, -5,-10,-10,-20)]

kingmid=[(-30,-40,-40,-50,-50,-40,-40,-30),
         (-30,-40,-40,-50,-50,-40,-40,-30),
         (-30,-40,-40,-50,-50,-40,-40,-30),
         (-30,-40,-40,-50,-50,-40,-40,-30),
        (-20,-30,-30,-40,-40,-30,-30,-20),
         (-10,-20,-20,-20,-20,-20,-20,-10),
         ( 20, 20,  0, -5, -5,  0, 20, 20),
         ( 20, 30, 10,  0,  0, 10, 30, 20)]

kingend=[(-50,-40,-30,-20,-20,-30,-40,-50),
         (-30,-20,-10,  0,  0,-10,-20,-30),
         (-30,-10, 20, 30, 30, 20,-10,-30),
         (-30,-10, 30, 40, 40, 30,-10,-30),
        (-30,-10, 30, 40, 40, 30,-10,-30),
         (-30,-10, 20, 30, 30, 20,-10,-30),
         (-30,-30,  0,  0,  0,  0,-30,-30),
         (-50,-30,-30,-30,-30,-30,-30,-50)]
def evaluate(board):
    score=0

    for i in chess.SQUARES:
        score += pieceValue(board.piece_at(i),i)
    
    #if board.is_pinned(board.turn,i):
    #    score += 5000
    #score += 100 if board.is_capture(board.peek()) else 0
    #raise SystemExit(board)
    score += 1000 if board.is_checkmate() else 0
    score += -1000 if board.is_stalemate() else 0
    score += (1000 if board.turn else -1000) if board.is_repetition(2) else 0
    #score += 500 if board.is_castling(board.peek()) else 0
        
    return score

def pieceValue(piece,i):
    if piece == None:
        return 0
    def getAbsoluteValue(piece,i):
        if piece.piece_type == chess.PAWN:
            return 100 + (pawn[::-1][math.floor(i/8)][i%8] if  piece.color else pawn[math.floor(i/8)][i%8])
        elif piece.piece_type == chess.KNIGHT:
            return 320 + knight[math.floor(i/8)][i%8]
        elif piece.piece_type == chess.BISHOP:
            return 330 + (bishop[::-1][math.floor(i/8)][i%8] if  piece.color else bishop[math.floor(i/8)][i%8])
        elif piece.piece_type == chess.ROOK:
            return 500 + (rook[::-1][math.floor(i/8)][i%8] if  piece.color else rook[math.floor(i/8)][i%8])
        elif piece.piece_type == chess.QUEEN:
            return 900 + (queen[::-1][math.floor(i/8)][i%8] if  piece.color else queen[math.floor(i/8)][i%8])
        elif piece.piece_type == chess.KING:
            return 9000 + (kingmid[::-1][math.floor(i/8)][i%8] if  piece.color else kingmid[math.floor(i/8)][i%8])

    absoluteValue = getAbsoluteValue(piece,i)
    return absoluteValue if piece.color == True else -absoluteValue
def minimaxRoot(depth, board, isMaximisingPlayer):

    moves = list(board.legal_moves)
    bestMove = -99999 if isMaximisingPlayer else 99990

    for move in moves:
        board.push(move)
        value = minimax(depth - 1, board, -100000, 100000, not isMaximisingPlayer)
        board.pop()
        move.score = value
        if isMaximisingPlayer and value >= bestMove:
            bestMove = value
            bestMoveFound = move
        elif not isMaximisingPlayer and value <= bestMove:
            bestMove = value
            bestMoveFound = move
    
    return bestMoveFound, moves

def minimax(depth, board, alpha, beta, isMaximisingPlayer):

    if depth == 0:
        return evaluate(board) #zavisi kade e minusot treba da se smeni

    moves = list(board.legal_moves)

    if (isMaximisingPlayer):
        bestMove = -99999
        for move in moves:
            board.push(move)
            bestMove = max(bestMove, minimax(depth - 1, board, alpha, beta, not isMaximisingPlayer))
            board.pop()
            alpha = max(alpha, bestMove)
            if beta <= alpha:
                return bestMove
        return bestMove
    else:
        bestMove = 99999
        for move in moves:
            board.push(move);
            bestMove = min(bestMove, minimax(depth - 1, board, alpha, beta, not isMaximisingPlayer))
            board.pop()
            beta = min(beta, bestMove)
            if beta <= alpha:
                return bestMove
        return bestMove
maxDepth = 3
play_game(player1,player2)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1761301594234549, 'fraction_numerical': 0.09532649050010919, 'mean_word_length': 2.0347912524850895, 'pattern_counts': {'":': 3, '<': 16, '<?xml version=': 0, '>': 15, 'https://': 5, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 47, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '82595', 'license': 'MIT', 'n_tokens_mistral': 3944, 'n_tokens_neox': 3446, 'n_words': 828, 'path': 'Chess.ipynb', 'repo_name': 'vasetrendafilov/AI', 'size': '9158'}