def __init__(self):
     if platform.system() == 'Darwin':
         self.engine = popen_engine(basepath + "/stockfish-osx")
     elif platform.system() == 'Linux':
         self.engine = popen_engine(basepath + "/stockfish-linux")
     elif platform.system() == 'Windows':
         self.engine = popen_engine(basepath + "/stockfish-windows")
Пример #2
0
 def _init_engine(self):
     if platform.system() == "Linux":
         if platform.machine() == "armv7l":
             self.engine = uci.popen_engine("bin/stockfish-8-arm-rasp")
         else:
             self.engine = uci.popen_engine("bin/stockfish-9-popcnt")
     elif platform.system() == "Darwin":
         self.engine = uci.popen_engine("bin/stockfish")
     self.engine.uci()
     self.engine.ucinewgame()
Пример #3
0
 def on_add(self):
     dialog = QFileDialog()
     dialog.setFilter(QDir.Executable | QDir.Files)
     filename = dialog.getOpenFileName(self, self.trUtf8('Select Engine'), None, '',QFileDialog.DontUseNativeDialog)
     if(filename):
             engine = Engine()
             engine.path = filename
             try:
                 eng = popen_engine(filename)
                 command = eng.uci(async_callback=True)
                 command.result(timeout=1.5)
                 engine.name = eng.name
                 self.engines.append(engine)
                 item = QListWidgetItem(engine.name)
                 self.lstEngines.addItem(item)
                 item.setSelected(True)
                 print("I am quitting. I quit.")
                 eng.quit()
                 print("sine they have my stapler")
                 #self.active_engine = engine
             except BaseException as e:
                 print(e)
             finally: pass
                 # todo: better error handling if
                 # a non-chess engine is chosen
Пример #4
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)
Пример #5
0
    async def __aenter__(self):
        """Starts a chess engine and prepares it for commands."""
        # We make sure we aren't running in an async with statement
        self._check_not_in_awith()

        # We initialise the engine
        self.engine = uci.popen_engine(self.engine_path, setpgrp=True)

        # We set the difficulty
        await self.wait_for(
            self.engine.setoption(
                {
                    "Skill Level": self.difficulty,
                    "Threads": self.num_search_threads
                },
                async_callback=True))

        # We set the board position to the saved one
        await self.wait_for(
            self.engine.position(self.board, async_callback=True))

        # We're longer in an async with statement
        self._in_with_statement = True

        return self
Пример #6
0
 def start_engine(self):
     if self.engine is not None:
         self.engine.quit()
     self.engine = uci.popen_engine(
         os.path.join(self.binary_dir, "engine.exe"))
     self.engine.setoption({'Threads': self.get_option("threads")})
     self.engine.uci()
     self.engine.ucinewgame()
Пример #7
0
def main():
    global move_array
    game = True
    engine = uci.popen_engine('./Engine/stockfish_8_x64')
    engine.uci()

    while game:

        SCREEN.blit(BACKGROUND, (0, 512))
        button("Reset", 50, 520, 100, 30, BUTTON_BACK, BUTTON_BACK, resetBoard)
        button("<<", 200, 520, 50, 30, BUTTON_BACK, BUTTON_BACK, toBeginning)
        button("<", 270, 520, 50, 30, BUTTON_BACK, BUTTON_BACK, oneBack)
        button(">", 340, 520, 50, 30, BUTTON_BACK, BUTTON_BACK, pushOne)
        button(">>", 410, 520, 50, 30, BUTTON_BACK, BUTTON_BACK, toEnd)

        for row in range(8):
            for column in range(8):
                if (row, column) not in move_array:
                    if (row + column) % 2 == 0:
                        SCREEN.blit(SQUARE_DARK, (row * 64, column * 64))
                    else:
                        SCREEN.blit(SQUARE_LIGHT, (row * 64, column * 64))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game = False
            if event.type == pygame.MOUSEBUTTONUP:
                pos = pygame.mouse.get_pos()
                x_val, y_val = int(pos[0] / 64), 7 - (int(pos[1] / 64))
                if y_val >= 0:
                    move_array.append((x_val, y_val))

        if len(move_array) == 1:
            SCREEN.blit(SQUARE_CLICKED,
                        (move_array[0][0] * 64, (7 - move_array[0][1]) * 64))

        if len(move_array) == 2:
            square_x = chess.square(move_array[0][0], move_array[0][1])
            square_y = chess.square(move_array[1][0], move_array[1][1])

            if (str(BOARD.piece_at(square_x)) == 'P' or str(BOARD.piece_at(square_x)) == 'p') \
            and chess.file_index(square_x) != chess.file_index(square_y) and \
            (chess.rank_index(square_y) == 0 or chess.rank_index(square_y) == 7):
                cur_move = chess.Move(square_x, square_y, promotion=5)
            else:
                cur_move = chess.Move(square_x, square_y)

            if cur_move in BOARD.legal_moves:
                BOARD.push(cur_move)
                engine_position = engine.position(BOARD)
                engine_moves = engine.go()
                BOARD.push(engine_moves[0])
            else:
                move_array = []

        updateBoard()
        pygame.display.flip()
        CLOCK.tick(30)
