def __init__(self, owner, regSVG, xml=None, nombre=None):

        QtWidgets.QDialog.__init__(self, owner)

        self.setWindowTitle(_("Image"))
        self.setWindowFlags(QtCore.Qt.Dialog | QtCore.Qt.WindowTitleHint)

        self.configuracion = VarGen.configuracion

        if not regSVG:
            regSVG = TabVisual.PSVG()
            regSVG.xml = xml
            if nombre:
                regSVG.nombre = nombre

        liAcciones = [
            (_("Save"), Iconos.Aceptar(), "grabar"),
            None,
            (_("Cancel"), Iconos.Cancelar(), "reject"),
            None,
        ]
        tb = Controles.TB(self, liAcciones)

        # Tablero
        confTablero = owner.tablero.confTablero
        self.tablero = Tablero.Tablero(self, confTablero, siDirector=False)
        self.tablero.crea()
        self.tablero.copiaPosicionDe(owner.tablero)

        # Datos generales
        liGen = []

        # nombre del svg que se usara en los menus del tutorial
        config = FormLayout.Editbox(_("Name"), ancho=120)
        liGen.append((config, regSVG.nombre))

        # ( "opacidad", "n", 1.0 ),
        config = FormLayout.Dial(_("Degree of transparency"), 0, 99)
        liGen.append((config, 100 - int(regSVG.opacidad * 100)))

        # ( "psize", "n", 100 ),
        config = FormLayout.Spinbox(_("Size") + " %", 1, 1600, 50)
        liGen.append((config, regSVG.psize))

        # orden
        config = FormLayout.Combobox(_("Order concerning other items"),
                                     QTUtil2.listaOrdenes())
        liGen.append((config, regSVG.posicion.orden))

        self.form = FormLayout.FormWidget(liGen, dispatch=self.cambios)

        # Layout
        layout = Colocacion.H().control(self.form).relleno().control(
            self.tablero)
        layout1 = Colocacion.V().control(tb).otro(layout)
        self.setLayout(layout1)

        # Ejemplos
        liMovs = ["b4c4", "e2e2", "e4g7"]
        self.liEjemplos = []
        for a1h8 in liMovs:
            regSVG.a1h8 = a1h8
            regSVG.siMovible = True
            svg = self.tablero.creaSVG(regSVG, siEditando=True)
            self.liEjemplos.append(svg)
    def editar(self, una, icono):
        if una is None:
            una = {}

        # Datos basicos
        liGen = [(None, None)]
        liGen.append((FormLayout.Editbox(_("Name")), una.get("NOMBRE", "")))

        liGen.append((None, None))

        config = FormLayout.Fichero(_("Debug file"), "txt", True)
        liGen.append((config, una.get("DEBUG", "")))

        liGen.append((None, None))

        liGen.append((None, _("Serious errors, select the best move if:")))
        liGen.append((FormLayout.Editbox(_("Mate is less than or equal to"),
                                         tipo=int,
                                         ancho=50), una.get("MAXMATE", 0)))
        liGen.append(
            (FormLayout.Editbox(_("The loss of points is greater than"),
                                tipo=int,
                                ancho=50), una.get("MINDIFPUNTOS", 0)))
        liGen.append((None, None))
        liGen.append((FormLayout.Editbox(_(
            "Max. loss of points per move by the <br> engine to reach a leveled evaluation"
        ),
                                         tipo=int,
                                         ancho=50), una.get("ATERRIZAJE", 50)))

        # Apertura
        liA = [(None, None)]

        config = FormLayout.Fichero(_("Polyglot book"), "bin", False)
        liA.append((config, una.get("BOOK", "")))

        # Medio juego
        liMJ = [(None, None)]

        # # Ajustar
        liMJ.append((FormLayout.Combobox(_("Strength"),
                                         self.listaAjustes(False)),
                     una.get("AJUSTAR", kAjustarMejor)))

        # Movimiento siguiente
        liMJ.append((None, _("In the next move")))

        trlistaSG = [
            _("To move a pawn"),
            _("Advance piece"),
            _("Make check"),
            _("Capture")
        ]
        listaSG = ["MOVERPEON", "AVANZARPIEZA", "JAQUE", "CAPTURAR"]
        for n, opcion in enumerate(listaSG):
            liMJ.append((FormLayout.Spinbox(trlistaSG[n], -2000, +2000,
                                            50), una.get(opcion, 0)))

        # Movimientos previstos
        liMJ.append((None, _("In the expected moves")))
        trlistaPR = [
            _("Keep the two bishops"),
            _("Advance"),
            _("Make check"),
            _("Capture")
        ]
        listaPR = ["2B", "AVANZAR", "JAQUE", "CAPTURAR"]
        for n, opcion in enumerate(listaPR):
            liMJ.append((FormLayout.Spinbox(trlistaPR[n], -2000, +2000,
                                            50), una.get(opcion + "PR", 0)))

        # Final
        liF = [(None, None)]

        # Ajustar
        liF.append((FormLayout.Combobox(_("Strength"),
                                        self.listaAjustes(False)),
                    una.get("AJUSTARFINAL", kAjustarMejor)))

        liF.append((FormLayout.Spinbox(_("Maximum pieces at this stage"), 0,
                                       32, 50), una.get("MAXPIEZASFINAL", 0)))
        liF.append((None, None))

        # Movimiento siguiente
        liF.append((None, _("In the next move")))
        for n, opcion in enumerate(listaSG):
            liF.append((FormLayout.Spinbox(trlistaSG[n], -2000, +2000,
                                           50), una.get(opcion + "F", 0)))

        # Movimientos previstos
        liF.append((None, _("In the expected moves")))
        for n, opcion in enumerate(listaPR):
            liF.append((FormLayout.Spinbox(trlistaPR[n], -2000, +2000,
                                           50), una.get(opcion + "PRF", 0)))

        while True:
            lista = []
            lista.append((liGen, _("Basic data"), ""))
            lista.append((liA, _("Opening"), ""))
            lista.append((liMJ, _("Middlegame"), ""))
            lista.append((liF, _("Endgame"), ""))
            resultado = FormLayout.fedit(lista,
                                         title=_("Personalities"),
                                         parent=self.owner,
                                         anchoMinimo=460,
                                         icon=icono)
            if resultado:
                accion, liResp = resultado
                liGenR, liAR, liMJR, liFR = liResp

                nombre = liGenR[0].strip()

                if not nombre:
                    QTUtil2.mensError(self.owner, _("Missing name"))
                    continue

                una = {}
                # Base
                una["NOMBRE"] = nombre
                una["DEBUG"] = liGenR[1]
                una["MAXMATE"] = liGenR[2]
                una["MINDIFPUNTOS"] = liGenR[3]
                una["ATERRIZAJE"] = liGenR[4]

                # Apertura
                una["BOOK"] = liAR[0]

                # Medio
                una["AJUSTAR"] = liMJR[0]

                for num, opcion in enumerate(listaSG):
                    una[opcion] = liMJR[num + 1]

                nSG = len(listaSG) + 1
                for num, opcion in enumerate(listaPR):
                    una[opcion + "PR"] = liMJR[num + nSG]

                # Final
                una["AJUSTARFINAL"] = liFR[0]
                una["MAXPIEZASFINAL"] = liFR[1]

                for num, opcion in enumerate(listaSG):
                    una[opcion + "F"] = liFR[num + 2]

                nSG = len(listaSG) + 2
                for num, opcion in enumerate(listaPR):
                    una[opcion + "PRF"] = liFR[num + nSG]

                return una

            return None
    def new(self):
        recno = self.ghistorico.recno()
        if recno >= 0:
            key = self.liHistorico[recno]
            reg = self.historico[key]
            sitePre = reg["SITE"]
            intervaloPre = reg["INTERVAL"]
            intervaloPorPiezaPre = reg["INTERVALPIECE"]
            esatacadaPre = reg["ISATTACKED"]
            esatacantePre = reg["ISATTACKING"]
            posicionPre = reg["POSITION"]
            colorPre = reg["COLOR"]
        else:
            recno = 0
            sitePre = None
            intervaloPre = 3
            intervaloPorPiezaPre = True
            esatacadaPre = False
            esatacantePre = False
            posicionPre = False
            colorPre = False

        # Datos
        liGen = [(None, None)]

        # # Site
        f = open(self.path_bloque)
        liData = [x.split("|") for x in f.read().split("\n")]
        f.close()
        liSites = []
        sitePreNum = -1
        for n, uno in enumerate(liData):
            site = uno[0]
            if site:
                if sitePre and site == sitePre:
                    sitePreNum = n
                liSites.append((site, n))
        liSites = sorted(liSites, key=lambda st: st[0])
        config = FormLayout.Combobox(_("Site"), liSites)
        if sitePreNum == -1:
            sitePreNum = liSites[0][0]
        liGen.append((config, sitePreNum))

        liGen.append((None, None))

        # # Intervals
        liGen.append((None, _("Seconds of every glance") + ":"))
        liGen.append((FormLayout.Spinbox(_("Seconds"), 1, 100,
                                         50), intervaloPre))

        liTypes = ((_("By piece"), True), (_("Fixed"), False))
        config = FormLayout.Combobox(_("Type"), liTypes)
        liGen.append((config, intervaloPorPiezaPre))

        liGen.append((None, None))

        liGen.append((None, _("Ask for") + ":"))
        liGen.append((_("Position") + ":", posicionPre))
        liGen.append((_("Square color") + ":", colorPre))
        liGen.append((_("Is attacked?") + ":", esatacadaPre))
        liGen.append((_("Is attacking?") + ":", esatacantePre))

        resultado = FormLayout.fedit(liGen,
                                     title=_("Configuration"),
                                     parent=self,
                                     icon=Iconos.Gafas(),
                                     anchoMinimo=360)
        if resultado:
            accion, liGen = resultado

            siteNum, \
            intervalo, intervaloPorPieza, \
            posicion, color, esatacada, esatacante = liGen

            dicdatos = {}
            f = dicdatos["DATE"] = Util.hoy()
            dicdatos["FENS"] = liData[siteNum][1:]
            dicdatos["SITE"] = liData[siteNum][0]
            dicdatos["INTERVAL"] = intervalo
            dicdatos["INTERVALPIECE"] = intervaloPorPieza
            dicdatos["ISATTACKED"] = esatacada
            dicdatos["ISATTACKING"] = esatacante
            dicdatos["POSITION"] = posicion
            dicdatos["COLOR"] = color
            dicdatos["ERRORS"] = 0
            dicdatos["TIME"] = 0
            dicdatos["LEVEL"] = 1

            key = Util.dtosext(f)
            self.historico[key] = dicdatos
            self.liHistorico.insert(0, key)
            self.ghistorico.refresh()
            self.ghistorico.gotop()

            self.work(recno)
