Exemple #1
0
 def makes_move(self, in_round):
     move, geval, maps_predicted = self._choose_best_move()
     moverec = self._get_moverec(move, geval, in_round)
     maps_actual = (moverec.possible, moverec.attacked, moverec.defended)
     if is_debug() and maps_predicted:
         self.board.multiplot("", maps_predicted[1:], maps_actual[1:])
     self._log_move(moverec)
     self.board.push(move)
     if is_debug():
         logging.debug("%d. %r %.2f\n%s", self.board.fullmove_number,
                       move.uci(), geval, self.board.unicode())
     not_over = move != chess.Move.null() and not self.board.is_game_over(
         claim_draw=False)
     return not_over
    def _get_move_norepeat(self, move_rating):
        selected_move = move_rating[0][0] if move_rating else chess.Move.null()
        had_3fold = False
        for move, sw, dw in move_rating:
            self.board.push(move)
            try:
                if self.board.can_claim_threefold_repetition():
                    had_3fold = True
                    continue
                if self.board.can_claim_fifty_moves():
                    continue
            finally:
                self.board.pop()

            selected_move = move
            break

        if had_3fold:
            if is_debug() or len(self.moves_log) < 3:
                self.board.write_pgn("last.pgn", -1)

            logging.debug("Rolling back some moves from %s",
                          len(self.moves_log))

            self.moves_log[-1].ignore = True
            self.moves_log[-2].ignore = True
            self.moves_log[-3].ignore = True
            self.moves_log[-4].ignore = True

        return selected_move
def play_one_game(pwhite, pblack, rnd):
    """

    :type pwhite: NNPLayer
    :type pblack: NNPLayer
    :type rnd: int
    """
    board: BoardOptim = BoardOptim.from_chess960_pos(rnd % 960)
    pwhite.board = board
    pblack.board = board

    try:
        while True:  # and board.fullmove_number < 150
            if not pwhite.makes_move(rnd):
                break
            if not pblack.makes_move(rnd):
                break

            if is_debug():
                board.write_pgn(pwhite, pblack, os.path.join(os.path.dirname(__file__), "last.pgn"), rnd)
    except:
        last = board.move_stack[-1] if board.move_stack else Move.null()
        logging.warning("Final move: %s %s %s", last, last.from_square, last.to_square)
        logging.warning("Final position:\n%s", board.unicode())
        raise
    finally:
        if board.move_stack:
            board.write_pgn(pwhite, pblack, os.path.join(os.path.dirname(__file__), "last.pgn"), rnd)

    result = board.result(claim_draw=True)

    badp = 0
    badc = 0
    if isinstance(pwhite, NNPLayer):
        badp += pwhite.invalid_moves
        pwhite.invalid_moves = 0
        badc += 1

    if isinstance(pblack, NNPLayer):
        badp += pblack.invalid_moves
        pblack.invalid_moves = 0
        badc += 1

    badp = badp / badc

    logging.info("Game #%d/%d:\t%s by %s,\t%d moves, %d%% bad", rnd, rnd % 960, result, board.explain(),
                 board.fullmove_number, badp)

    return result
def play_per_turn(pwhite, pblack):
    dataset = DataSet("moves.pkl")
    dataset.load_moves()
    if not is_debug():
        pwhite.nn.learn(dataset.dataset, 20)
        nn.save("nn.hdf5")

    rnd = max([x.from_round
               for x in dataset.dataset]) if dataset.dataset else 0
    while True:
        result = play_one_game(pwhite, pblack, rnd)

        moves = pwhite.get_moves() + pblack.get_moves()
        moves = list(filter(lambda x: x.get_eval() > 0, moves))
        dataset.update(moves)

        rnd += 1
        if not (rnd % 20):
            dataset.dump_moves()

            nn.learn(dataset.dataset, 20)
            nn.save("nn.hdf5")
Exemple #5
0
import logging
import random

import chess
from chess import WHITE
from chess.engine import SimpleEngine

from chessnn import BoardOptim, is_debug
from chessnn.nn import NNChess
from chessnn.player import NNPLayer

if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG if is_debug() else logging.INFO)

    engine = SimpleEngine.popen_uci("stockfish")

    try:
        board = BoardOptim.from_chess960_pos(random.randint(0, 959))
        nn = NNChess("nn.hdf5")
        white = NNPLayer("Lisa", WHITE, nn)
        white.board = board

        while not board.is_game_over():
            if not white.makes_move(0):
                break

            result = engine.play(board, chess.engine.Limit(time=0.100))
            board.push(result.move)

        logging.info("Result: %s", board.result())
    finally:
Exemple #6
0
    lst = list(winning.dataset + losing.dataset)
    random.shuffle(lst)
    if lst:
        nn.train(lst, 20)
        nn.save("nn.hdf5")
        # raise ValueError()

    # winning.dataset.clear()
    # losing.dataset.clear()
    # draw.dataset.clear()


if __name__ == "__main__":
    sys.setrecursionlimit(10000)
    _LOG_FORMAT = '[%(relativeCreated)d %(name)s %(levelname)s] %(message)s'
    logging.basicConfig(level=logging.DEBUG if is_debug() else logging.INFO, format=_LOG_FORMAT)

    # if os.path.exists("nn.hdf5"):
    #    os.remove("nn.hdf5")

    nn = NNChess("nn.hdf5")
    white = NNPLayer("Lisa", WHITE, nn)
    black = NNPLayer("Karen", BLACK, nn)
    # black = Stockfish(BLACK)

    try:
        play_with_score(white, black)
    finally:
        if isinstance(black, Stockfish):
            black.engine.quit()