Пример #8
0
 def get_engine_move(self,engine):
     settings = self.config[engine]
     engine_loc = settings.pop('Location')
     engine = uci.popen_engine(engine_loc)
     engine.position(self.board)
     move, ponder = engine.go(**settings)
     engine.terminate()
     settings['Location'] = engine_loc
     return move
Пример #9
0
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
Пример #10
0
def play_stockfish(board):
    eng = uci.popen_engine("/usr/games/stockfish")
    eng.uci()
    eng.position(board)
    m = eng.go(movetime=1000)
    eng.ucinewgame()
    # import ipdb; ipdb.set_trace()
    make_mouse_move(m[0].from_square, m[0].to_square)
    board.push_uci(m[0].uci())
    print board
Пример #11
0
 def __init__(self):
     if IS_WINDOWS:
         self.base_file_name = 'base.exe'
     else:
         self.base_file_name = './base'
     self.base_engine = uci.popen_engine(self.base_file_name)
     self.info_handler_base = uci.InfoHandler()
     self.base_engine.info_handlers.append(self.info_handler_base)
     self.base_engine.setoption({'Threads': '2'})
     self.base_engine.setoption({'Hash': '2048'})
Пример #12
0
def lin_ex (n): # Run 1 move in n games sequentially
	for i in range(n):
		eng = uci.popen_engine("/usr/games/stockfish")
		eng.uci()
		eng.ucinewgame()
		board = chess.Board()
		eng.position(board)
		command = eng.go(movetime=1000, async_callback=True)  
		command.result()
		eng.quit()
Пример #13
0
    def __init__(self):
        self._color = os.environ.get('COLOR') == "white"
        self._game_id = os.environ.get('GAME_ID')
        self.bot_id = secrets.token_hex(nbytes=16)

        #TODO : connect from config file
        self._red = redis.StrictRedis(host='redis',
                                      db=3,
                                      port=6379,
                                      password='******')
        self._engine = uci.popen_engine("/usr/games/stockfish")
        self._board = Board()
Пример #14
0
	def on_message(self, message):
		"""
		when we receive some message we want some message handler..
		for this example i will just print message to console
		"""
		print "Client %s received a message : %s" % (self.id, message)
		# self.write_message('Server received: {}'.format(message))

		board = Board(fen=message)
		engine = uci.popen_engine("/Users/jaco/code/bughouse/stockfish-7-mac/Mac/stockfish-7-64")
		engine.uci()
		engine.setoption({'Ponder': False})
		engine.position(board)
		best_move = engine.go(wtime=60000, btime=60000)
		engine.quit()

		# print engine.options
		# options = OptionMap(
		# 	{
		# 		'Syzygy50MoveRule': Option(name='Syzygy50MoveRule', type='check', default=True, min=None, max=None,
		# 		                           var=[]),
		# 		'Ponder': Option(name='Ponder', type='check', default=False, min=None, max=None, var=[]),
		# 		'Hash': Option(name='Hash', type='spin', default=16, min=1, max=1048576, var=[]),
		# 		'Clear Hash': Option(name='Clear Hash', type='button', default='', min=None, max=None, var=[]),
		# 		'SyzygyProbeLimit': Option(name='SyzygyProbeLimit', type='spin', default=6, min=0, max=6,
		# 		                           var=[]),
		# 		'Write Debug Log': Option(name='Write Debug Log', type='check', default=False, min=None,
		# 		                          max=None, var=[]),
		# 		'SyzygyProbeDepth': Option(name='SyzygyProbeDepth', type='spin', default=1, min=1, max=100,
		# 		                           var=[]),
		# 		'Slow Mover': Option(name='Slow Mover', type='spin', default=84, min=10, max=1000, var=[]),
		# 		'SyzygyPath': Option(name='SyzygyPath', type='string', default='<empty>', min=None, max=None,
		# 		                     var=[]),
		# 		'UCI_Chess960': Option(name='UCI_Chess960', type='check', default=False, min=None, max=None,
		# 		                       var=[]),
		# 		'Threads': Option(name='Threads', type='spin', default=1, min=1, max=128, var=[]),
		# 		'Contempt': Option(name='Contempt', type='spin', default=0, min=-100, max=100, var=[]),
		# 		'Skill Level': Option(name='Skill Level', type='spin', default=20, min=0, max=20, var=[]),
		# 		'Move Overhead': Option(name='Move Overhead', type='spin', default=30, min=0, max=5000, var=[]),
		# 		'Minimum Thinking Time': Option(name='Minimum Thinking Time', type='spin', default=20, min=0,
		# 		                                max=5000, var=[]),
		# 		'nodestime': Option(name='nodestime', type='spin', default=0, min=0, max=10000, var=[]),
		# 		'MultiPV': Option(name='MultiPV', type='spin', default=1, min=1, max=500, var=[])
		# 	})

		msg = {
			'board': 'main',
			'from': str(best_move.bestmove)[:2],
			'to': str(best_move.bestmove)[-2:]
		}
		print 'replying {}'.format(msg)
		self.write_message(json.dumps(msg))
