Ejemplo n.º 1
0
    def __init__(self,
                 variant,
                 initial_fen="",
                 chess960=False,
                 count_started=0,
                 disabled_fen=""):
        if variant == "shogun":
            sf.set_option("Protocol", "uci")
        self.variant = variant
        self.chess960 = chess960
        self.sfen = False
        self.show_promoted = variant in ("makruk", "makpong", "cambodian")
        self.initial_fen = initial_fen if initial_fen else self.start_fen(
            variant, chess960, disabled_fen)
        self.move_stack = []
        self.ply = 0
        self.color = WHITE if self.initial_fen.split()[1] == "w" else BLACK
        self.fen = self.initial_fen
        self.manual_count = count_started != 0
        self.count_started = count_started

        if self.variant == "janggi":
            self.notation = sf.NOTATION_JANGGI
        elif self.variant in CATEGORIES["shogi"]:
            self.notation = sf.NOTATION_SHOGI_HODGES_NUMBER
        elif self.variant in (
                "xiangqi",
                "minixiangqi"):  # XIANGQI_WXF can't handle Manchu banner!
            self.notation = sf.NOTATION_XIANGQI_WXF
        else:
            self.notation = sf.NOTATION_SAN
Ejemplo n.º 2
0
 def __init__(self, variant, initial_fen="", chess960=False):
     if variant == "shogun":
         sf.set_option("Protocol", "uci")
     self.variant = variant
     self.chess960 = chess960
     self.sfen = False
     self.show_promoted = variant == "makruk" or variant == "cambodian"
     self.initial_fen = initial_fen if initial_fen else self.start_fen(
         variant, chess960)
     self.move_stack = []
     self.color = WHITE if self.initial_fen.split()[1] == "w" else BLACK
     self.fen = self.initial_fen
     if chess960 and initial_fen == self.start_fen(variant):
         self.chess960 = False
Ejemplo n.º 3
0
import logging
import random
import string

from game import MAX_PLY

try:
    import pyffish as sf
    sf.set_option("VariantPath", "variants.ini")
except ImportError:
    print("No pyffish module installed!")

from broadcast import round_broadcast
from const import DRAW, STARTED, VARIANT_960_TO_PGN, INVALIDMOVE, VARIANTEND
from compress import decode_moves, R2C, C2R, V2C, C2V
from convert import mirror5, mirror9, usi2uci, zero2grand
from fairy import BLACK, STANDARD_FEN
from game import Game
from user import User
from settings import URI

log = logging.getLogger(__name__)


async def tv_game(db, app):
    """ Get latest played game id """
    if app["tv"] is not None:
        return app["tv"]
    else:
        game_id = None
        doc = await db.game.find_one({}, sort=[('$natural', -1)])
Ejemplo n.º 4
0
 def test_set_option(self):
     result = sf.set_option("UCI_Variant", "capablanca")
     self.assertIsNone(result)
Ejemplo n.º 5
0
    def runMatches(self,
                   variant: Variant,
                   matchCount=100,
                   debug=False,
                   variantPath: str = "") -> MatchData:
        """

        :param variant: The variant we want to run matches of.
        :param matchCount: The number of matches to run
        :param debug: If true, print debug statements
        :param variantPath: A path to the .ini file that contains the variant. If none is provided, one will be created.
        :return:
        """

        matchData = MatchData(variant)

        if variantPath == "" and not variant.builtIn:
            variantPath = "variant-{0}.ini".format(variant.name)
            with open(variantPath, "w") as ini:
                ini.write(variant.getFairyStockfishINI())

        pyffish.set_option("VariantPath", variantPath)

        for e in self.engines:
            # Set the engines to the variant we are running.
            e.setVariant(variant, variantPath)

        # This is the root of our MCT

        for matchNo in range(matchCount):

            match = Match(variant, (matchNo + 1))

            for e in self.engines:
                e.newgame()

            # Go through a MCTS opening

            stop = False
            curNode: MonteCarloTreeNode = matchData.MCTRoot

            while not stop:

                match.curNode = curNode
                stop, curNode = curNode.selectBestChild()

                if curNode is None:
                    # Checkmate or stalemate.

                    if pyffish.game_result(variant.name, variant.startingFEN,
                                           match.moves) == 0:
                        # Stalemate
                        match.markDraw()
                    elif i % 2 == 0:
                        match.markBlackVictory()
                    else:
                        match.markWhiteVictory()
                    break

                move = curNode.move
                match.addMove(move)

            # This is the loop that goes through the moves in any individual game
            while True:
                # Don't let too many moves happen!
                if len(match.moves) >= 1000:
                    match.markDraw()
                    break

                legal_moves = pyffish.legal_moves(variant.name,
                                                  variant.startingFEN,
                                                  match.moves)

                if len(legal_moves) == 0 and pyffish.game_result(
                        variant.name, variant.startingFEN, match.moves) == 0:
                    match.markDraw()
                    break
                elif pyffish.is_optional_game_end(variant.name,
                                                  variant.startingFEN,
                                                  match.moves)[0]:
                    match.markDraw()
                    break

                active_engine = self.engines[len(match.moves) % 2]
                inactive_engine = self.engines[(len(match.moves) + 1) % 2]

                active_engine.setposition(match.moves)
                moveDict = active_engine.bestmove()
                bestMove: str = moveDict["move"]
                ponder: str = moveDict["ponder"]
                info: str = moveDict["info"]
                match.addMove(bestMove)

                if debug:
                    print("{0}, move {1}, info {2}".format(
                        len(match.moves), bestMove, info))

                # If the engine found mate, then we can stop running through the steps.
                # TODO: This needs to be replaced with calls to pyffish.
                if 'mate' in moveDict.keys():
                    mateNum: int = moveDict['mate']
                    if mateNum in (1, 0):
                        # Somebody has checkmate, so find out who is the winner
                        if mateNum > 0:
                            winning = active_engine
                        else:
                            winning = inactive_engine

                        if winning == self.whiteEngine:
                            match.markWhiteVictory()
                        else:
                            match.markBlackVictory()
                        break
                # Add the matches we just played to the match data.
            matchData.addMatch(match)
            print(match)
        return matchData