def paramAnalisisMasivo(parent,
                        configuracion,
                        siVariosSeleccionados,
                        siDatabase=False):
    alm = leeDicParametros(configuracion)

    # Datos
    liGen = [SEPARADOR]

    # # Tutor
    li = configuracion.ayudaCambioTutor()
    li[0] = alm.motor
    liGen.append((_("Engine") + ":", li))

    liGen.append(SEPARADOR)

    # # Time
    config = FormLayout.Editbox(_("Duration of engine analysis (secs)"),
                                40,
                                tipo=float)
    liGen.append((config, alm.tiempo / 1000.0))

    # Depth
    liDepths = [("--", 0)]
    for x in range(1, 31):
        liDepths.append((str(x), x))
    config = FormLayout.Combobox(_("Depth"), liDepths)
    liGen.append((config, alm.depth))

    # Time+Depth
    liGen.append(("%s+%s:" % (_("Time"), _("Depth")), alm.timedepth))

    # MultiPV
    liGen.append(SEPARADOR)
    li = [(_("Default"), "PD"), (_("Maximum"), "MX")]
    for x in (1, 3, 5, 10, 15, 20, 30, 40, 50, 75, 100, 150, 200):
        li.append((str(x), str(x)))
    config = FormLayout.Combobox(
        _("Number of moves evaluated by engine(MultiPV)"), li)
    liGen.append((config, alm.multiPV))
    liGen.append(SEPARADOR)

    liJ = [(_("White"), "BLANCAS"), (_("Black"), "NEGRAS"),
           (_("White & Black"), "AMBOS")]
    config = FormLayout.Combobox(_("Analyze only color"), liJ)
    liGen.append((config, "AMBOS"))

    liGen.append(
        ("<div align=\"right\">" + _("Only player moves") + ":<br>%s</div>" %
         _("(You can add multiple aliases separated by ; and wildcard * )"),
         ""))

    fvar = configuracion.ficheroBooks
    listaLibros = Books.ListaLibros()
    listaLibros.recuperaVar(fvar)
    # Comprobamos que todos esten accesibles
    listaLibros.comprueba()
    defecto = listaLibros.lista[0]
    li = [("--", None)]
    for libro in listaLibros.lista:
        if libro.nombre == alm.libro:
            defecto = libro
        li.append((libro.nombre, libro))
    config = FormLayout.Combobox(
        _("Do not scan the opening moves based on book"), li)
    liGen.append((config, defecto))

    liGen.append((_("Start from the end of the game") + ":", alm.desdeelfinal))

    liGen.append(SEPARADOR)
    liGen.append((_("Only selected games") + ":", siVariosSeleccionados))

    liBlunders, liBrilliancies = formBlundersBrilliancies(alm, configuracion)

    lista = []
    lista.append((liGen, _("General options"), ""))
    lista.append((liBlunders, _("Wrong moves"), ""))
    lista.append((liBrilliancies, _("Brilliancies"), ""))

    reg = Util.Almacen()
    reg.form = None

    def dispatchR(valor):
        if reg.form is None:
            if isinstance(valor, FormLayout.FormTabWidget):
                reg.form = valor
                reg.wtime = valor.getWidget(0, 1)
                reg.wdepth = valor.getWidget(0, 2)
                reg.wdt = valor.getWidget(0, 3)
            elif isinstance(valor, FormLayout.FormWidget):
                reg.form = valor
                reg.wtime = valor.getWidget(1)
                reg.wdepth = valor.getWidget(2)
                reg.wdt = valor.getWidget(3)
        else:
            sender = reg.form.sender()
            if not reg.wdt.isChecked():
                if sender == reg.wtime:
                    if reg.wtime.textoFloat() > 0:
                        reg.wdepth.setCurrentIndex(0)
                elif sender == reg.wdepth:
                    if reg.wdepth.currentIndex() > 0:
                        reg.wtime.ponFloat(0.0)
                elif sender == reg.wdt:
                    if reg.wtime.textoFloat() > 0:
                        reg.wdepth.setCurrentIndex(0)
                    elif reg.wdepth.currentIndex() > 0:
                        reg.wtime.ponFloat(0.0)

                QTUtil.refreshGUI()

    resultado = FormLayout.fedit(lista,
                                 title=_("Mass analysis"),
                                 parent=parent,
                                 anchoMinimo=460,
                                 icon=Iconos.Opciones(),
                                 dispatch=dispatchR)

    if resultado:
        accion, liResp = resultado

        liGen, liBlunders, liBrilliancies = liResp

        alm.motor = liGen[0]
        alm.tiempo = int(liGen[1] * 1000)
        alm.depth = liGen[2]
        alm.timedepth = liGen[3]
        alm.multiPV = liGen[4]

        color = liGen[5]
        alm.blancas = color != "NEGRAS"
        alm.negras = color != "BLANCAS"

        cjug = liGen[6].strip()
        alm.liJugadores = cjug.upper().split(";") if cjug else None

        alm.libroAperturas = liGen[7]
        alm.libro = alm.libroAperturas.nombre if alm.libroAperturas is not None else None

        alm.desdeelfinal = liGen[8]

        alm.siVariosSeleccionados = liGen[9]

        alm.kblunders = liBlunders[0]
        alm.tacticblunders = liBlunders[1]
        alm.pgnblunders = liBlunders[2]
        alm.oriblunders = liBlunders[3]
        alm.bmtblunders = liBlunders[4]

        alm.dpbrilliancies = liBrilliancies[0]
        alm.ptbrilliancies = liBrilliancies[1]
        alm.fnsbrilliancies = liBrilliancies[2]
        alm.pgnbrilliancies = liBrilliancies[3]
        alm.oribrilliancies = liBrilliancies[4]
        alm.bmtbrilliancies = liBrilliancies[5]

        dic = {}
        for x in dir(alm):
            if not x.startswith("__"):
                dic[x.upper()] = getattr(alm, x)
        Util.guardaVar(configuracion.ficheroAnalisis, dic)

        if not (alm.tacticblunders or alm.pgnblunders or alm.bmtblunders
                or alm.fnsbrilliancies or alm.pgnbrilliancies
                or alm.bmtbrilliancies or siDatabase):
            QTUtil2.mensError(parent,
                              _("No file was specified where to save results"))
            return

        return alm
    else:
        return None