Пример #15
0
def init_engines(pars):
    info_handlers = []
    uciEngines = []
    for e in Engines:
        uciEngines.append(uci.popen_engine(e['file']))

    for u in uciEngines:
        u.uci()
        u.setoption(Options)
        u.setoption(pars[uciEngines.index(u)])
        u.isready()

    return uciEngines
Пример #16
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)
Пример #17
0
def init_engines(pars):
    info_handlers = []
    uciEngines = []
    for e in Engines:
        uciEngines.append(uci.popen_engine(e['file']))

    for e, u in enumerate(uciEngines):
        u.uci()
        u.setoption(Options)
        u.setoption(pars[e])
        u.isready()

    return uciEngines
Пример #18
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)
Пример #19
0
def par_ex (n): # Run 1 move in n games across n separate processes at the same time
	engs = []
	commands = []
	for i in range(n):
		eng = uci.popen_engine("/usr/games/stockfish")
		eng.uci()
		eng.ucinewgame()
		engs.append(eng)
	for i in range(n):
		board = chess.Board()
		engs[i].position(board)
		commands.append(engs[i].go(movetime=1000, async_callback=True))
	for i in range(n):
		commands[i].result()
		engs[i].quit()
 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}
Пример #21
0
 def recommend_move():
     """
     Recommend move using by looking up polyglot opening book. If not in book then use stockfish engine.
     """
     try:
         with polyglot.open_reader(
                 "./data/polyglot/performance.bin") as reader:
             main_entry = reader.find(board)
         recom_move = main_entry.move()
     except IndexError:
         engine = uci.popen_engine("./Stockfish/src/stockfish")
         engine.uci()
         engine.position(board)
         # Gets tuple of bestmove and ponder move.
         best_move = engine.go(movetime=ENGINE_MOVETIME)
         recom_move = best_move[0]
         engine.quit()
     return recom_move
Пример #22
0
    def __init__(self, win, stockfish_path, stockfish_timeout=TIMEOUT_MS, stockfish_player=SFISH_WHITE):
        self.win = win
        self.board = pychess.Board()
        self.engine = pychess_uci.popen_engine(stockfish_path)
        self.engine.uci()
        self.engine.setoption({"UCI_Chess960": True})
        self.stockfish_timeout = stockfish_timeout
        self.stockfish_player = stockfish_player
	self.tts_engine = pyttsx.init()
        self.tts_engine.setProperty("rate", 130)
        voices = self.tts_engine.getProperty("voices")
        self.tts_engine.setProperty("voice", voices[9].id)
        if self.stockfish_player == SFISH_WHITE:
            what_playing = "white"
        elif self.stockfish_player == SFISH_BLACK:
            what_playing = "black"
        else:
            what_playing = "both white and black"
        self.tts_engine.say("i am playing %s"%what_playing)
        self.tts_engine.runAndWait()
        self.engine.info_handlers.append(pychess_uci.InfoHandler())
