Beispiel #1
0
    def __generate_chess_moves_tree(self, parent_node, chess_board: chess.Board, depth):
        player_color = 'black' if parent_node['player_color'] == 'white' else 'white'
        
        if chess_board.legal_moves.count == 0:
            ## parent'ın yapabilecegi hamle yok demek
            ## parent final node demek, o yüzden bu node icin gidip value hesaplanacak
            board_fen = parent_node['board_fen']
            piece_map = chess_board.piece_map()
            value = self.__evaluate_chess_board(board_fen, chess_board.is_check(), parent_node['player_color'], piece_map)
            parent_node['value'] = value


        if depth == self.__max_depth: ## buna benzer bir islemi eger herhangi bir legal moves yoksa da yapmak lazim ...
            for possible_move in list(chess_board.legal_moves):
                chess_board.push(possible_move)
                board_fen = chess_board.board_fen()
                piece_map = chess_board.piece_map()                
                child = self.__create_node(possible_move, board_fen, player_color, depth)
                parent_node['children'].append(child)
                # her bir child icin value hesapla
                value = self.__evaluate_chess_board(board_fen, chess_board.is_check(), player_color, piece_map)
                child['value'] = value
                chess_board.pop()

            return    
    
        for possible_move in list(chess_board.legal_moves):
            chess_board.push(possible_move)
            board_fen = chess_board.board_fen()            
            child = self.__create_node(possible_move, board_fen, player_color, depth)
            parent_node['children'].append(child)
            self.__generate_chess_moves_tree(child, chess_board, depth + 1)
            chess_board.pop()
Beispiel #2
0
    def y(self, chess_board: chess.Board):
        print('Ai started thinking !')
        print('Finding all possible moves within next ' + str(self.__max_depth) + ' moves')
        root = self.__create_node(None, chess_board.board_fen(), 'white', 0)
        self.__generate_chess_moves_tree(root, chess_board, 1)

        node = root
        i = 0
        while i < self.__max_depth:
            print('Move Count: ' + str(node['depth']))
            print('Player color:' + node['player_color'])
            print('Chess Move:' + str(node['chess_move']))
            print('Board Fen:' + node['board_fen'])
            print('Value: ' + str(node['value']))
            print('--------------------------------------')
            node = node['children'][0]
            i = i+1

        print('Move Count: ' + str(node['depth']))
        print('Player color:' + node['player_color'])
        print('Chess Move:' + str(node['chess_move']))
        print('Board Fen:' + node['board_fen'])
        print('Value: ' + str(node['value']))
        print('--------------------------------------')

        return root
Beispiel #3
0
 def _oldstyle_fen(game: chess.Board):
     builder = []
     builder.append(game.board_fen())
     builder.append('w' if game.turn == chess.WHITE else 'b')
     builder.append(game.castling_xfen())
     builder.append(chess.SQUARE_NAMES[game.ep_square] if game.ep_square else '-')
     builder.append(str(game.halfmove_clock))
     builder.append(str(game.fullmove_number))
     return ' '.join(builder)
Beispiel #4
0
 def _oldstyle_fen(game: chess.Board):
     builder = []
     builder.append(game.board_fen())
     builder.append('w' if game.turn == chess.WHITE else 'b')
     builder.append(game.castling_xfen())
     builder.append(
         chess.SQUARE_NAMES[game.ep_square] if game.ep_square else '-')
     builder.append(str(game.halfmove_clock))
     builder.append(str(game.fullmove_number))
     return ' '.join(builder)
def board_evaluation(board: Board, add_mobility: bool = False) -> float:
    """
    Function for evaluating a chess position, given its board.
    It returns positive values for white evaluation.
    157 µs ± 1.87 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)"""
    score = float()
    fen = board.board_fen()
    for piece, value in VALUE_DICT.items():
        score += value * (fen.count(piece.upper()) - fen.count(piece))
    if add_mobility:
        mobility = get_mobility(board)
        if not board.turn:
            mobility *= -1
        score += mobility
    return score
def render_board(board: chess.Board, turn: chess.Color, output_file: Path):
    scene = bpy.context.scene

    # Setup rendering
    scene.render.engine = "CYCLES"
    scene.render.image_settings.file_format = "PNG"
    scene.render.filepath = str(output_file)
    scene.render.resolution_x = 1200
    scene.render.resolution_y = 800

    corner_coords = None
    while not corner_coords:
        camera_params = setup_camera(turn)
        lighting_params = setup_lighting()
        corner_coords = get_corner_coordinates(scene)

    # Create a collection to store the position
    if COLLECTION_NAME not in bpy.data.collections:
        collection = bpy.data.collections.new("Chess position")
        scene.collection.children.link(collection)
    collection = bpy.data.collections["Chess position"]

    # Remove all objects from the collection
    bpy.ops.object.delete({"selected_objects": collection.objects})

    piece_data = []
    for square, piece in board.piece_map().items():
        obj = add_piece(piece, square, collection)
        piece_data.append({
            "piece": piece.symbol(),
            "square": chess.square_name(square),
            "box": get_bounding_box(scene, obj)
        })

    # Write data output
    data = {
        "fen": board.board_fen(),
        "white_turn": turn,
        "camera": camera_params,
        "lighting": lighting_params,
        "corners": corner_coords,
        "pieces": piece_data
    }
    with (output_file.parent / (output_file.stem + ".json")).open("w") as f:
        json.dump(data, f)

    # Perform the rendering
    bpy.ops.render.render(write_still=1)