Example #5
0
def nuevaKibitzer(ventana, configuracion):
    # Datos generales
    liGen = [(None, None)]

    # # Nombre
    liGen.append((_("Kibitzer") + ":", ""))

    ## Motor
    config = FormLayout.Combobox(_("Engine"),
                                 configuracion.comboMotoresCompleto())
    liGen.append((config, "stockfish"))

    ## Tipo
    liTipos = [
        "M",
        ("M", _("Candidates")),
        ("I", _("Indexes")),
        ("S", _("Best move")),
        ("L", _("Best move in one line")),
        ("J", _("Select move")),
        ("C", _("Threats")),
    ]
    liGen.append((_("Type"), liTipos))

    # Editamos
    resultado = FormLayout.fedit(liGen,
                                 title=_("New"),
                                 parent=ventana,
                                 anchoMinimo=460,
                                 icon=Iconos.Kibitzer())

    if resultado:
        accion, resp = resultado

        kibitzer = resp[0]
        motor = resp[1]
        tipo = resp[2]
        if not kibitzer:
            for xtipo, txt in liTipos[1:]:
                if xtipo == tipo:
                    kibitzer = "%s: %s" % (txt, motor)

        d = datetime.datetime.now()
        id = "MOS" + d.isoformat()[2:].strip("0").replace("-", "").replace(
            "T", "").replace(":", "").replace(".", "")
        fvideo = configuracion.plantillaVideo % id

        dic = {
            "NOMBRE": kibitzer,
            "MOTOR": motor,
            "TIPO": tipo,
            "FVIDEO": fvideo
        }

        liKibitzers = listaKibitzersRecuperar(configuracion)
        liKibitzers.append(dic)

        listaKibitzersGrabar(configuracion, liKibitzers)

        return liKibitzers
    else:
        return None