Пример #23
0
 def on_add(self):
     dialog = QFileDialog()
     dialog.setFilter(QDir.Executable | QDir.Files)
     filename = dialog.getOpenFileName(self, self.trUtf8('Select Engine'),
                                       None, '',
                                       QFileDialog.DontUseNativeDialog)
     if (filename):
         engine = Engine()
         engine.path = filename
         try:
             eng = popen_engine(filename)
             command = eng.uci(async_callback=True)
             command.result(timeout=1.5)
             engine.name = eng.name
             self.engines.append(engine)
             item = QListWidgetItem(engine.name)
             self.lstEngines.addItem(item)
             item.setSelected(True)
             eng.quit()
             #self.active_engine = engine
         except BaseException as e:
             print(e)
         finally:
             pass
 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
     }
Пример #25
0
from chess import uci
from tornado.options import options

engine = uci.popen_engine(options.path_to_engine)
engine.uci()

from .base import BaseHandler
from .index import IndexHandler
from .game import GameHandler
Пример #26
0
 def __init__(self):
     # Open stockfish engine and run it
     self.engine = uci.popen_engine(STOCKFISH_PATH)
     self.engine.uci()
Пример #27
0
#!/usr/bin/env python3

from chess import Board
from chess.uci import popen_engine
from flask import Flask, jsonify, request
import os

MOVE_MS = 1
DEPTH = 2

engine = popen_engine('stockfish')
engine.uci()

app = Flask(__name__)


@app.route('/find_move', methods=['POST'])
def make_move():
    req = request.get_json(force=True)
    try:
        board = Board(req['fen'])
    except (ValueError, KeyError):
        return '', 400
    engine.ucinewgame()
    engine.position(board)
    best_move = engine.go(movetime=MOVE_MS, depth=DEPTH)[0]
    board.push(best_move)
    return jsonify({
        'best_move': best_move.uci(),
    })
Пример #28
0
def chess_plugin(client, channel, nick, message, cmd, args):
    """

    Command for helga-chess.

    Usage:

    <bigjust> !chess board
    <helga> <url to dpaste.com>

    <bigjust> !chess newgame
    <helga> I chose black, white to move
    <helga> I chose white, e5

    Between each move, the game is saved and persisted on file.

    board and move commands always assume latest game in the
    gamefile. Multiple games will be stored per channel/user in
    history.
    """

    engine = uci.popen_engine(ENGINE)
    headers = OrderedDict()
    current_game = None

    game = load_game(channel)

    if not game:
        game = pgn.Game()

    board = game.end().board()

    if args[0] in ['newgame', 'move', 'board']:
        if args[0] == 'board':
            return 'http://localhost:8080/chess/{}/'.format(channel)

        if args[0] == 'move':
            if len(args) < 2:
                return 'usage: move e3e5'

            try:
                board.push(Move.from_uci(args[1]))
            except ValueError:
                return 'not a valid move. valid moves: {}'.format(', '.join(
                    [str(move) for move in board.legal_moves]))

            engine.position(board)
            move = engine.go(movetime=THINK_TIME).bestmove
            client.msg(channel, 'my move: {}'.format(str(move)))
            board.push(move)

        if args[0] == 'newgame':

            # setup a new game, choose a random side, persist after
            # setup(), and possibly first move
            engine.ucinewgame()
            board = Board()
            engine.position(board)

            next_round, stockfish_level = next_game_stats(channel)

            bot_turn = randrange(2)

            if not bot_turn:
                # we're white
                headers.update({
                    'White': NICK,
                    'Black': channel,
                })

                best_move = engine.go(movetime=THINK_TIME).bestmove
                board.push(best_move)
                next_turn = 'Black'

            else:
                headers.update({
                    'Black': NICK,
                    'White': channel,
                })
                next_turn = 'White'

            now = datetime.datetime.now()
            headers.update({
                'Date':
                '{}.{}.{}'.format(now.year, now.month, now.day),
                'Round':
                next_round,
                'Event':
                stockfish_level,
            })

            client.msg(channel, '{} to move'.format(next_turn))

        # persist the game
        game = pgn.Game.from_board(board)
        game.headers = headers
        save_game(channel, game)
Пример #29
0
from chess import uci, Move, Board

board = Board()
engine = uci.popen_engine("/Users/ben/src/Stockfish/src/stockfish")

while True:
    move = input("move: ")
    if move.startswith("fen "):
        board.set_fen(move[4:])
        continue
    board.push(Move.from_uci(move))
    engine.position(board)
    print(engine.go(depth=15))
