示例#1
0
def play_game(engine1, engine2):
    board = chess.Board()
    info1 = uci.InfoHandler()
    info2 = uci.InfoHandler()
    engine1.info_handlers.append(info1)
    engine2.info_handlers.append(info2)
    while not board.is_game_over():
        engine1.position(board)
        bestInfo = engine1.go(movetime = 1000)
        print bestInfo
        board.push(bestInfo.bestmove)
        if board.is_game_over(): break

        engine2.position(board)
        bestInfo = engine2.go(movetime = 1000)
        print bestInfo
        board.push(bestInfo.bestmove)
        print board
        with info1:
            cp = info1.info["score"][1].cp
            mate = info1.info["score"][1].mate
            print cp, mate
        with info2:
            cp, mate = info2.info["score"][1].cp, info2.info["score"][1].mate
            print cp, mate
示例#2
0
def play_game(engine1, engine2):
    board = chess.Board()
    info1 = uci.InfoHandler()
    info2 = uci.InfoHandler()
    engine1.info_handlers.append(info1)
    engine2.info_handlers.append(info2)
    while not board.is_game_over():
        engine1.position(board)
        bestInfo = engine1.go(movetime=100)
        #        print bestInfo
        board.push(bestInfo.bestmove)
        if board.is_game_over(): break

        engine2.position(board)
        bestInfo = engine2.go(movetime=100)
        #        print bestInfo
        board.push(bestInfo.bestmove)


#        print board
#        with info1:
#            cp = info1.info["score"][1].cp
#            mate = info1.info["score"][1].mate
#            print cp, mate
#        with info2:
#            cp, mate = info2.info["score"][1].cp, info2.info["score"][1].mate
#            print cp, mate
    if board.is_checkmate():
        #White's turn
        if board.turn:
            return 0.
        else:
            return 1.
    else:
        return .5
示例#3
0
    def __init__(self, config, engine=True, newmodel: bool = False):
        logging.debug('newmodel')
        logging.debug(newmodel)
        self.config = config
        self.engine = engine

        if self.engine:
            self.engine = uci.popen_engine(
                stockfish_command(config['stockfish']['update']))
            self.engine.setoption({
                'Threads': config['stockfish']['threads'],
                'Hash': config['stockfish']['memory']
            })
            self.engine.uci()
            self.infoHandler = uci.InfoHandler()
            self.engine.info_handlers.append(self.infoHandler)

        self.api = Api(config['api']['url'], config['api']['token'])

        # Set up mongodb
        self.client = MongoClient(config['db']['host'])
        self.db = self.client.irwin
        if config['db']['authenticate']:
            self.db.authenticate(config['db']['authentication']['username'],
                                 config['db']['authentication']['password'],
                                 mechanism='MONGODB-CR')

        # Irwin
        self.irwinEnv = IrwinEnv(config, self.db)
        self.irwin = Irwin(self.irwinEnv, newmodel)
示例#4
0
文件: client.py 项目: shinbet/lc1
def get_engine(engine_conf):
    e = uci.popen_engine(engine_conf.cmd, engine_cls=TrainEngine)
    e.uci()
    if engine_conf.options:
        e.setoption(engine_conf.options)
    e.isready()

    info_handler = uci.InfoHandler()
    e.info_handlers.append(info_handler)
    return e
示例#5
0
    def new(conf: ConfigWrapper):
        engine = uci.popen_engine(stockfish_command(conf['stockfish update']))
        engine.setoption({
            'Threads': conf['stockfish threads'],
            'Hash': conf['stockfish memory']
        })
        engine.uci()

        infoHandler = uci.InfoHandler()

        engine.info_handlers.append(infoHandler)

        return EngineTools(engine=engine, infoHandler=infoHandler)
示例#6
0
 def restartEngine(self):
     if self.engine:
         self.engine.kill()
         self.engine = uci.popen_engine(
             stockfish_command(self.config['stockfish']['update']))
         self.engine.setoption({
             'Threads':
             self.config['stockfish']['threads'],
             'Hash':
             self.config['stockfish']['memory']
         })
         self.engine.uci()
         self.infoHandler = uci.InfoHandler()
         self.engine.info_handlers.append(self.infoHandler)
 def initialize(self):
     # Caffe net setup
     net = caffe.Net(CAFFENET_DEPLOY_TXT, CAFFENET_MODEL_FILE, caffe.TEST)
     # Set up transformer for input data
     transformer = caffe.io.Transformer(
         {'data': net.blobs['data'].data.shape})
     transformer.set_transpose('data', (2, 0, 1))
     transformer.set_mean(
         'data', np.array([104.00698793, 116.66876762, 122.67891434]))
     transformer.set_raw_scale(
         'data', 255
     )  # the reference model operates on images in [0,255] range instead of [0,1]
     transformer.set_channel_swap('data', (
         2, 1,
         0))  # the reference model has channels in BGR order instead of RGB
     net.blobs['data'].reshape(BATCH_SIZE, 3, 227, 227)
     self.board = pychess.Board()
     self.engine = pychess_uci.popen_engine(STOCKFISH_PATH)
     self.engine.uci()
     self.engine.setoption({"UCI_Chess960": True})
     self.engine.info_handlers.append(pychess_uci.InfoHandler())
     self.remap = {
         'bb': 'b',
         'bk': 'k',
         'bn': 'n',
         'bp': 'p',
         'bq': 'q',
         'br': 'r',
         'wb': 'B',
         'wk': 'K',
         'wn': 'N',
         'wp': 'P',
         'wq': 'Q',
         'wr': 'R',
         None: None
     }