def paramAnalisis(parent, configuracion, siModoAmpliado, siTodosMotores=False):
    alm = leeDicParametros(configuracion)

    # Datos
    liGen = [SEPARADOR]

    # # Tutor
    if siTodosMotores:
        li = configuracion.ayudaCambioCompleto(alm.motor)
    else:
        li = configuracion.ayudaCambioTutor()
        li[0] = alm.motor
    liGen.append((_("Engine") + ":", li))

    # # Time
    liGen.append(SEPARADOR)
    config = FormLayout.Editbox(_("Duration of engine analysis (secs)"),
                                40,
                                tipo=float)
    liGen.append((config, alm.tiempo / 1000.0))

    # Depth
    liDepths = [("--", 0)]
    for x in range(1, 51):
        liDepths.append((str(x), x))
    config = FormLayout.Combobox(_("Depth"), liDepths)
    liGen.append((config, alm.depth))

    # Time+Depth
    liGen.append(("%s+%s:" % (_("Time"), _("Depth")), alm.timedepth))

    # MultiPV
    liGen.append(SEPARADOR)
    li = [(_("Default"), "PD"), (_("Maximum"), "MX")]
    for x in (1, 3, 5, 10, 15, 20, 30, 40, 50, 75, 100, 150, 200):
        li.append((str(x), str(x)))
    config = FormLayout.Combobox(
        _("Number of moves evaluated by engine(MultiPV)"), li)
    liGen.append((config, alm.multiPV))

    # Priority
    liGen.append(SEPARADOR)
    config = FormLayout.Combobox(_("Process priority"),
                                 EngineThread.priorities.combo())
    liGen.append((config, alm.priority))

    # Completo
    if siModoAmpliado:
        liGen.append(SEPARADOR)

        liJ = [(_("White"), "BLANCAS"), (_("Black"), "NEGRAS"),
               (_("White & Black"), "AMBOS")]
        config = FormLayout.Combobox(_("Analyze only color"), liJ)
        liGen.append((config, "AMBOS"))

        config = FormLayout.Editbox("<div align=\"right\">" + _("Moves") +
                                    "<br>" + _("By example:") +
                                    " -5,8-12,14,19-",
                                    rx="[0-9,\-,\,]*")
        liGen.append((config, ""))

        fvar = configuracion.ficheroBooks
        listaLibros = Books.ListaLibros()
        listaLibros.recuperaVar(fvar)
        # Comprobamos que todos esten accesibles
        listaLibros.comprueba()
        li = [("--", None)]
        defecto = listaLibros.lista[0] if alm.libro else None
        for libro in listaLibros.lista:
            if alm.libro == libro.nombre:
                defecto = libro
            li.append((libro.nombre, libro))
        config = FormLayout.Combobox(
            _("Do not scan the opening moves based on book"), li)
        liGen.append((config, defecto))
        liGen.append(SEPARADOR)

        liGen.append(
            (_("Redo any existing prior analyses (if they exist)") + ":",
             alm.siBorrarPrevio))

        liGen.append(
            (_("Start from the end of the game") + ":", alm.desdeelfinal))

        liGen.append(SEPARADOR)

        liGen.append((_("Show graphics") + ":", alm.showGraphs))

        liVar = [SEPARADOR]
        liVar.append((_("Add analysis to variants") + ":", alm.masvariantes))
        liVar.append(SEPARADOR)

        liVar.append((FormLayout.Spinbox(_("Minimum points lost"), 0, 1000,
                                         60), alm.limitemasvariantes))
        liVar.append(SEPARADOR)

        liVar.append((_("Only add better variant") + ":", alm.mejorvariante))
        liVar.append(SEPARADOR)

        liVar.append((_("Include info about engine") + ":", alm.infovariante))
        liVar.append(SEPARADOR)

        liVar.append(
            ("%s %s/%s/%s:" %
             (_("Format"), _("Points"), _("Depth"), _("Time")), alm.siPDT))
        liVar.append(SEPARADOR)

        liVar.append(
            (_("Only one move of each variant") + ":", alm.unmovevariante))

        liBlunders, liBrilliancies = formBlundersBrilliancies(
            alm, configuracion)

        liST = [SEPARADOR]
        liST.append((_("Activate") + ":", alm.stability))
        liST.append(SEPARADOR)
        liST.append(
            (FormLayout.Spinbox(_("Last depths to control same best move"), 2,
                                10, 40), alm.st_depths))
        liST.append(SEPARADOR)
        liST.append(
            (FormLayout.Spinbox(_("Maximum difference among last evaluations"),
                                0, 99999, 60), alm.st_centipawns))
        liST.append(SEPARADOR)
        liST.append((FormLayout.Spinbox(_("Additional time limit"), 0, 99999,
                                        60), alm.st_timelimit))

        lista = []
        lista.append((liGen, _("General options"), ""))
        lista.append((liVar, _("Variants"), ""))
        lista.append((liBlunders, _("Wrong moves"), ""))
        lista.append((liBrilliancies, _("Brilliancies"), ""))
        lista.append((liST, _("Stability control"), ""))

    else:
        lista = liGen

    reg = Util.Almacen()
    reg.form = None

    def dispatchR(valor):
        if reg.form is None:
            if isinstance(valor, FormLayout.FormTabWidget):
                reg.form = valor
                reg.wtime = valor.getWidget(0, 1)
                reg.wdepth = valor.getWidget(0, 2)
                reg.wdt = valor.getWidget(0, 3)
            elif isinstance(valor, FormLayout.FormWidget):
                reg.form = valor
                reg.wtime = valor.getWidget(1)
                reg.wdepth = valor.getWidget(2)
                reg.wdt = valor.getWidget(3)
        else:
            sender = reg.form.sender()
            if not reg.wdt.isChecked():
                if sender == reg.wtime:
                    if reg.wtime.textoFloat() > 0:
                        reg.wdepth.setCurrentIndex(0)
                elif sender == reg.wdepth:
                    if reg.wdepth.currentIndex() > 0:
                        reg.wtime.ponFloat(0.0)
                elif sender == reg.wdt:
                    if reg.wtime.textoFloat() > 0:
                        reg.wdepth.setCurrentIndex(0)
                    elif reg.wdepth.currentIndex() > 0:
                        reg.wtime.ponFloat(0.0)

                QTUtil.refreshGUI()

    resultado = FormLayout.fedit(lista,
                                 title=_("Analysis Configuration"),
                                 parent=parent,
                                 anchoMinimo=460,
                                 icon=Iconos.Opciones(),
                                 dispatch=dispatchR)

    if resultado:
        accion, liResp = resultado

        if siModoAmpliado:
            liGen, liVar, liBlunders, liBrilliancies, liST = liResp
        else:
            liGen = liResp

        alm.motor = liGen[0]
        alm.tiempo = int(liGen[1] * 1000)
        alm.depth = liGen[2]
        alm.timedepth = liGen[3]
        alm.multiPV = liGen[4]
        alm.priority = liGen[5]

        if siModoAmpliado:
            color = liGen[6]
            alm.blancas = color != "NEGRAS"
            alm.negras = color != "BLANCAS"
            alm.jugadas = liGen[7]
            alm.libroAperturas = liGen[8]
            alm.libro = alm.libroAperturas.nombre if alm.libroAperturas else None
            alm.siBorrarPrevio = liGen[9]
            alm.desdeelfinal = liGen[10]
            alm.showGraphs = liGen[11]

            (alm.masvariantes, alm.limitemasvariantes, alm.mejorvariante,
             alm.infovariante, alm.siPDT, alm.unmovevariante) = liVar

            (alm.kblunders, alm.tacticblunders, alm.pgnblunders,
             alm.oriblunders, alm.bmtblunders) = liBlunders

            (alm.dpbrilliancies, alm.ptbrilliancies, alm.fnsbrilliancies,
             alm.pgnbrilliancies, alm.oribrilliancies,
             alm.bmtbrilliancies) = liBrilliancies

            (alm.stability, alm.st_depths, alm.st_centipawns,
             alm.st_timelimit) = liST

        dic = {}
        for x in dir(alm):
            if not x.startswith("__"):
                dic[x.upper()] = getattr(alm, x)
        Util.guardaVar(configuracion.ficheroAnalisis, dic)

        return alm
    else:
        return None