Пример #30
0
    def __init__(self, engine, parent = None):
        super(DialogEngineOptions,self).__init__(parent)
        self.setWindowTitle(self.trUtf8("UCI Engine Options: ")+engine.name)

        # first parse all options form uci response
        eng = popen_engine(engine.path)
        command = eng.uci(async_callback=True)
        command.result(timeout=1.5)
        # eng.options
        # create sorted shallow copy
        eng_opts = []
        for key in eng.options:
            eng_opts.append(eng.options[key])
        eng_opts.sort(key=lambda x: x.name)

        self.optionWidgets = []
        grid = QGridLayout()
        count = len(eng.options)
        rowwidth = count/4
        x = 0
        y = 0
        for opt in eng_opts:
            #opt = eng.options[key]
            # add a widget for that option depending on its type
            # we will ignore options where the name starts with UCI_
            # or is one of the following:
            #   Hash, NalimovPath, NalimovCache, Ponder, Ownbook, MultiPV
            # (see UCI protocol specification)
            # in addition:
            # - for internal engine also block 'Skill Level' (handled at other place via GUI)
            # - settings of button type (maybe implement later, but for now we just
            #   save all settings, and send them to the views right before engine is
            #   activated via switching to resp. game mode, and not while in this dialog
            if not opt.name.startswith('UCI_') and not \
                (opt.name == 'Hash' or opt.name == 'NalimovPath' or \
                 opt.name == 'NalimovCache' or opt.name == 'Ponder' or \
                 opt.name == 'Ownbook' or opt.name =='MultiPV') and not \
                (type(engine) == InternalEngine and opt.name == 'Skill Level') and \
                not opt.type == 'button':

                if(y >= rowwidth):
                    y = 0
                    x += 1
                # crude way of adding spacing
                if(not y==0):
                    grid.addWidget(QLabel("    "),x,y)
                    y +=1

                # label for option
                lbl = QLabel(opt.name)
                grid.addWidget(lbl,x,y)
                # actual widget for manipulating value
                if opt.type == 'spin':
                    widget = QSpinBox()
                    widget.setMinimum(opt.min)
                    widget.setMaximum(opt.max)
                    if(engine.exists_option_value(opt.name)):
                        widget.setValue(engine.get_option_value(opt.name))
                    else:
                        widget.setValue(opt.default)
                elif opt.type == 'check':
                    widget = QCheckBox()
                    if(engine.exists_option_value(opt.name)):
                        widget.setChecked(engine.get_option_value(opt.name))
                    else:
                        widget.setChecked(opt.default)
                elif opt.type == 'combo':
                    widget = QComboBox()
                    if(engine.exists_option_value(opt.name)):
                        active_setting = engine.get_option_value(opt.name)
                    else:
                        active_setting = opt.default
                    for idx,val in enumerate(opt.var):
                        widget.addItem(val)
                        if(val == active_setting):
                            widget.setCurrentIndex(idx)
                #elif opt.type == 'button':
                #    widget = QPushButton(opt.name)
                elif opt.type == 'string':
                    widget = QLineEdit()
                    if(engine.exists_option_value(opt.name)):
                        active_setting = engine.get_option_value(opt.name)
                    else:
                        active_setting = opt.default
                    widget.setText(active_setting)
                y += 1
                grid.addWidget(widget,x,y)
                self.optionWidgets.append((opt,widget))
                y+=1
                #x+=1            #

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok| QDialogButtonBox.Cancel)
        vbox = QVBoxLayout()
        vbox.addLayout(grid)

        vbox.addWidget(self.HLine())
        #vbox.addLayout(hbox)
        vbox.addWidget(buttonBox)

        eng.quit()
        self.setLayout(vbox)

        self.connect(buttonBox, SIGNAL("accepted()"),self, SLOT("accept()"))
        self.connect(buttonBox, SIGNAL("rejected()"),self, SLOT("reject()"))