示例#8
0
def launchSf(locpars):
    sf = uci.popen_engine(engine)
    base = uci.popen_engine(engine)
    info_handler = uci.InfoHandler()
    info_handler1 = uci.InfoHandler()
    sf.info_handlers.append(info_handler)
    base.info_handlers.append(info_handler1)

    sf.setoption({'Clear Hash': True})
    sf.setoption({'Hash': 1})
    base.setoption({'Clear Hash': True})
    base.setoption({'Hash': 1})

    for p in locpars:
        sf.setoption({p[0]: p[1]})

    sf.uci()
    sf.isready()
    sf.ucinewgame()
    base.uci()
    base.isready()
    base.ucinewgame()
    board = Board(chess960=False)
    #  board.set_epd('5rk1/p1pr2bp/1p2b1p1/2q1p3/2P1P3/1P1P1PQ1/P5BP/2BR1R1K b - - 9 23')
    #  opening, play, evals = pgn_prepare()
    #  print(opening)
    #  for move in opening:
    #    board.push_san(move)
    #  sf.position(board)

    diffs = 0
    #  diffs1 = []
    #  evs = []
    for j in range(2):
        #    i=0
        try:
            while True:
                if board.turn == 1:
                    pos = board
                    sf.position(pos)
                    pos.push(sf.go(depth=14)[0])
                    score = info_handler.info["score"][1].cp
                    #         print(info_handler.info["score"])
                    if info_handler.info["score"][1].mate is not None:
                        break
                    if pos.is_game_over(claim_draw=True) is True:
                        break
                    diffs += score
                else:
                    pos = board
                    base.position(pos)
                    pos.push(base.go(depth=14)[0])
                    if info_handler1.info["score"][1].mate is not None:
                        break
                    if pos.is_game_over(claim_draw=True) is True:
                        break


#      i=i+1
        finally:
            break
        base.position(board)
        board.push(base.go(depth=12)[0])
    print(diffs)

    sf.terminate()

    return diffs
示例#9
0
    def launchSf(
        self,
        pars,
        fen,
        tablebases,
    ):
        try:
            board = Board(fen, chess960=False)
        except BaseException:
            try:
                board.set_epd(fen)
            except BaseException:
                board = Board(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()

        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                       # ~ 1.5 ms

                try:
                    wdl = tablebases.probe_wdl(board)
                    if wdl is not None:
                        break
                except KeyError:
                    pass  # < 1 ms

            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)


#    print(result)
        return result
        exit(0)
示例#10
0
        exit(1)

    katyusha = None
    try:
        katyusha = uci.popen_engine(argv[1])
        katyusha.uci()
    except e:
        print "error initializing engine"
        print e
        exit(1)
    weightsfile = argv[2]

    temp_npz_file = "temp_td_weights.npz"
    na.model.load_weights(weightsfile)
    na.save_as_npz(temp_npz_file)
    info_handler = uci.InfoHandler()
    katyusha.info_handlers.append(info_handler)
    katyusha.setoption({
        "Katyusha_Learning": True,
        "weightsfile": temp_npz_file
    })
    pos_file = open(argv[3], "r")
    fen_arr = np.array([line.strip() for line in pos_file])
    mask = np.arange(len(fen_arr))
    np.random.shuffle(mask)
    fen_arr = fen_arr[mask]

    num_moves = 12
    for batch_num in xrange(max_batches):
        print "On Batch " + str(batch_num)
        evals_list = []
示例#11
0
import chess
from chess import uci

from sys import argv, exit

usage = "usage engine1 engine2"
if len(argv) < 3:
  print usage
  exit(1)

engine1, engine2 = None, None
try:
    engine1, engine2 = uci.popen_engine(argv[1]), uci.popen_engine(argv[2])
    engine1.uci()
    engine2.uci()
    engine1.info_handlers.append(uci.InfoHandler())
    engine2.info_handlers.append(uci.InfoHandler())
except e:
    print e
    print "error opening engine binaries"
    print usage
    exit(1)

def play_game(engine1, engine2):
    board = chess.Board()
    info1 = uci.InfoHandler()
    info2 = uci.InfoHandler()
    engine1.info_handlers.append(info1)
    engine2.info_handlers.append(info2)
    while not board.is_game_over():
        engine1.position(board)