Example #7
0
    def trainNewEngines(self):
        training = self.dbop.trainingEngines()
        color = "WHITE"
        basepv = self.dbop.basePV
        mandatory = basepv.count(" ") + 1 if len(basepv) > 0 else 0
        control = 10
        lost_points = 20
        engine_control = self.configuracion.tutor.clave
        engine_time = 5.0
        num_engines = 20
        key_engine = "alaric"

        if training is not None:
            color = training["COLOR"]
            mandatory = training.get("MANDATORY", mandatory)
            control = training.get("CONTROL", control)
            lost_points = training.get("LOST_POINTS", lost_points)
            engine_control = training.get("ENGINE_CONTROL", engine_control)
            engine_time = training.get("ENGINE_TIME", engine_time)
            num_engines = training.get("NUM_ENGINES", num_engines)
            key_engine = training.get("KEY_ENGINE", key_engine)

        separador = FormLayout.separador
        liGen = [separador]

        liJ = [(_("White"), "WHITE"), (_("Black"), "BLACK")]
        config = FormLayout.Combobox(_("Play with"), liJ)
        liGen.append((config, color))

        liGen.append((_("Mandatory moves") + ":", mandatory))
        liGen.append(separador)
        liGen.append((_("Moves until the control") + ":", control))
        liGen.append(separador)
        liGen.append(
            (_("Maximum number of centipawns lost to pass control") + ":",
             lost_points))
        liGen.append(separador)

        dicRivales = self.configuracion.dicRivales
        dicRivales = EnginesBunch.filtra(dicRivales)
        config = FormLayout.Spinbox(_("Number of engines"), 2, len(dicRivales),
                                    50)
        liGen.append((config, num_engines))

        likeys = [(dicRivales[x].nombre, x) for x in dicRivales]
        likeys.sort(key=lambda x: x[1])
        config = FormLayout.Combobox(_("Bunch of engines"), likeys)
        liGen.append((config, key_engine))
        liGen.append(separador)

        config = FormLayout.Combobox(_("Engine that does the control"),
                                     self.configuracion.comboMotoresCompleto())
        liGen.append((config, engine_control))
        liGen.append(
            (_("Duration of analysis (secs)") + ":", float(engine_time)))

        resultado = FormLayout.fedit(liGen,
                                     title=_("With engines"),
                                     parent=self,
                                     anchoMinimo=360,
                                     icon=Iconos.Study())
        if resultado is None:
            return

        accion, liResp = resultado

        reg = {}

        (reg["COLOR"], reg["MANDATORY"], reg["CONTROL"], reg["LOST_POINTS"],
         reg["NUM_ENGINES"], reg["KEY_ENGINE"], reg["ENGINE_CONTROL"],
         reg["ENGINE_TIME"]) = liResp

        self.dbop.createTrainingEngines(reg, self.procesador)

        QTUtil2.mensaje(self, _("Created"))