Пример #31
0
def runMatches():

    whiteEngine = False
    blackEngine = False
    engineDepth = 1
    engineNodes = 1
    engineMovetime = .0001

    ai_type = getInput(
        "White: 1 console, 2 minimax, 3 MonteCarlo, 4 stockfish", default='4')
    if ai_type == '1':
        white = AI.ConsoleAI()
    elif ai_type == '2':
        white = AI.Minimax_AI(int(getInput("Minimax Depth", default=3)))
    elif ai_type == '3':
        white = AI.MonteCarlo()
    elif ai_type == '4':
        whiteEngine = True
        white = uci.popen_engine('engines/stockfish')
        white.uci()

    ai_type = getInput(
        "Black: 1 console, 2 minimax, 3 MonteCarlo, 4 stockfish", default='4')
    if ai_type == '1':
        black = AI.ConsoleAI()
    elif ai_type == '2':
        black = AI.Minimax_AI(int(input("Minimax Depth: ")))
    elif ai_type == '3':
        black = AI.MonteCarlo()
    elif ai_type == '4':
        blackEngine = True
        black = uci.popen_engine('engines/stockfish')
        black.uci()

    log = getInput("Logging?", default='n')
    logging = False
    if log == 'y':
        logging = True

    num_games = int(getInput("Number of games", default=10))

    white_times = []
    black_times = []

    white_wins = 0
    black_wins = 0
    ties = 0

    for i in range(num_games):
        print("Playing game:", str(i + 1) + '/' + str(num_games))
        board = Board()
        while not board.is_stalemate() and not board.is_game_over():

            # Get and play White's move
            start = timeit.default_timer()
            if whiteEngine:
                white.position(copy.deepcopy(board))
                whiteMove = str(
                    white.go(movetime=engineMovetime,
                             depth=engineDepth,
                             nodes=engineNodes)[0])
            else:
                whiteMove = white.getMove(copy.deepcopy(board))
            stop = timeit.default_timer()
            white_times.append(stop - start)

            board.push_uci(whiteMove)
            if logging:
                print("White Move:", whiteMove)
                printBoard(board)

            # check if game over
            if board.is_stalemate() or board.is_game_over():
                break

            # Get and play Black's move
            start = timeit.default_timer()
            if blackEngine:
                black.position(copy.deepcopy(board))
                blackMove = str(
                    black.go(movetime=engineMovetime,
                             depth=engineDepth,
                             nodes=engineNodes)[0])
            else:
                blackMove = black.getMove(copy.deepcopy(board))
            stop = timeit.default_timer()
            black_times.append(stop - start)

            board.push_uci(blackMove)
            if logging:
                print("Black move:", blackMove)
                printBoard(board)

        print(board.result())
        if board.result() == '1-0':
            white_wins += 1
        elif board.result() == '0-1':
            black_wins += 1
        else:
            ties += 1

    print("======================================================")
    print("White:", str(white))
    print("Average move time:", sum(white_times) / len(white_times))
    print("Wins:", white_wins)
    print("======================================================")
    print("Black:", str(black))
    print("Average move time:", sum(black_times) / len(black_times))
    print("Wins:", black_wins)
    print("======================================================")
    print("Ties:", ties)
    print("======================================================")
Пример #32
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
Пример #33
0
Файл: RWO3.5.py Проект: n-p/RWO
 def open_engine_process(self):
     self.modified_engine = uci.popen_engine(self.modified_file_name)
     self.info_handler_modified = uci.InfoHandler()
     self.modified_engine.info_handlers.append(self.info_handler_modified)
Пример #34
0
 def __init__(self):
     self._engine = uci.popen_engine('stockfish')
     self._engine.uci()
Пример #35
0
    #Next, I add the desired errors, and voila, it works!
    #This is inefficient, but I'm not in the mood to extend Keras
    #Tee-hee-heee
    training_dict["out"] += np.ravel(current_evals)
    #print training_dict["out"].shape, all_errors.shape, all_errors
    model.train_on_batch(training_dict)

if __name__ == "__main__":
    usage = "usage katyushabinaryfile weightsfile positions"
    if len(argv) < 4:
        print usage
        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])
Пример #36
0
def set_up_engine(path=os.path.join(projdir, 'stockfish7')):
    engine = uci.popen_engine(path)
    engine.uci()
    return engine
Пример #37
0
    #This is inefficient, but I'm not in the mood to extend Keras
    #Tee-hee-heee
    training_dict["out"] += np.ravel(current_evals)
    #print training_dict["out"].shape, all_errors.shape, all_errors
    model.train_on_batch(training_dict)


if __name__ == "__main__":
    usage = "usage katyushabinaryfile weightsfile positions"
    if len(argv) < 4:
        print usage
        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
Пример #38
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)
Пример #39
0
def parse_engine_json(jsonfile):
    obj = json.load(jsonfile)
    engine = uci.popen_engine("/home/benjamin/Katyusha/" + obj["binary"])
    engine.setoption(obj["options"])
    engine.description = obj["description"]
    return engine
Пример #40
0
 def __init__(self):
     self.eng = uci.popen_engine("/usr/games/stockfish")
     self.eng.uci()