Beispiel #7
0
    def put(self, board: chess.Board, move_stack, depth: int):
        val = self.hash(board)
        fen = board.board_fen()

        #if an entry already exists in the table for the given hash key,
        #check if it is the same position or not. If it is, overwrite it if the new entry is at a higher depth.
        #if it is not, overwrite it.

        if val in self.table:
            if self.table[val][0] == fen:
                if self.table[val][2] < depth:
                    self.table[val] = [fen, move_stack, depth, board.turn]
                    return
                else:
                    return

        self.table[val] = [fen, move_stack, depth, board.turn]
Beispiel #8
0
 def heuristic(self, board: chess.Board) -> float:
     result = board.result()
     return AIController.RESULT_MAP[result] if result in AIController.RESULT_MAP \
         else np.sum([AIController.PIECE_MAP[char] if char in AIController.PIECE_MAP else 0 for char in board.board_fen()])
Beispiel #9
0
'''

# test for speed
import time

loop_count = 10000
t0 = time.time()
for i in range(loop_count):
	w.evaluation(b)
t1 = time.time()
print('python code time: {}'.format(t1-t0))

t0 = time.time()
for i in range(loop_count):
	x = b.result()
	y = b.board_fen()
	z = len(y)
	e.evaluation(x, y, z)
t1 = time.time()
print('c code time: {}'.format(t1-t0))

t0 = time.time()
x = list(b.legal_moves)[0]
for i in range(loop_count):
	for j in range(30):
		b.push(x)
		b.pop()
t1 = time.time()
print('chess board legal_moves code time: {}'.format(t1-t0))

 def update_history(self, board: Board, value: float) -> None:
     self.evaluations[board.board_fen()] = value
Beispiel #11
0
    def launchSf(
        self,
        pars,
        fen,
        tablebases,
    ):
        board = Board(fen, chess960=False)
        wdl = None
        drawPlyCnt, resignPlyCnt = 0, 0
        whiteIdx = 1
        turnIdx = whiteIdx ^ (board.turn == chess.BLACK)
        uciEngines = init_engines(pars)
        info_handler = uci.InfoHandler()
        for u in uciEngines:
            u.info_handlers.append(info_handler)
            u.ucinewgame()

        try:
            while (not board.is_game_over(claim_draw=True)):

                if board.castling_rights == 0:
                    if len(re.findall(r"[rnbqkpRNBQKP]",
                                      board.board_fen())) < 6:
                        wdl = tablebases.probe_wdl(board)
                        if wdl is not None:
                            break

                uciEngines[turnIdx].position(board)
                bestmove, score = uciEngines[turnIdx].go(depth=9)
                score = info_handler.info["score"][1].cp
                #        print(score)

                if score is not None:
                    # Resign adjudication
                    if abs(score) >= Resign['score']:
                        resignPlyCnt += 1
                        if resignPlyCnt >= 2 * Resign['movecount']:
                            break
                    else:
                        resignPlyCnt = 0

                    # Draw adjudication
                    if abs(score
                           ) <= Draw['score'] and board.halfmove_clock > 0:
                        drawPlyCnt += 1
                        if drawPlyCnt >= 2 * Draw['movecount'] \
                                and board.fullmove_number >= Draw['movenumber']:
                            break
                    else:
                        drawPlyCnt = 0
                else:
                    # Disable adjudication over mate scores
                    drawPlyCnt, resignPlyCnt = 0, 0

                board.push(bestmove)
                turnIdx ^= 1

            result = board.result(True)
            if result == '*':
                if resignPlyCnt >= 2 * Resign['movecount']:
                    if score > 0:
                        result = '1-0' if board.turn == chess.WHITE else '0-1'
                    else:
                        result = '0-1' if board.turn == chess.WHITE else '1-0'
                elif wdl is not None:
                    if wdl <= -1:
                        result = '1-0' if board.turn == chess.WHITE else '0-1'
                    elif wdl >= 1:
                        result = '0-1' if board.turn == chess.WHITE else '1-0'
                    else:
                        result = '1/2-1/2'
#            print('tb draw')
                else:
                    result = '1/2-1/2'
#          print('draw')

#    print(board.fen())
#    print(re.findall(r"[rnbqkpRNBQKP]", board.board_fen()))
            for u in uciEngines:
                u.quit(0)
        except (MemoryError, SystemError, KeyboardInterrupt, OverflowError,
                OSError, ResourceWarning):
            for u in uciEngines:
                u.quit(1)
        return result
        #    print(result)
        exit(0)