Example #8
0
    def ta_massive(self):
        dicVar = self.configuracion.leeVariables("MASSIVE_OLINES")

        liGen = [FormLayout.separador]

        config = FormLayout.Combobox(
            _("Engine"), self.configuracion.comboMotoresMultiPV10(4))
        liGen.append((config, dicVar.get("ENGINE", self.configuracion.tutor)))

        liGen.append(
            (_("Duration of engine analysis (secs)") + ":",
             dicVar.get("SEGUNDOS",
                        float(self.configuracion.tiempoTutor / 1000.0))))
        liDepths = [("--", 0)]
        for x in range(1, 51):
            liDepths.append((str(x), x))
        config = FormLayout.Combobox(_("Depth"), liDepths)
        liGen.append((config, dicVar.get("DEPTH",
                                         self.configuracion.depthTutor)))

        li = [(_("Maximum"), 0)]
        for x in (1, 3, 5, 10, 15, 20, 30, 40, 50, 75, 100, 150, 200):
            li.append((str(x), x))
        config = FormLayout.Combobox(
            _("Number of moves evaluated by engine(MultiPV)"), li)
        liGen.append(
            (config, dicVar.get("MULTIPV", self.configuracion.tutorMultiPV)))

        liGen.append(FormLayout.separador)
        liGen.append(
            (_("Redo any existing prior analyses (if they exist)") + ":",
             dicVar.get("REDO", False)))

        resultado = FormLayout.fedit(liGen,
                                     title=_("Mass analysis"),
                                     parent=self,
                                     anchoMinimo=460,
                                     icon=Iconos.Analizar())
        if resultado is None:
            return

        claveMotor, tiempo, depth, multiPV, redo = resultado[1]
        ms = int(tiempo * 1000)
        if ms == 0 and depth == 0:
            return

        dicVar["ENGINE"] = claveMotor
        dicVar["SEGUNDOS"] = tiempo
        dicVar["DEPTH"] = depth
        dicVar["MULTIPV"] = multiPV
        dicVar["REDO"] = redo
        self.configuracion.escVariables("MASSIVE_OLINES", dicVar)

        um = QTUtil2.unMomento(self)
        stFensM2 = self.dbop.getAllFen()
        if redo == False:
            liBorrar = []
            for fenM2 in stFensM2:
                dic = self.dbop.getfenvalue(fenM2)
                if "ANALISIS" in dic:
                    liBorrar.append(fenM2)
            for fenM2 in liBorrar:
                stFensM2.remove(fenM2)

        conf_engine = copy.deepcopy(self.configuracion.buscaMotor(claveMotor))
        conf_engine.actMultiPV(multiPV)
        xgestor = self.procesador.creaGestorMotor(conf_engine, ms, depth, True)

        um.final()

        mensaje = _("Move") + "  %d/" + str(len(stFensM2))
        tmpBP = QTUtil2.BarraProgreso(self, _("Mass analysis"), "",
                                      len(stFensM2))

        done = 0

        for n, fenM2 in enumerate(stFensM2, 1):

            if tmpBP.siCancelado():
                break

            tmpBP.inc()
            tmpBP.mensaje(mensaje % n)

            mrm = xgestor.analiza(fenM2 + " 0 1")
            dic = self.dbop.getfenvalue(fenM2)
            dic["ANALISIS"] = mrm
            self.dbop.setfenvalue(fenM2, dic)
            done += 1

        tmpBP.cerrar()
