How to use the chess.uci.popen_engine function in chess

To help you get started, we’ve selected a few chess examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github emdoyle / chess_ai / wrapped_stockfish.py View on Github external
parser.add_argument("movetime", default=250, nargs='?')
parser.add_argument("--no_draw", action='store_true', help="Prevents engine from claiming draw.")
parser.add_argument("--gif", action='store_true', help="Save GIF of last played match.")
CLI_args = parser.parse_args()

GIF = CLI_args.gif

STRENGTH_1 = max(0, min(int(CLI_args.strength_levels[0]), 20))
STRENGTH_2 = max(0, min(int(CLI_args.strength_levels[1]), 20))

MOVETIME = CLI_args.movetime

CLAIM_DRAW = not CLI_args.no_draw

# Easily open a UCI connection to local stockfish
stockfish = uci.popen_engine(ROOT_DIR+"stockfish")
stockfish.uci()

stockfish.ucinewgame(lambda x: print("New Game Started"))

# Initialize game and board
game = chess.pgn.Game()
game.headers["White"] = stockfish.name
game.headers["Black"] = stockfish.name
board = chess.Board()
stockfish.position(board)
stockfish.setoption({'Threads': THREADS}, async_callback=
	(lambda x: print("Using "+str(THREADS)+" threads.")))

def update_strength(turn):
	if turn:
		stockfish.setoption({'Skill Level': STRENGTH_1})
github clarkerubber / Cheat-Net / main.py View on Github external
try:
    # Optionally fix colors on Windows and in journals if the colorama module
    # is available.
    import colorama
    wrapper = colorama.AnsiToWin32(sys.stdout)
    if wrapper.should_wrap():
        sys.stdout = wrapper.stream
except ImportError:
    pass

logging.basicConfig(format="%(message)s", level=settings.loglevel, stream=sys.stdout)
logging.getLogger("requests.packages.urllib3").setLevel(logging.WARNING)
logging.getLogger("chess.uci").setLevel(logging.WARNING)

engine = chess.uci.popen_engine(stockfish_command(False))
engine.setoption({'Threads': settings.threads, 'Hash': settings.memory})
engine.uci()
info_handler = chess.uci.InfoHandler()
engine.info_handlers.append(info_handler)


"""Start doing things"""

def collect_analyse_save(userId):
    try:
        player_data = get_player_data(userId, settings.token)
        playerAssessments = [PlayerAssessment(i) for i in player_data['assessment']['playerAssessments']]
        recents = recent_games(playerAssessments, player_data['games'])

        ap = AnalysedPlayer(
            userId,
github SamRagusa / Batch-First / playing_chess.py View on Github external
def __init__(self, engine_location, num_threads=1, move_time=15, print_search_info=False):
        """
        :param move_time: Either the time in milliseconds given to choose a move, or a size 2 tuple representing the
         range of possible time to give.  e.g. (100,1000) would randomly choose a time between 100 and 1000 ms
        """
        self.engine = chess.uci.popen_engine(engine_location)
        self.engine.setoption({"threads" : num_threads})

        self.info_handler = chess.uci.InfoHandler()
        self.engine.info_handlers.append(self.info_handler)

        self.move_time = move_time

        self.print_info = print_search_info
github ncksllvn / chess-api / app / handlers / __init__.py View on Github external
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
github CYHSM / chess-surprise-analysis / csa / csa.py View on Github external
def load_engine(engine_options=None):
    """Load engine for analysing games"""
    # Use the open-soure engine Stockfish
    engine = chess.uci.popen_engine('stockfish')
    # Important to use UCI (Universal Chess Interface)
    engine.uci()
    if engine_options:
        engine.setoption(engine_options)
    # Use an InfoHandler to save information about the analysis
    info_handler = chess.uci.InfoHandler()
    engine.info_handlers.append(info_handler)

    return engine
github clarkerubber / Cheat-Net / analyse.py View on Github external
try:
    # Optionally fix colors on Windows and in journals if the colorama module
    # is available.
    import colorama
    wrapper = colorama.AnsiToWin32(sys.stdout)
    if wrapper.should_wrap():
        sys.stdout = wrapper.stream
except ImportError:
    pass

logging.basicConfig(format="%(message)s", level=settings.loglevel, stream=sys.stdout)
logging.getLogger("requests.packages.urllib3").setLevel(logging.WARNING)
logging.getLogger("chess.uci").setLevel(logging.WARNING)

engine = chess.uci.popen_engine(stockfish_command())
engine.setoption({'Threads': settings.threads, 'Hash': settings.memory})
engine.uci()
info_handler = chess.uci.InfoHandler()
engine.info_handlers.append(info_handler)


"""Start importing players"""

cheaters = [
    'IMSomeOne',
    'Variogram',
    'TrapidFred',
    'toraman71',
    'strongulos',
    'langarita',
    'ahmedxchess',
github olinrobotics / hiro / hiro_archive / Fall_2018 / chess / movement.py View on Github external
def run(self):
        # main part
        print("Chess Movement running")
        #connect to pollux
        tcp_ip = "10.42.0.175"
        self.coordinator = urx.Robot(tcp_ip)

        #create initial chessboard with initial piece positions
        board = chess.Board()

        #connect stockfish engine with chess-python. Turns on engine so that program knows the engine is running
        engine = chess.uci.popen_engine("stockfish")
        engine.uci()
        #set initial engine position
        engine.position(board)

        #initialize number of dead pieces for each side
        num_b = 0
        num_w = 0

        #select mode before while loop starts
        switch = self.enter_mode()

        #opens the gripper
        self.open_grip()

        #runs program until the game is over
        while not board.is_game_over() and not rospy.is_shutdown():
github rpdelaney / python-chess-annotator / annotator.py View on Github external
- Attempt to classify the opening with ECO and identify the root node
        * The root node is the position immediately after the ECO classification
        * This allows us to skip analysis of moves that have an ECO classification
    - Analyze the game, adding annotations where appropriate
    - Return the root node with annotations
    """

    # First, check the game for PGN parsing errors
    # This is done so that we don't waste CPU time on nonsense games
    checkgame(game)

    ###########################################################################
    # Initialize the engine
    ###########################################################################
    try:
        engine = chess.uci.popen_engine(enginepath)
    except FileNotFoundError:
        errormsg = "Engine '{}' was not found. Aborting...".format(enginepath)
        logger.critical(errormsg)
        raise
    except PermissionError:
        errormsg = "Engine '{}' could not be executed. Aborting...".format(enginepath)
        logger.critical(errormsg)
        raise

    engine.uci()
    info_handler = chess.uci.InfoHandler()
    engine.info_handlers.append(info_handler)

    # Start keeping track of the root node
    # This will change if we successfully classify the opening
    root_node = game.end()

chess

A chess library with move generation and validation, Polyglot opening book probing, PGN reading and writing, Gaviota tablebase probing, Syzygy tablebase probing, and XBoard/UCI engine communication.

GPL-3.0
Latest version published 3 months ago

Package Health Score

82 / 100
Full package analysis