Example #9
0
def crearTactic(procesador, wowner, liRegistros, rutinaDatos):
    # Se pide el nombre de la carpeta
    liGen = [(None, None)]

    liGen.append((_("Name") + ":", ""))

    liGen.append((None, None))

    liJ = [(_("Default"), 0), (_("White"), 1), (_("Black"), 2)]
    config = FormLayout.Combobox(_("Point of view"), liJ)
    liGen.append((config, 0))

    eti = _("Create tactics training")
    resultado = FormLayout.fedit(liGen,
                                 title=eti,
                                 parent=wowner,
                                 anchoMinimo=460,
                                 icon=Iconos.Tacticas())

    if not resultado:
        return
    accion, liGen = resultado
    menuname = liGen[0].strip()
    if not menuname:
        return
    pointview = str(liGen[1])

    restDir = Util.validNomFichero(menuname)
    nomDir = os.path.join(VarGen.configuracion.dirPersonalTraining, "Tactics",
                          restDir)
    nomIni = os.path.join(nomDir, "Config.ini")
    if os.path.isfile(nomIni):
        dicIni = Util.ini8dic(nomIni)
        n = 1
        while True:
            if "TACTIC%d" % n in dicIni:
                if "MENU" in dicIni["TACTIC%d" % n]:
                    if dicIni["TACTIC%d" %
                              n]["MENU"].upper() == menuname.upper():
                        break
                else:
                    break
                n += 1
            else:
                break
        nomTactic = "TACTIC%d" % n
    else:
        nomDirTac = os.path.join(VarGen.configuracion.dirPersonalTraining,
                                 "Tactics")
        Util.creaCarpeta(nomDirTac)
        Util.creaCarpeta(nomDir)
        nomTactic = "TACTIC1"
        dicIni = {}
    nomFNS = os.path.join(nomDir, "Puzzles.fns")
    if os.path.isfile(nomFNS):
        n = 1
        nomFNS = os.path.join(nomDir, "Puzzles-%d.fns")
        while os.path.isfile(nomFNS % n):
            n += 1
        nomFNS = nomFNS % n

    # Se crea el fichero con los puzzles
    f = codecs.open(nomFNS, "w", "utf-8", 'ignore')

    nregs = len(liRegistros)
    tmpBP = QTUtil2.BarraProgreso(wowner, menuname, _("Game"), nregs)
    tmpBP.mostrar()

    fen0 = ControlPosicion.FEN_INICIAL

    for n in range(nregs):

        if tmpBP.siCancelado():
            break

        tmpBP.pon(n + 1)

        recno = liRegistros[n]

        dicValores = rutinaDatos(recno)
        plies = dicValores["PLIES"]
        if plies == 0:
            continue

        pgn = dicValores["PGN"]
        li = pgn.split("\n")
        if len(li) == 1:
            li = pgn.split("\r")
        li = [linea for linea in li if not linea.strip().startswith("[")]
        jugadas = " ".join(li).replace("\r", "").replace("\n", "")
        if not jugadas.strip("*"):
            continue

        def xdic(k):
            x = dicValores.get(k, "")
            if x is None:
                x = ""
            elif "?" in x:
                x = x.replace(".?", "").replace("?", "")
            return x.strip()

        fen = dicValores.get("FEN")
        if not fen:
            fen = fen0

        event = xdic("EVENT")
        site = xdic("SITE")
        date = xdic("DATE")
        if site == event:
            es = event
        else:
            es = event + " " + site
        es = es.strip()
        if date:
            if es:
                es += " (%s)" % date
            else:
                es = date
        white = xdic("WHITE")
        black = xdic("BLACK")
        wb = ("%s-%s" % (white, black)).strip("-")
        titulo = ""
        if es:
            titulo += "<br>%s" % es
        if wb:
            titulo += "<br>%s" % wb

        txt = fen + "|%s|%s\n" % (titulo, jugadas)

        f.write(txt)

    f.close()
    tmpBP.cerrar()

    # Se crea el fichero de control
    dicIni[nomTactic] = d = {}
    d["MENU"] = menuname
    d["FILESW"] = "%s:100" % os.path.basename(nomFNS)
    d["POINTVIEW"] = pointview

    Util.dic8ini(nomIni, dicIni)

    QTUtil2.mensaje(
        wowner,
        _X(_("Tactic training %1 created."), menuname) + "<br>" + _X(
            _("You can access this training from menu Trainings-Learn tactics by repetition-%1"
              ), restDir))

    procesador.entrenamientos.rehaz()
    def __init__(self, owner, regMarco):

        QtGui.QDialog.__init__(self, owner)

        self.setWindowTitle(_("Box"))
        self.setWindowFlags(QtCore.Qt.Dialog | QtCore.Qt.WindowTitleHint)

        if not regMarco:
            regMarco = TabVisual.PMarco()

        liAcciones = [
            (_("Save"), Iconos.Aceptar(), "grabar"),
            None,
            (_("Cancel"), Iconos.Cancelar(), "reject"),
            None,
        ]
        tb = Controles.TB(self, liAcciones)

        # Tablero
        confTablero = owner.tablero.confTablero
        self.tablero = Tablero.TableroVisual(self, confTablero)
        self.tablero.crea()
        self.tablero.copiaPosicionDe(owner.tablero)

        # Datos generales
        liGen = []

        # nombre del marco que se usara en los menus del tutorial
        config = FormLayout.Editbox(_("Name"), ancho=120)
        liGen.append((config, regMarco.nombre))

        # ( "tipo", "n", Qt.SolidLine ), #1=SolidLine, 2=DashLine, 3=DotLine, 4=DashDotLine, 5=DashDotDotLine
        config = FormLayout.Combobox(_("Line Type"), QTUtil2.tiposDeLineas())
        liGen.append((config, regMarco.tipo))

        # ( "color", "n", 0 ),
        config = FormLayout.Colorbox(_("Color"), 80, 20)
        liGen.append((config, regMarco.color))

        # ( "colorinterior", "n", -1 ),
        config = FormLayout.Colorbox(_("Internal color"),
                                     80,
                                     20,
                                     siChecked=True)
        liGen.append((config, regMarco.colorinterior))

        # ( "opacidad", "n", 1.0 ),
        config = FormLayout.Dial(_("Degree of transparency"), 0, 99)
        liGen.append((config, 100 - int(regMarco.opacidad * 100)))

        # ( "grosor", "n", 1 ), # ancho del trazo
        config = FormLayout.Spinbox(_("Thickness"), 1, 20, 50)
        liGen.append((config, regMarco.grosor))

        # ( "redEsquina", "n", 0 ),
        config = FormLayout.Spinbox(_("Rounded corners"), 0, 100, 50)
        liGen.append((config, regMarco.redEsquina))

        # orden
        config = FormLayout.Combobox(_("Order concerning other items"),
                                     QTUtil2.listaOrdenes())
        liGen.append((config, regMarco.posicion.orden))

        self.form = FormLayout.FormWidget(liGen, dispatch=self.cambios)

        # Layout
        layout = Colocacion.H().control(self.form).relleno().control(
            self.tablero)
        layout1 = Colocacion.V().control(tb).otro(layout)
        self.setLayout(layout1)

        # Ejemplos
        liMovs = ["b4c4", "e2e2", "e4g7"]
        self.liEjemplos = []
        for a1h8 in liMovs:
            regMarco.a1h8 = a1h8
            regMarco.siMovible = True
            marco = self.tablero.creaMarco(regMarco)
            self.liEjemplos.append(marco)