예제 #1
0
    def MoverTiempo(self):
        if self.siReloj:
            self.siReloj = False
        else:

            menu = QTVarios.LCMenu(self)
            menu.opcion("previo", "%s: %0.02f" % (_("Duration of interval (secs)"), self.intervalo / 1000.0),
                        Iconos.MoverTiempo())
            menu.opcion("otro", _("Change interval"), Iconos.Configurar())
            resp = menu.lanza()
            if not resp:
                return

            if resp == "otro":
                liGen = [(None, None)]
                config = FormLayout.Editbox(_("Duration of interval (secs)"), 40, tipo=float)
                liGen.append(( config, self.intervalo / 1000.0 ))
                resultado = FormLayout.fedit(liGen, title=_("Interval"), parent=self, icon=Iconos.MoverTiempo())
                if resultado is None:
                    return
                accion, liResp = resultado
                tiempo = liResp[0]
                if tiempo > 0.01:
                    self.intervalo = int(tiempo * 1000)
                else:
                    return

            self.siReloj = True
            if self.siMoves and (self.posHistoria >= len(self.historia) - 1):
                self.MoverInicio()
            self.lanzaReloj()
예제 #2
0
    def cambiarJuego(self):
        mateg = self.controlMate.ultimoNivel()
        ult_nivel = mateg.nivel + 1
        ult_bloque = mateg.numBloqueSinHacer() + 1
        if mateg.siTerminado():
            ult_nivel += 1
            ult_bloque = 1

        liGen = [(None, None)]

        config = FormLayout.Spinbox(_("Level"), 1, ult_nivel, 50)
        liGen.append(( config, ult_nivel ))

        config = FormLayout.Spinbox(_("Block"), 1, 10, 50)
        liGen.append(( config, ult_bloque ))

        resultado = FormLayout.fedit(liGen, title=_("Level"), parent=self.pantalla, icon=Iconos.Jugar())

        if resultado:
            nv, bl = resultado[1]
            nv -= 1
            bl -= 1
            self.controlMate.ponNivel(nv)
            self.ponRotuloNivel()
            self.refresh()
            self.jugar(bl)
예제 #3
0
    def tg_append_polyglot(self):

        previo = VarGen.configuracion.leeVariables("WBG_MOVES")
        carpeta = previo.get("CARPETABIN", "")

        ficheroBIN = QTUtil2.leeFichero(self, carpeta, "%s (*.bin)" % _("Polyglot book"), titulo=_("File to import"))
        if not ficheroBIN:
            return
        previo["CARPETABIN"] = os.path.dirname(ficheroBIN)
        VarGen.configuracion.escVariables("WBG_MOVES", previo)

        liGen = [(None, None)]

        liGen.append(( None, _("Select a maximum number of moves (plies)<br> to consider from each game") ))

        liGen.append(( FormLayout.Spinbox(_("Depth"), 3, 99, 50), 30 ))
        liGen.append((None, None))

        liGen.append(( _("Only white best moves"), False ))
        liGen.append((None, None))

        liGen.append(( _("Only black best moves"), False ))
        liGen.append((None, None))

        resultado = FormLayout.fedit(liGen, title=os.path.basename(ficheroBIN), parent=self, anchoMinimo=360,
                                     icon=Iconos.PuntoNaranja())

        if resultado:
            accion, liResp = resultado
            depth, whiteBest, blackBest = liResp
            return self.bookGuide.grabarPolyglot(self, ficheroBIN, depth, whiteBest, blackBest)

        return False
예제 #4
0
    def getNewName(self, title, previous=""):
        name = previous

        while True:
            liGen = [(None, None)]
            liGen.append(( _("Name") + ":", name ))

            resultado = FormLayout.fedit(liGen, title=title, parent=self, anchoMinimo=460,
                                         icon=Iconos.TutorialesCrear())
            if resultado is None:
                return None

            accion, liResp = resultado
            name = liResp[0].strip()
            if not name:
                return None

            name = Util.validNomFichero(name)

            ok = True
            for k in self.bookGuide.getOtras():
                if k.lower() == name.lower():
                    QTUtil2.mensError(self, _("This name is repeated, please select other"))
                    ok = False
                    break
            if ok:
                return name
예제 #5
0
    def data_new(self):
        menu = QTVarios.LCMenu(self)

        menu1 = menu.submenu(_("Checkmates in GM games"), Iconos.GranMaestro())
        menu1.opcion( "mate_basic", _( "Basic" ), Iconos.PuntoAzul() )
        menu1.separador()
        menu1.opcion( "mate_easy", _( "Easy" ), Iconos.PuntoAmarillo() )
        menu1.opcion( "mate_medium", _( "Medium" ), Iconos.PuntoNaranja() )
        menu1.opcion( "mate_hard", _( "Hard" ), Iconos.PuntoRojo() )

        menu.separador()
        menu.opcion("sts_basic", _("STS: Strategic Test Suite"), Iconos.STS())

        resp = menu.lanza()
        if resp:
            tipo, model = resp.split("_")
            if tipo == "sts":
                liGen = [(None, None)]
                liR = [ (str(x), x) for x in range(1, 100) ]
                config = FormLayout.Combobox(_("Model"), liR)
                liGen.append((config, "1"))
                resultado = FormLayout.fedit(liGen, title=_("STS: Strategic Test Suite"), parent=self, anchoMinimo=160, icon=Iconos.Maps())
                if resultado is None:
                    return
                accion, liResp = resultado
                model = liResp[0]
            self.workmap.nuevo(tipo,model)
            self.activaWorkmap()
예제 #6
0
    def tg_append_pgn(self):

        previo = VarGen.configuracion.leeVariables("WBG_MOVES")
        carpeta = previo.get("CARPETAPGN", "")

        ficheroPGN = QTUtil2.leeFichero(self, carpeta, "%s (*.pgn)" % _("PGN Format"), titulo=_("File to import"))
        if not ficheroPGN:
            return
        previo["CARPETAPGN"] = os.path.dirname(ficheroPGN)
        VarGen.configuracion.escVariables("WBG_MOVES", previo)

        liGen = [(None, None)]

        liGen.append(( None, _("Select a maximum number of moves (plies)<br> to consider from each game") ))

        liGen.append(( FormLayout.Spinbox(_("Depth"), 3, 999, 50), 30 ))
        liGen.append((None, None))

        resultado = FormLayout.fedit(liGen, title=os.path.basename(ficheroPGN), parent=self, anchoMinimo=460,
                                     icon=Iconos.PuntoNaranja())

        if resultado:
            accion, liResp = resultado
            depth = liResp[0]
            return self.bookGuide.grabarPGN(self, ficheroPGN, depth)
        return False
예제 #7
0
def numPosicion(wParent, titulo, nFEN, pos):

    liGen = [FormLayout.separador]

    label = "%s (1..%d)"%(_("Select position"), nFEN)
    liGen.append((FormLayout.Spinbox(label, 1, nFEN, 50), pos))

    liGen.append(FormLayout.separador)

    li = [   ( _("Sequential"), "s"),
             ( _("Random"), "r"),
             ( _("Random with same sequence based on position"), "rk" )
    ]
    liGen.append( (FormLayout.Combobox(_("Type"), li), "s") )

    liGen.append(FormLayout.separador)

    liGen.append( (_("Jump to the next after solve")+":", False))

    resultado = FormLayout.fedit(liGen, title=titulo, parent=wParent, anchoMinimo=200,
                                     icon=Iconos.Entrenamiento())
    if resultado:
        posicion, tipo, jump = resultado[1]
        return posicion, tipo, jump
    else:
        return None
예제 #8
0
    def grabarTema(self, tema):

        liGen = [(None, None)]

        nombre = tema["NOMBRE"] if tema else ""
        config = FormLayout.Editbox(_("Name"), ancho=160)
        liGen.append((config, nombre ))

        seccion = tema.get("SECCION", "") if tema else ""
        config = FormLayout.Editbox(_("Section"), ancho=160)
        liGen.append((config, seccion ))

        ico = Iconos.Grabar() if tema else Iconos.GrabarComo()

        resultado = FormLayout.fedit(liGen, title=_("Name"), parent=self, icon=ico)
        if resultado:
            accion, liResp = resultado
            nombre = liResp[0]
            seccion = liResp[1]

            if nombre:
                tema["NOMBRE"] = nombre
                if seccion:
                    tema["SECCION"] = seccion
                self.confTablero.png64Thumb(base64.b64encode(self.tablero.thumbnail(64)))
                tema["TEXTO"] = self.confTablero.grabaTema()
                tema["BASE"] = self.confTablero.grabaBase()
                self.temaActual = tema
                self.ponSecciones()
                return tema
예제 #9
0
 def configurar(self):
     menu = QTVarios.LCMenu(self)
     menu.opcion("formula", _("Formula to calculate elo"), Iconos.STS())
     resp = menu.lanza()
     if resp:
         X = self.sts.X
         K = self.sts.K
         while True:
             liGen = [(None, None)]
             liGen.append((None, "X * %s + K" % _("Result")))
             config = FormLayout.Editbox("X", 100, tipo=float, decimales=4)
             liGen.append(( config, X ))
             config = FormLayout.Editbox("K", 100, tipo=float, decimales=4)
             liGen.append(( config, K ))
             resultado = FormLayout.fedit(liGen, title=_("Formula to calculate elo"), parent=self, icon=Iconos.Elo(),
                                          siDefecto=True)
             if resultado:
                 resp, valor = resultado
                 if resp == 'defecto':
                     X = self.sts.Xdefault
                     K = self.sts.Kdefault
                 else:
                     x, k = valor
                     self.sts.formulaChange(x, k)
                     self.grid.refresh()
                     return
             else:
                 return
예제 #10
0
    def empezar(self):
        regBase = self.liIntentos[0] if self.liIntentos else {}

        liGen = [(None, None)]

        liGen.append((FormLayout.Spinbox(_("Level"), 0, self.partida.numJugadas(), 40), regBase.get("LEVEL", 0)))
        liGen.append((None, None))
        liGen.append((None, _("User play with") + ":"))
        liGen.append((_("White"), "w" in regBase.get("COLOR", "bw")))
        liGen.append((_("Black"), "b" in regBase.get("COLOR", "bw")))
        liGen.append((None, None))
        liGen.append((_("Show clock"), True))

        resultado = FormLayout.fedit(liGen, title=_("New try"), anchoMinimo=200, parent=self,
                                     icon=Iconos.TutorialesCrear())
        if resultado is None:
            return

        accion, liResp = resultado
        level = liResp[0]
        white = liResp[1]
        black = liResp[2]
        if not (white or black):
            return
        siClock = liResp[3]

        w = WLearnPuente(self, self.partida, level, white, black, siClock)
        w.exec_()
예제 #11
0
def cambioTutor(parent, configuracion):
    liGen = [(None, None)]

    # # Tutor
    liGen.append(( _("Engine") + ":", configuracion.ayudaCambioTutor() ))

    # # Decimas de segundo a pensar el tutor
    liGen.append(( _("Duration of engine analysis (secs)") + ":", float(configuracion.tiempoTutor / 1000.0) ))
    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, configuracion.tutorMultiPV ))

    liGen.append(( None, _("Sensitivity") ))
    liGen.append((FormLayout.Spinbox(_("Minimum difference in points"), 0, 1000, 70), configuracion.tutorDifPts ))
    liGen.append((FormLayout.Spinbox(_("Minimum difference in %"), 0, 1000, 70), configuracion.tutorDifPorc ))

    # Editamos
    resultado = FormLayout.fedit(liGen, title=_("Tutor change"), parent=parent, anchoMinimo=460, icon=Iconos.Opciones())

    if resultado:
        claveMotor, tiempo, multiPV, difpts, difporc = resultado[1]
        configuracion.tutor = configuracion.buscaTutor(claveMotor)
        configuracion.tiempoTutor = int(tiempo*1000)
        configuracion.tutorMultiPV = multiPV
        configuracion.tutorDifPts = difpts
        configuracion.tutorDifPorc = difporc
        configuracion.graba()
        return True
    else:
        return False
예제 #12
0
    def ggrabarGuion(self):
        liGen = [(None, None)]

        config = FormLayout.Editbox(_("Name"), ancho=160)
        liGen.append((config, self.nomGuion ))

        resultado = FormLayout.fedit(liGen, title=_("Name"), parent=self)
        if resultado:
            resp = resultado[1][0].strip()
            if resp:
                self.dbGuiones[resp] = self.guion.guarda()
예제 #13
0
    def reindexarPlayer(self):
        dic = VarGen.configuracion.leeVariables("reindexplayer")

        # Select depth
        liGen = [(None, None)]
        liGen.append(( _("Player (wildcards=*)"), dic.get("player", "")))
        liGen.append((None, None))
        liGen.append(( None, _("Select the number of moves <br> for each game to be considered") ))
        liGen.append((None, None))

        li = [(str(n), n) for n in range(3, 255)]
        config = FormLayout.Combobox(_("Depth"), li)
        liGen.append(( config, dic.get("depth", 30) ))

        resultado = FormLayout.fedit(liGen, title=_("Summary filtering by player"), parent=self,
                                     icon=Iconos.Reindexar())
        if resultado is None:
            return None

        accion, liResp = resultado

        dic["player"] = player = liResp[0]
        if not player:
            return
        dic["depth"] = depth = liResp[1]

        VarGen.configuracion.escVariables("reindexplayer", dic)

        class CLT:
            pass

        clt = CLT()
        clt.RECCOUNT = 0
        clt.SICANCELADO = False

        bpTmp = QTUtil2.BarraProgreso1(self, _("Rebuilding"))
        bpTmp.mostrar()

        def dispatch(recno, reccount):
            if reccount != clt.RECCOUNT:
                clt.RECCOUNT = reccount
                bpTmp.ponTotal(reccount)
            bpTmp.pon(recno)
            if bpTmp.siCancelado():
                clt.SICANCELADO = True

            return not clt.SICANCELADO

        self.dbGames.recrearSTATplayer(dispatch, depth, player)
        bpTmp.cerrar()
        if clt.SICANCELADO:
            self.dbGames.ponSTATbase()
        self.grid.refresh()
예제 #14
0
def dameMinutosExtra(pantalla):
    liGen = [(None, None)]

    config = FormLayout.Spinbox(_("Extra minutes for the player"), 1, 99, 50)
    liGen.append(( config, 5 ))

    resultado = FormLayout.fedit(liGen, title=_("Time"), parent=pantalla, icon=Iconos.MoverTiempo())
    if resultado:
        accion, liResp = resultado
        return liResp[0]

    return None
예제 #15
0
    def editaNombre(self, nombre):
        liGen = [(None, None)]
        config = FormLayout.Editbox(_("Name"), ancho=160)
        liGen.append((config, nombre ))
        ico = Iconos.Grabar()

        resultado = FormLayout.fedit(liGen, title=_("Name"), parent=self, icon=ico)
        if resultado:
            accion, liResp = resultado
            nombre = liResp[0]
            return nombre
        return None
예제 #16
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") ),
               ( "E", _("Stockfish eval") ),
    ]
    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()
        xid = "MOS" + d.isoformat()[2:].strip("0").replace("-", "").replace("T", "").replace(":", "").replace(".", "")
        fvideo = configuracion.plantillaVideo % xid

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

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

        listaKibitzersGrabar(configuracion, liKibitzers)

        return liKibitzers
    else:
        return None
예제 #17
0
    def newBookmark(self, move):

        comment = move.comment()
        allpgn = move.allPGN()
        siComment = len(comment) > 0

        txt = comment if siComment else allpgn

        liGen = [(None, None)]
        liGen.append(( _("Name") + ":", txt ))

        liGen.append(( _("Copy PGN") + ":", False ))
        if siComment:
            liGen.append(( _("Copy comment") + ":", False ))

        reg = KRegistro()
        reg.allpgn = allpgn
        reg.comment = comment.split("\n")[0].strip()
        reg.form = None

        def dispatch(valor):
            if reg.form is None:
                reg.form = valor
                reg.wname = valor.getWidget(0)
                reg.wpgn = valor.getWidget(1)
                reg.wcomment = valor.getWidget(2)
                reg.wpgn.setText(reg.allpgn)
                if reg.wcomment:
                    reg.wcomment.setText(reg.comment)
            else:
                QTUtil.refreshGUI()
                if reg.wpgn.isChecked():
                    reg.wname.setText(reg.allpgn)
                elif reg.wcomment and reg.wcomment.isChecked():
                    reg.wname.setText(reg.comment)
                if reg.wcomment:
                    reg.wcomment.setChecked(False)
                reg.wpgn.setChecked(False)
                QTUtil.refreshGUI()

        resultado = FormLayout.fedit(liGen, title=_("Bookmark"), parent=self.wmoves, anchoMinimo=460,
                                     icon=Iconos.Favoritos(), dispatch=dispatch)
        if resultado is None:
            return None

        accion, liResp = resultado
        txt = liResp[0].strip()
        if txt:
            move.mark(txt)
            self.ponIconoBookmark(move.item(), move.mark())
            self.wmoves.compruebaBookmarks()
예제 #18
0
파일: Piezas.py 프로젝트: cdcupt/lucaschess
    def configurations(self):
        dic = VarGen.configuracion.leeVariables("BLINDFOLD")
        dicConf = collections.OrderedDict()
        for k in dic:
            if k.startswith("_"):
                cl = k[1:]
                dicConf[cl] = dic[k]

        menu = QTVarios.LCMenu(self)
        for k in dicConf:
            menu.opcion((True, k), k, Iconos.PuntoAzul())
        menu.separador()
        menu.opcion((True, None), _("Save current configuration"), Iconos.PuntoVerde())
        if dicConf:
            menu.separador()
            menudel = menu.submenu(_("Remove"), Iconos.Delete())
            for k in dicConf:
                menudel.opcion((False, k), k, Iconos.PuntoNegro())

        resp = menu.lanza()
        if resp is None:
            return

        si, cual = resp

        if si:
            if cual:
                dpz = dic["_" + cual]
                for pz in "kqrbnp":
                    lbPZw, cbPZw, lbPZ, lbPZb, cbPZb, tipoW, tipoB = self.dicWidgets[pz]
                    cbPZw.ponValor(dpz[pz.upper()])
                    cbPZb.ponValor(dpz[pz])
                self.reset()
            else:
                liGen = [(None, None)]
                liGen.append(( _("Name") + ":", "" ))

                resultado = FormLayout.fedit(liGen, title=_("Save current configuration"), parent=self, anchoMinimo=460,
                                             icon=Iconos.TutorialesCrear())
                if resultado is None:
                    return None

                accion, liResp = resultado
                name = liResp[0].strip()
                if not name:
                    return None
                dic["_%s" % name] = self.config.dicPiezas
                VarGen.configuracion.escVariables("BLINDFOLD", dic)
        else:
            del dic["_%s" % cual]
            VarGen.configuracion.escVariables("BLINDFOLD", dic)
예제 #19
0
    def entrenar(self, fil=None, col=None):
        if len(self.lista) == 0:
            return
        if fil is None:
            fil = self.grid.recno()

        # Ultimo entrenamiento
        dicPar = Util.recuperaVar(self.ficheroParam)
        if dicPar is None:
            jugamos = "BLANCAS"
            repeticiones = 5
        else:
            jugamos = dicPar["JUGAMOS"]
            repeticiones = dicPar["REPETICIONES"]
        if not ((col is None) or (col.clave == "NOMBRE")):
            jugamos = col.clave

        # Datos
        liGen = [(None, None)]

        liJ = [(_("White"), "BLANCAS"), (_("Black"), "NEGRAS"), (_("White & Black"), "AMBOS")]
        config = FormLayout.Combobox(_("Play with"), liJ)
        liGen.append(( config, jugamos ))

        liR = [( _("Undefined"), 0 )]

        for x in range(4):
            liR.append((str(x + 1), x + 1))

        for x in range(5, 105, 5):
            liR.append((str(x), x))
        config = FormLayout.Combobox(_("Model"), liR)
        liGen.append(( config, repeticiones ))

        # Editamos
        resultado = FormLayout.fedit(liGen, title=_("Train"), parent=self, anchoMinimo=360, icon=Iconos.Entrenar())
        if resultado is None:
            return

        accion, liResp = resultado
        jugamos = liResp[0]
        repeticiones = liResp[1]

        dicPar = {}
        dicPar["JUGAMOS"] = jugamos
        dicPar["REPETICIONES"] = repeticiones
        Util.guardaVar(self.ficheroParam, dicPar)

        self.resultado = (self.listaAperturasStd, self.ficheroDatos, self.lista, fil, jugamos, repeticiones)
        self.accept()
예제 #20
0
    def desdeHasta(self, titulo, desde, hasta):
        liGen = [(None, None)]

        config = FormLayout.Casillabox(_("From square"))
        liGen.append(( config, desde ))

        config = FormLayout.Casillabox(_("To square"))
        liGen.append(( config, hasta ))

        resultado = FormLayout.fedit(liGen, title=titulo, parent=self)
        if resultado:
            resp = resultado[1]
            self.ultDesde = desde = resp[0]
            self.ultHasta = hasta = resp[1]
            return desde, hasta
        else:
            return None, None
예제 #21
0
 def editarNombre(self, previo, siNuevo=False):
     while True:
         liGen = [(None, None)]
         liGen.append((_("Name") + ":", previo))
         resultado = FormLayout.fedit(liGen, title=_("STS: Strategic Test Suite"), parent=self, icon=Iconos.STS())
         if resultado:
             accion, liGen = resultado
             nombre = Util.validNomFichero(liGen[0].strip())
             if nombre:
                 if not siNuevo and previo == nombre:
                     return None
                 path = os.path.join(self.carpetaSTS, nombre + ".sts")
                 if os.path.isfile(path):
                     QTUtil2.mensError(self, _("The file %s already exist") % nombre)
                     continue
                 return nombre
             else:
                 return None
         else:
             return None
예제 #22
0
    def configurar(self):
        segundos, puntos = self.boxing.actual()

        liGen = [(None, None)]

        config = FormLayout.Spinbox(_("Time in seconds"), 1, 99999, 80)
        liGen.append(( config, segundos ))

        config = FormLayout.Spinbox(_("Points"), 10, 99999, 80)
        liGen.append(( config, puntos ))

        resultado = FormLayout.fedit(liGen, title=_("Config"), parent=self, icon=Iconos.Configurar())
        if resultado:
            accion, liResp = resultado
            segundos = liResp[0]
            puntos = liResp[1]
            self.boxing.cambiaConfiguracion(segundos, puntos)
            self.ponTextoAyuda()
            self.grid.refresh()
            return liResp[0]
예제 #23
0
    def configurar(self):
        # Datos
        liGen = [(None, None)]

        # # Motor
        mt = self.configuracion.tutorInicial if self.motor is None else self.motor

        liCombo = [mt]
        for nombre, clave in self.configuracion.comboMotoresMultiPV10():
            liCombo.append((clave, nombre))

        liGen.append(( _("Engine") + ":", liCombo ))

        # # Segundos a pensar el tutor
        config = FormLayout.Spinbox(_("Duration of engine analysis (secs)"), 1, 99, 50)
        liGen.append(( config, self.segundos ))

        ## Pruebas
        config = FormLayout.Spinbox(_("N. of tests"), 1, 40, 40)
        liGen.append(( config, self.pruebas ))

        ## Fichero
        config = FormLayout.Fichero(_("File"), "%s (*.fns);;%s PGN (*.pgn)" % (_("List of FENs"), _("File")), False,
                                    anchoMinimo=280)
        liGen.append(( config, self.fns ))

        # Editamos
        resultado = FormLayout.fedit(liGen, title=_("Configuration"), parent=self, icon=Iconos.Opciones())
        if resultado:
            accion, liResp = resultado
            self.motor = liResp[0]
            self.segundos = liResp[1]
            self.pruebas = liResp[2]
            self.fns = liResp[3]

            param = Util.DicSQL(self.configuracion.ficheroDailyTest, tabla="parametros")
            param["MOTOR"] = self.motor
            param["SEGUNDOS"] = self.segundos
            param["PRUEBAS"] = self.pruebas
            param["FNS"] = self.fns
            param.close()
예제 #24
0
def paramPelicula(parent):
    # Datos
    liGen = [(None, None)]

    # # Segundos
    liGen.append(( _("Number of seconds between moves") + ":", 2 ))

    # # Si desde el principi
    liGen.append(( _("Start from first move") + ":", True ))

    # Editamos
    resultado = FormLayout.fedit(liGen, title=_("Replay game"), parent=parent, anchoMinimo=460, icon=Iconos.Pelicula())

    if resultado:
        accion, liResp = resultado

        segundos = liResp[0]
        siPrincipio = liResp[1]
        return segundos, siPrincipio
    else:
        return None
예제 #25
0
    def configuraciones(self):
        fichero = self.configuracion.ficheroEntMaquinaConf
        dbc = Util.DicSQL(fichero)
        liConf = dbc.keys(siOrdenados=True)
        menu = Controles.Menu(self)
        SELECCIONA, BORRA, AGREGA = range(3)
        for x in liConf:
            menu.opcion((SELECCIONA, x), x, Iconos.PuntoAzul())
        menu.separador()
        menu.opcion((AGREGA, None), _("Save current configuration"), Iconos.Mas())
        if liConf:
            menu.separador()
            submenu = menu.submenu(_("Remove"), Iconos.Delete())
            for x in liConf:
                submenu.opcion((BORRA, x), x, Iconos.PuntoRojo())
        resp = menu.lanza()

        if resp:
            op, k = resp

            if op == SELECCIONA:
                dic = dbc[k]
                self.muestraDic(dic)
            elif op == BORRA:
                if QTUtil2.pregunta(self, _X(_("Delete %1 ?"), k)):
                    del dbc[k]
            elif op == AGREGA:
                liGen = [(None, None)]

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

                resultado = FormLayout.fedit(liGen, title=_("Name"), parent=self, icon=Iconos.Libre())
                if resultado:
                    accion, liGen = resultado

                    nombre = liGen[0].strip()
                    if nombre:
                        dbc[nombre] = self.creaDic()

        dbc.close()
예제 #26
0
    def configurar(self):
        # Datos
        liGen = [(None, None)]

        # # Motor
        mt = self.configuracion.tutorInicial if self.motor is None else self.motor

        liCombo = [mt]
        for nombre, clave in self.configuracion.comboMotoresMultiPV10():
            liCombo.append((clave, nombre))

        liGen.append(( _("Engine") + ":", liCombo ))

        # # Segundos a pensar el tutor
        config = FormLayout.Spinbox(_("Duration of engine analysis (secs)"), 1, 99, 50)
        liGen.append(( config, self.segundos ))

        ## Minutos
        config = FormLayout.Spinbox(_("Minimum minutes"), 0, 99, 50)
        liGen.append(( config, self.min_min ))

        config = FormLayout.Spinbox(_("Maximum minutes"), 0, 99, 50)
        liGen.append(( config, self.min_max ))

        # Editamos
        resultado = FormLayout.fedit(liGen, title=_("Configuration"), parent=self, icon=Iconos.Opciones())
        if resultado:
            accion, liResp = resultado
            self.motor = liResp[0]
            self.segundos = liResp[1]
            self.min_min = liResp[2]
            self.min_max = liResp[3]

            param = Util.DicSQL(self.configuracion.ficheroPotencia, tabla="parametros")
            param["MOTOR"] = self.motor
            param["SEGUNDOS"] = self.segundos
            param["MIN_MIN"] = self.min_min
            param["MIN_MAX"] = self.min_max
            param.close()
예제 #27
0
def opcionesPrimeraVez(parent, configuracion):
    separador = (None, None)

    # Datos generales
    liGen = [separador]

    # # Nombre del jugador
    liGen.append(( _("Player's name") + ":", configuracion.jugador ))

    # Editamos
    resultado = FormLayout.fedit(liGen, title=_("Configuration"), parent=parent, anchoMinimo=560,
                                 icon=Iconos.Opciones())

    if resultado:
        accion, resp = resultado

        liGen = resp

        configuracion.jugador = liGen[0]

        return True
    else:
        return False
예제 #28
0
def cambiaColoresPGN(ventana, configuracion):
    liGen = [(None, None)]

    dicNAGs = TrListas.dicNAGs()
    config = FormLayout.Colorbox(dicNAGs[1], 80, 20, siSTR=True)
    liGen.append(( config, configuracion.color_nag1 ))

    config = FormLayout.Colorbox(dicNAGs[2], 80, 20, siSTR=True)
    liGen.append(( config, configuracion.color_nag2 ))

    config = FormLayout.Colorbox(dicNAGs[3], 80, 20, siSTR=True)
    liGen.append(( config, configuracion.color_nag3 ))

    config = FormLayout.Colorbox(dicNAGs[4], 80, 20, siSTR=True)
    liGen.append(( config, configuracion.color_nag4 ))

    config = FormLayout.Colorbox(dicNAGs[5], 80, 20, siSTR=True)
    liGen.append(( config, configuracion.color_nag5 ))

    config = FormLayout.Colorbox(dicNAGs[6], 80, 20, siSTR=True)
    liGen.append(( config, configuracion.color_nag6 ))

    resultado = FormLayout.fedit(liGen, title=_("PGN"), parent=ventana, icon=Iconos.Vista(), siDefecto=True)
    if resultado:
        accion, liResp = resultado
        if accion == "defecto":
            configuracion.coloresPGNdefecto()
            configuracion.graba()
            cambiaColoresPGN(ventana, configuracion)
        else:
            configuracion.color_nag1 = liResp[0]
            configuracion.color_nag2 = liResp[1]
            configuracion.color_nag3 = liResp[2]
            configuracion.color_nag4 = liResp[3]
            configuracion.color_nag5 = liResp[4]
            configuracion.color_nag6 = liResp[5]
            configuracion.graba()
예제 #29
0
    def reindexar(self):
        if not QTUtil2.pregunta(self, _("Do you want to rebuild stats?")):
            return

        # Select depth
        liGen = [(None, None)]
        liGen.append(( None, _("Select the number of moves <br> for each game to be considered") ))
        liGen.append((None, None))

        li = [(str(n), n) for n in range(3, 255)]
        config = FormLayout.Combobox(_("Depth"), li)
        liGen.append(( config, self.dbGames.depthStat() ))

        resultado = FormLayout.fedit(liGen, title=_("Rebuild"), parent=self, icon=Iconos.Reindexar())
        if resultado is None:
            return None

        accion, liResp = resultado

        depth = liResp[0]

        self.RECCOUNT = 0

        bpTmp = QTUtil2.BarraProgreso1(self, _("Rebuilding"))
        bpTmp.mostrar()

        def dispatch(recno, reccount):
            if reccount != self.RECCOUNT:
                self.RECCOUNT = reccount
                bpTmp.ponTotal(reccount)
            bpTmp.pon(recno)
            return not bpTmp.siCancelado()

        self.dbGames.recrearSTAT(dispatch, depth)
        bpTmp.cerrar()
        self.grid.refresh()
예제 #30
0
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)
    if alm.blancas and alm.negras:
        color = "AMBOS"
    elif alm.negras:
        color = "NEGRAS"
    elif alm.blancas:
        color = "BLANCAS"
    else:
        color = "AMBOS"
    liGen.append((config, color))

    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((_("Redo any existing prior analyses (if they exist)") + ":",
                  alm.siBorrarPrevio))

    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, tiempo, alm.depth, alm.timedepth, alm.multiPV, color, cjug, alm.libroAperturas, \
            alm.desdeelfinal, alm.siBorrarPrevio, alm.siVariosSeleccionados = liGen

        alm.tiempo = int(tiempo * 1000)
        alm.blancas = color != "NEGRAS"
        alm.negras = color != "BLANCAS"
        cjug = cjug.strip()
        alm.liJugadores = cjug.upper().split(";") if cjug else None
        alm.libro = alm.libroAperturas.nombre if alm.libroAperturas is not None else None

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

        alm.dpbrilliancies, alm.ptbrilliancies, alm.fnsbrilliancies, alm.pgnbrilliancies, \
            alm.oribrilliancies, alm.bmtbrilliancies = liBrilliancies

        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
예제 #31
0
    def remove_worst(self):
        # color + time
        liGen = [FormLayout.separador]
        liJ = [(_("White"), "WHITE"), (_("Black"), "BLACK")]
        config = FormLayout.Combobox(_("Side"), liJ)
        liGen.append((config, "WHITE"))
        liGen.append((_("Duration of engine analysis (secs)") + ":",
                      float(self.configuration.x_tutor_mstime / 1000.0)))
        resultado = FormLayout.fedit(liGen,
                                     title=_("Remove worst lines"),
                                     parent=self,
                                     icon=Iconos.OpeningLines())
        if resultado:
            color, segs = resultado[1]
            ms = int(segs * 1000)
            if ms == 0:
                return
            si_white = color == "WHITE"
            dic = self.dbop.dicRepeFen(si_white)
            mensaje = _("Move") + "  %d/" + str(len(dic))
            tmpBP = QTUtil2.BarraProgreso(self, _("Remove worst lines"), "",
                                          len(dic))

            xmanager = self.procesador.creaManagerMotor(
                self.configuration.tutor, ms, 0, siMultiPV=False)

            st_borrar = set()

            ok = True

            for n, fen in enumerate(dic, 1):

                if tmpBP.is_canceled():
                    ok = False
                    break

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

                max_puntos = -999999
                max_pv = None
                dicPV = dic[fen]
                for pv in dicPV:
                    if tmpBP.is_canceled():
                        ok = False
                        break
                    FasterCode.set_fen(fen)
                    FasterCode.move_pv(pv[:2], pv[2:4], pv[4:])
                    mrm = xmanager.analiza(fen)
                    rm = mrm.mejorMov()
                    pts = rm.centipawns_abs()
                    if not si_white:
                        pts = -pts
                    if pts > max_puntos:
                        max_puntos = pts
                        if max_pv:
                            for nl in dicPV[max_pv]:
                                st_borrar.add(nl)
                        max_pv = pv
                    else:
                        for nl in dicPV[pv]:
                            st_borrar.add(nl)

            tmpBP.cerrar()

            xmanager.terminar()

            if ok:
                li_borrar = list(st_borrar)
                n = len(li_borrar)
                if n:
                    self.dbop.removeLines(li_borrar, _("Remove worst lines"))
                    QTUtil2.message_bold(self, _("Removed %d lines") % n)
                else:
                    QTUtil2.message_bold(self, _("Done"))
예제 #32
0
    def file(self):
        menu = QTVarios.LCMenu(self)
        menu.opcion("saveas", _("Save a copy"), Iconos.GrabarComo())
        menu.separador()
        menu.opcion("restorefrom", _("Restore from"), Iconos.Recuperar())
        menu.separador()
        submenu = menu.submenu(_("Create new"), Iconos.Nuevo())
        submenu.opcion("new_UNED", _("UNED chess school"), Iconos.Uned())
        submenu.separador()
        submenu.opcion("new_UWE", _("Uwe Auerswald"), Iconos.Uwe())
        menu.separador()
        menu.opcion("savedb", _("Save as database"), Iconos.DatabaseC())

        resp = menu.lanza()
        if resp is None:
            return
        if resp == "saveas":
            liGen = [(None, None)]
            config = FormLayout.Editbox(_("Name"), ancho=160)
            liGen.append((config, ""))

            resultado = FormLayout.fedit(liGen,
                                         title=_("Name"),
                                         parent=self,
                                         icon=Iconos.GrabarComo())
            if resultado:
                accion, liResp = resultado
                fich = nombre = liResp[0]
                if nombre.lower()[-4:] != ".wsm":
                    fich += ".wsm"
                path = os.path.join(self.configuracion.carpeta, fich)
                ok = True
                if Util.existeFichero(path):
                    ok = QTUtil2.pregunta(
                        self,
                        _X(
                            _("The file %1 already exists, what do you want to do?"
                              ), fich),
                        etiSi=_("Overwrite"),
                        etiNo=_("Cancel"))
                if ok:
                    shutil.copy(self.dbwashing.file, path)
        elif resp == "restorefrom":
            li = []
            for fich in os.listdir(self.configuracion.carpeta):
                if fich.endswith(".wsm") and fich != self.dbwashing.filename:
                    li.append(fich[:-4])
            if not li:
                QTUtil2.mensaje(self, _("There is no file"))
                return
            menu = QTVarios.LCMenu(self)
            for fich in li:
                menu.opcion(fich, fich, Iconos.PuntoRojo())
            resp = menu.lanza()
            if resp:
                if QTUtil2.pregunta(
                        self, "%s\n%s" %
                    (_("Current data will be removed and overwrited."),
                     _("Are you sure?"))):
                    shutil.copy(
                        os.path.join(self.configuracion.carpeta,
                                     resp + ".wsm"), self.dbwashing.file)
                    self.wreload = True
                    self.guardarVideo()
                    self.accept()
        elif resp.startswith("new_"):
            tactic = resp[4:]
            if QTUtil2.pregunta(
                    self, "%s\n%s" %
                (_("Current data will be removed and overwrited."),
                 _("Are you sure?"))):
                self.dbwashing.new(tactic)
                self.wreload = True
                self.guardarVideo()
                self.accept()
        elif resp == "savedb":
            ext = "lcg"
            path = QTUtil2.salvaFichero(self, _("Database of complete games"),
                                        self.configuracion.ficheroDBgames,
                                        _("File") + " %s (*.%s)" % (ext, ext),
                                        False)
            if path:
                if not path.lower().endswith(".lcg"):
                    path += ".lcg"
                me = QTUtil2.mensEspera.inicio(self, _("Saving..."))
                dbn = DBgames.DBgames(path)
                for engine in self.washing.liEngines:
                    if engine.state == Washing.ENDED:
                        game = self.dbwashing.restoreGame(engine)
                        pc = Partida.PartidaCompleta()
                        pc.leeOtra(game)
                        dt = engine.date
                        if engine.color:
                            white = self.configuracion.jugador
                            black = engine.nombre
                            result = "1-0"
                            whiteelo = str(self.configuracion.elo)
                            blackelo = engine.elo
                        else:
                            black = self.configuracion.jugador
                            white = engine.nombre
                            result = "0-1"
                            blackelo = str(self.configuracion.elo)
                            whiteelo = engine.elo
                        tags = [
                            ["Site", "Lucas Chess"],
                            ["Event", _("The Washing Machine")],
                            ["Date",
                             "%d-%d-%d" % (dt.year, dt.month, dt.day)],
                            ["White", white],
                            ["Black", black],
                            ["WhiteElo", whiteelo],
                            ["BlackElo", blackelo],
                            ["Result", result],
                        ]
                        ap = game.apertura
                        if ap:
                            tags.append(["ECO", ap.eco])
                            tags.append(["Opening", ap.trNombre])
                        pc.setTags(tags)
                        dbn.inserta(pc)
                me.final()
예제 #33
0
    def borrar(self):
        tam_dbop = len(self.dbop)
        if tam_dbop == 0:
            return
        current = self.glines.recno() // 2
        li = []
        if 0 <= current < tam_dbop:
            li.append([
                "current",
                _("Remove line %d") % (current + 1, ),
                Iconos.Mover()
            ])
        if tam_dbop > 1:
            li.append(
                ["lines",
                 _("Remove a list of lines"),
                 Iconos.MoverLibre()])

        if len(li) > 0:
            menu = QTVarios.LCMenu(self)
            for key, title, ico in li:
                menu.opcion(key, title, ico)
                menu.separador()
            resp = menu.lanza()

            if resp == "current":
                self.dbop.saveHistory(_("Remove line %d") % (current + 1, ))
                del self.dbop[current]
                self.goto_inilinea()

            elif resp is not None:
                liGen = [FormLayout.separador]
                config = FormLayout.Editbox(
                    "<div align=\"right\">" + _("Lines") + "<br>" +
                    _("By example:") + " -5,8-12,14,19-",
                    rx="[0-9,\-,\,]*")
                liGen.append((config, ""))
                resultado = FormLayout.fedit(liGen,
                                             title=_("Remove a list of lines"),
                                             parent=self,
                                             anchoMinimo=460,
                                             icon=Iconos.OpeningLines())
                if resultado:
                    accion, liResp = resultado
                    clista = liResp[0]
                    if clista:
                        ln = Util.ListaNumerosImpresion(clista)
                        li = ln.selected(range(1, tam_dbop + 1))
                        sli = []
                        cad = ""
                        for num in li:
                            if cad:
                                cad += "," + str(num)
                            else:
                                cad = str(num)
                            if len(cad) > 80:
                                sli.append(cad)
                                cad = ""
                        if cad:
                            sli.append(cad)
                        cli = "\n".join(sli)
                        if QTUtil2.pregunta(
                                self,
                                _("Do you want to remove the next lines?") +
                                "\n\n" + cli):
                            um = QTUtil2.unMomento(self, _("Working..."))
                            self.dbop.removeLines([x - 1 for x in li], cli)
                            self.glines.refresh()
                            self.goto_inilinea()
                            um.final()
        self.show_lines()
예제 #34
0
 def xcolor(txt, tipo):
     config = FormLayout.Colorbox(txt, 40, 20, siSTR=True)
     color = QtGui.QColor(palette[tipo]) if palette else palette_std.color(
         getattr(QtGui.QPalette, tipo))
     liColor.append((config, color))
     liPalette.append(tipo)
예제 #35
0
def paramAnalisis(parent, configuracion, siModoAmpliado, siTodosMotores=False):
    alm = leeDicParametros(configuracion)

    # Datos
    liGen = [SEPARADOR]

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

    # # Time
    liGen.append(SEPARADOR)
    config = FormLayout.Editbox(_("Duration of engine analysis (secs)"), 40, tipo=float)
    liGen.append((config, alm.vtime / 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"), Priorities.priorities.combo())
    liGen.append((config, alm.priority))

    # Completo
    if siModoAmpliado:
        liGen.append(SEPARADOR)

        liJ = [(_("White"), "WHITE"), (_("Black"), "BLACK"), (_("White & Black"), "BOTH")]
        config = FormLayout.Combobox(_("Analyze only color"), liJ)
        if alm.white and alm.black:
            color = "BOTH"
        elif alm.black:
            color = "BLACK"
        elif alm.white:
            color = "WHITE"
        else:
            color = "BOTH"
        liGen.append((config, color))

        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.restore_pickle(fvar)
        # Comprobamos que todos esten accesibles
        listaLibros.comprueba()
        li = [("--", None)]
        defecto = listaLibros.lista[0] if alm.book_name else None
        for book in listaLibros.lista:
            if alm.book_name == book.name:
                defecto = book
            li.append((book.name, book))
        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.delete_previous))

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

        liGen.append(SEPARADOR)

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

        liVar = form_variations(alm)

        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, _("Variations"), ""))
        lista.append((liBlunders, _("Wrong moves"), ""))
        lista.append((liBrilliancies, _("Brilliancies"), ""))
        lista.append((liST, _("Stability control"), ""))

    else:
        lista = liGen

    reg = Util.Record()
    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.refresh_gui()

    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.engine = liGen[0]
        alm.vtime = 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.white = color != "BLACK"
            alm.black = color != "WHITE"
            alm.num_moves = liGen[7]
            alm.book = liGen[8]
            alm.book_name = alm.book.name if alm.book else None
            alm.delete_previous = liGen[9]
            alm.from_last_move = liGen[10]
            alm.show_graphs = liGen[11]

            (alm.include_variations, alm.limit_include_variations, alm.best_variation, alm.info_variation, alm.si_pdt, alm.one_move_variation) = 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] = getattr(alm, x)
        Util.save_pickle(configuracion.file_param_analysis(), dic)

        return alm
    else:
        return None
예제 #36
0
def options(parent, configuration):
    form = FormLayout.FormLayout(parent,
                                 _("Configuration"),
                                 Iconos.Opciones(),
                                 anchoMinimo=640)

    # Datos generales ##############################################################################################
    form.separador()

    form.edit(_("Player's name"), configuration.x_player)
    form.separador()
    form.combobox(_("Window style"), configuration.estilos(),
                  configuration.x_style)
    form.separador()

    li_traducciones = configuration.list_translations()
    tr_actual = configuration.translator()
    li = []
    for k, trad, porc, author in li_traducciones:
        label = "%s" % trad
        if int(porc) < 90:
            label += " (%s%%)" % porc
        li.append((label, k))
    form.combobox(_("Language"), li, tr_actual)
    form.separador()

    li = [
        (_("Play against an engine"), MENU_PLAY_ANY_ENGINE),
        (_("Opponents for young players"), MENU_PLAY_YOUNG_PLAYERS),
        (_("Both"), MENU_PLAY_BOTH),
    ]
    form.combobox(_("Menu Play"), li, configuration.x_menu_play)
    form.separador()

    if Code.is_windows:
        form.checkbox(_("Show the option to import from version 11"),
                      configuration.x_show_version11)
        form.separador()

    form.checkbox(_("Check for updates at startup"),
                  configuration.x_check_for_update)

    form.add_tab(_("General"))

    # Sonidos ########################################################################################################
    form.separador()
    form.checkbox(_("Beep after opponent's move"), configuration.x_sound_beep)
    form.separador()
    form.apart(_("Sound on in"))
    form.checkbox(_("Results"), configuration.x_sound_results)
    form.checkbox(_("Rival moves"), configuration.x_sound_move)
    form.separador()
    form.checkbox(_("Activate sounds with our moves"),
                  configuration.x_sound_our)

    form.add_tab(_("Sounds"))

    # Tutor ##########################################################################################################
    form.separador()
    form.combobox(_("Engine"), configuration.listaCambioTutor(),
                  configuration.tutor.key)
    form.float(_("Duration of tutor analysis (secs)"),
               float(configuration.x_tutor_mstime / 1000.0))
    form.spinbox(_("Depth"), 0, 40, 100, configuration.x_tutor_depth)

    form.spinbox(_("Number of moves evaluated by engine(MultiPV)"), 0, 512,
                 100, configuration.x_tutor_multipv)
    form.separador()
    form.checkbox(_("Disabled at the beginning of the game"),
                  not configuration.x_default_tutor_active)

    li_pos_tutor = [
        (_("Horizontal"), POS_TUTOR_HORIZONTAL),
        (_("Horizontal") + " 2+1", POS_TUTOR_HORIZONTAL_2_1),
        (_("Horizontal") + " 1+2", POS_TUTOR_HORIZONTAL_1_2),
        (_("Vertical"), POS_TUTOR_VERTICAL),
    ]
    form.combobox(_("Tutor boards position"), li_pos_tutor,
                  configuration.x_tutor_view)
    form.separador()
    form.checkbox(_("Work in the background, when possible"),
                  not configuration.x_engine_notbackground)
    form.separador()
    form.separador()
    form.apart(_("Sensitivity"))
    form.spinbox(_("Minimum difference in centipawns"), 0, 1000, 70,
                 configuration.x_tutor_difpoints)
    form.spinbox(_("Minimum difference in %"), 0, 1000, 70,
                 configuration.x_tutor_difporc)
    form.separador()
    form.separador()
    form.folder(_("Gaviota Tablebases"), configuration.x_carpeta_gaviota,
                configuration.carpeta_gaviota_defecto())
    form.separador()

    form.add_tab(_("Tutor"))

    # Boards #########################################################################################################
    form.separador()
    form.checkbox(_("Visual effects"), configuration.x_show_effects)

    drap = {
        1: 100,
        2: 150,
        3: 200,
        4: 250,
        5: 300,
        6: 350,
        7: 400,
        8: 450,
        9: 500
    }
    drap_v = {}
    for x in drap:
        drap_v[drap[x]] = x
    form.dial(
        "%s (%s=1)" % (_("Speed"), _("Default")),
        1,
        len(drap),
        drap_v.get(configuration.x_pieces_speed, 100),
        siporc=False,
    )
    form.separador()

    li_mouse_sh = [
        (_("Type fixed: you must always indicate origin and destination"),
         False),
        (_("Type predictive: program tries to guess your intention"), True),
    ]
    form.combobox(_("Mouse shortcuts"), li_mouse_sh,
                  configuration.x_mouse_shortcuts)
    form.checkbox(_("Show candidates"), configuration.x_show_candidates)
    form.checkbox(_("Always promote to queen\nALT key allows to change"),
                  configuration.x_autopromotion_q)
    form.checkbox(_("Show cursor when engine is thinking"),
                  configuration.x_cursor_thinking)
    form.separador()

    x = " - %s Graham O'Neill (https://goneill.co.nz)" % _("developed by")
    if Code.is_windows:
        li_db = [
            (_("None"), ""),
            (_("DGT"), "DGT"),
            (_("DGT Alternate") + x, "DGT-gon"),
            (_("Certabo") + x, "Certabo"),
            (_("Millennium") + x, "Millennium"),
            (_("Novag Citrine") + x, "Citrine"),
            (_("Novag UCB") + x, "Novag UCB"),
        ]
    else:
        li_db = [
            (_("None"), ""),
            (_("DGT") + x, "DGT-gon"),
            (_("Certabo") + x, "Certabo"),
            ("%s (%s) %s" % (_("Certabo"), _("Bluetooth"), x), "CertaboBT"),
            (_("Millennium") + x, "Millennium"),
            (_("Novag Citrine") + x, "Citrine"),
            (_("Novag UCB") + x, "Novag UCB"),
        ]
    form.combobox(_("Digital board"), li_db, configuration.x_digital_board)

    form.separador()
    form.checkbox(_("Show configuration icon"),
                  configuration.x_opacity_tool_board > 6)
    li_pos = [(_("Bottom"), "B"), (_("Top"), "T")]
    form.combobox(_("Configuration icon position"), li_pos,
                  configuration.x_position_tool_board)
    form.separador()
    form.checkbox(_("Show icon when position has graphic information"),
                  configuration.x_director_icon)
    form.separador()
    form.checkbox(_("Live graphics with the right mouse button"),
                  configuration.x_direct_graphics)

    form.add_tab(_("Boards"))

    # Aspect ########################################################################################################
    form.checkbox(_("By default"), False)
    form.separador()
    form.font(_("Font"), configuration.x_font_family)

    form.apart(_("Menus"))
    form.spinbox(_("Font size"), 3, 64, 60, configuration.x_menu_points)
    form.checkbox(_("Bold"), configuration.x_menu_bold)

    form.separador()
    form.apart(_("Toolbars"))
    form.spinbox(_("Font size"), 3, 64, 60, configuration.x_tb_fontpoints)
    form.checkbox(_("Bold"), configuration.x_tb_bold)
    li = (
        (_("Only display the icon"), QtCore.Qt.ToolButtonIconOnly),
        (_("Only display the text"), QtCore.Qt.ToolButtonTextOnly),
        (_("The text appears beside the icon"),
         QtCore.Qt.ToolButtonTextBesideIcon),
        (_("The text appears under the icon"),
         QtCore.Qt.ToolButtonTextUnderIcon),
    )
    form.combobox(_("Icons"), li, configuration.tipoIconos())

    form.separador()
    form.apart(_("PGN table"))
    form.spinbox(_("Width"), 283, 1000, 70, configuration.x_pgn_width)
    form.spinbox(_("Height of each row"), 18, 99, 70,
                 configuration.x_pgn_rowheight)
    form.spinbox(_("Font size"), 3, 99, 70, configuration.x_pgn_fontpoints)
    form.checkbox(_("PGN always in English"), configuration.x_pgn_english)
    form.checkbox(_("PGN with figurines"), configuration.x_pgn_withfigurines)
    form.separador()

    form.checkbox(_("Enable captured material window by default"),
                  configuration.x_captures_activate)
    form.checkbox(_("Enable information panel by default"),
                  configuration.x_info_activate)
    form.separador()
    form.spinbox(_("Font size of information labels"), 3, 30, 70,
                 configuration.x_sizefont_infolabels)

    form.add_tab(_("Appearance"))

    # Perfomance ####################################################################################################
    perf = configuration.perfomance

    def d(num):
        return " (%s %d)" % (_("default"), num)

    form.separador()
    form.apart(_("Bad moves: lost centipawns to consider a move as bad"))
    form.spinbox(_("Bad move") + d(90), 20, 1000, 60, perf.bad_lostp)
    form.spinbox(
        _("Very bad move") + d(200), 50, 1000, 60, perf.very_bad_lostp)
    form.separador()
    form.spinbox(
        _("Degree of effect of bad moves on the game elo") + d(2), 0, 5, 40,
        perf.bad_factor)
    form.separador()
    form.apart(
        _("Good moves: minimum depth required from the engine to discover the move"
          ))
    form.spinbox(_("Good move") + d(3), 2, 20, 40, perf.good_depth)
    form.spinbox(_("Very good move") + d(6), 3, 20, 40, perf.very_good_depth)

    form.add_tab(_("Performance"))

    # Modo no competitivo ############################################################################################
    form.separador()
    form.spinbox(_("Lucas-Elo"), 0, 3200, 70, configuration.x_elo)
    form.separador()
    form.spinbox(_("Club players competition"), 0, 3200, 70,
                 configuration.x_michelo)
    form.separador()
    form.spinbox(_("Fics-Elo"), 0, 3200, 70, configuration.x_fics)
    form.separador()
    form.spinbox(_("Fide-Elo"), 0, 3200, 70, configuration.x_fide)
    form.separador()
    form.spinbox(_("Lichess-Elo"), 0, 3200, 70, configuration.x_lichess)

    form.add_tab(_("Change elos"))

    resultado = form.run()

    if resultado:
        accion, resp = resultado

        li_gen, li_son, li_tt, li_b, li_asp, li_pr, li_nc = resp

        if Code.is_windows:
            (
                configuration.x_player,
                configuration.x_style,
                translator,
                configuration.x_menu_play,
                configuration.x_show_version11,
                configuration.x_check_for_update,
            ) = li_gen
        else:
            (
                configuration.x_player,
                configuration.x_style,
                translator,
                configuration.x_menu_play,
                configuration.x_check_for_update,
            ) = li_gen

        configuration.set_translator(translator)

        por_defecto = li_asp[0]
        if por_defecto:
            li_asp = (
                "",
                11,
                False,
                11,
                False,
                QtCore.Qt.ToolButtonTextUnderIcon,
                283,
                22,
                10,
                False,
                True,
                True,
                False,
                10,
            )
        else:
            del li_asp[0]
        (
            configuration.x_font_family,
            configuration.x_menu_points,
            configuration.x_menu_bold,
            configuration.x_tb_fontpoints,
            configuration.x_tb_bold,
            qt_iconstb,
            configuration.x_pgn_width,
            configuration.x_pgn_rowheight,
            configuration.x_pgn_fontpoints,
            configuration.x_pgn_english,
            configuration.x_pgn_withfigurines,
            configuration.x_captures_activate,
            configuration.x_info_activate,
            configuration.x_sizefont_infolabels,
        ) = li_asp
        if configuration.x_font_family == "System":
            configuration.x_font_family = ""

        configuration.set_tipoIconos(qt_iconstb)

        (
            configuration.x_sound_beep,
            configuration.x_sound_results,
            configuration.x_sound_move,
            configuration.x_sound_our,
        ) = li_son

        (
            configuration.x_tutor_clave,
            tiempoTutor,
            configuration.x_tutor_depth,
            configuration.x_tutor_multipv,
            tutor_inactive,
            configuration.x_tutor_view,
            workinbackground,
            configuration.x_tutor_difpoints,
            configuration.x_tutor_difporc,
            configuration.x_carpeta_gaviota,
        ) = li_tt
        configuration.x_default_tutor_active = not tutor_inactive
        configuration.x_tutor_mstime = int(tiempoTutor * 1000)
        configuration.x_engine_notbackground = not workinbackground

        (
            configuration.x_elo,
            configuration.x_michelo,
            configuration.x_fics,
            configuration.x_fide,
            configuration.x_lichess,
        ) = li_nc

        (
            configuration.x_show_effects,
            rapidezMovPiezas,
            configuration.x_mouse_shortcuts,
            configuration.x_show_candidates,
            configuration.x_autopromotion_q,
            configuration.x_cursor_thinking,
            dboard,
            toolIcon,
            configuration.x_position_tool_board,
            configuration.x_director_icon,
            configuration.x_direct_graphics,
        ) = li_b
        configuration.x_opacity_tool_board = 10 if toolIcon else 1
        configuration.x_pieces_speed = drap[rapidezMovPiezas]
        if configuration.x_digital_board != dboard:
            if dboard:
                if QTUtil2.pregunta(
                        parent,
                        "%s<br><br>%s %s" %
                    (
                        _("Are you sure %s is the correct driver ?") % dboard,
                        _("WARNING: selecting the wrong driver might cause damage to your board."
                          ),
                        _("Proceed at your own risk."),
                    ),
                ):
                    DGT.ponON()
                else:
                    dboard = ""
            configuration.x_digital_board = dboard

        perf.bad_lostp, perf.very_bad_lostp, perf.bad_factor, perf.good_depth, perf.very_good_depth = li_pr
        perf.very_bad_factor = perf.bad_factor * 4

        return True
    else:
        return False
예제 #37
0
def import_polyglot_config(owner, configuration, titulo, with_collisions):
    dic = configuration.read_variables("POLYGLOT_IMPORT")

    form = FormLayout.FormLayout(owner,
                                 titulo,
                                 Iconos.Import8(),
                                 anchoMinimo=440)
    form.separador()

    form.spinbox(_("Maximum half moves (plies)"), 1, 999, 60,
                 dic.get("PLIES", 50))
    form.separador()

    li_options = (("%s + %s" % (_("White"), _("Black")), {True, False}),
                  (_("White"), {True}), (_("Black"), {False}))
    form.combobox(_("Side to include"), li_options,
                  dic.get("SIDE", {True, False}))
    form.separador()

    form.apart_simple(_("Include games when result is"))
    form.checkbox("1-0", dic.get("1-0", True))
    form.checkbox("0-1", dic.get("0-1", True))
    form.checkbox("1/2-1/2", dic.get("1/2-1/2", True))
    form.separador()
    li_options = ((_("Discard"), ""), ("1-0", "1-0"), ("0-1", "0-1"),
                  ("1/2-1/2", "1/2-1/2"))
    form.combobox("%s %s" % (_("Unknown result"), _("convert to")), li_options,
                  dic.get("*", ""))
    form.separador()

    form.spinbox(_("Minimum number of games"), 1, 999999, 50,
                 dic.get("MINGAMES", 5))
    form.spinbox(
        _("Minimum score") + " (0-100)", 0, 100, 50, dic.get("MINSCORE", 0))

    form.separador()
    li_options = (
        (_("Number of games"), CALCWEIGHT_NUMGAMES),
        (_("Number of games") + " * " + _("Score"), CALCWEIGHT_NUMGAMES_SCORE),
        (_("Score") + "% * 100", CALCWEIGHT_SCORE),
    )
    form.combobox(_("Calculation of the weight"), li_options,
                  dic.get("CALCWEIGHT", CALCWEIGHT_NUMGAMES))
    form.separador()
    form.checkbox(_("Save score"), dic.get("SAVESCORE", False))
    form.separador()

    if with_collisions:
        li_options = ((_("Replace"), "replace"), (_("Add"), "add"),
                      (_("Discard"), "discard"))
        form.combobox(_("What to do in case of collisions"), li_options,
                      dic.get("COLLISIONS", "replace"))

    resultado = form.run()

    if not resultado:
        return None
    accion, resp = resultado
    if with_collisions:
        plies, st_side, r1_0, r0_1, r1_1, ru, min_games, min_score, calc_weight, save_score, collisions = resp
    else:
        plies, st_side, r1_0, r0_1, r1_1, ru, min_games, min_score, calc_weight, save_score = resp
    if not (r1_0 or r0_1 or r1_1 or ru != ""):
        return None

    st_results = set()
    if r1_0:
        st_results.add(b"1-0")
    if r1_1:
        st_results.add(b"1/2-1/2")
    if r0_1:
        st_results.add(b"0-1")
    if ru != "":
        st_results.add(b"*")

    dic["PLIES"] = plies
    dic["SIDE"] = st_side
    dic["1-0"] = r1_0
    dic["0-1"] = r0_1
    dic["1/2-1/2"] = r1_1
    dic["*"] = ru
    dic["MINGAMES"] = min_games
    dic["MINSCORE"] = min_score
    dic["CALCWEIGHT"] = calc_weight
    dic["SAVESCORE"] = save_score
    configuration.write_variables("POLYGLOT_IMPORT", dic)

    if with_collisions:
        return plies, st_side, st_results, ru, min_games, min_score, calc_weight, save_score, collisions
    else:
        return plies, st_side, st_results, ru, min_games, min_score, calc_weight, save_score
예제 #38
0
    def editar(self, fila):

        if fila is None:
            nombre = ""
            eco = ""
            pgn = ""
            estandar = True
            titulo = _("New opening")

        else:
            reg = self.lista[fila]

            nombre = reg["NOMBRE"]
            eco = reg["ECO"]
            pgn = reg["PGN"]
            estandar = reg["ESTANDAR"]

            titulo = nombre

        # Datos
        liGen = [(None, None)]
        liGen.append((_("Name") + ":", nombre))
        config = FormLayout.Editbox("ECO", ancho=30, rx="[A-Z, a-z][0-9][0-9]")
        liGen.append((config, eco))
        liGen.append((_("Add to standard list") + ":", estandar))

        # Editamos
        resultado = FormLayout.fedit(liGen,
                                     title=titulo,
                                     parent=self,
                                     anchoMinimo=460,
                                     icon=Iconos.Apertura())
        if resultado is None:
            return

        accion, liResp = resultado
        nombre = liResp[0].strip()
        if not nombre:
            return
        eco = liResp[1].upper()
        estandar = liResp[2]

        fen = ControlPosicion.FEN_INICIAL

        self.procesador.procesador = self.procesador  # ya que editaVariante espera un gestor

        resp = Variantes.editaVariante(self.procesador,
                                       self.procesador,
                                       fen,
                                       pgn,
                                       titulo=nombre,
                                       siBlancasAbajo=True)

        if resp:
            pgn, a1h8 = resp

            reg = {}
            reg["NOMBRE"] = nombre
            reg["ECO"] = eco
            reg["PGN"] = pgn
            reg["A1H8"] = a1h8
            reg["ESTANDAR"] = estandar

            if fila is None:
                self.lista.append(reg)
                self.grid.refresh()
                self.grabar()
            else:
                self.lista[fila] = reg
            self.grid.refresh()
            self.grabar()
예제 #39
0
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)
        if alm.blancas and alm.negras:
            color = "AMBOS"
        elif alm.negras:
            color = "NEGRAS"
        elif alm.blancas:
            color = "BLANCAS"
        else:
            color = "AMBOS"
        liGen.append((config, color))

        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
예제 #40
0
def opciones(parent, configuracion):
    separador = (None, None)

    # Datos generales
    liGen = [separador]

    # # Nombre del jugador
    liGen.append((_("Player's name") + ":", configuracion.jugador))

    # # Estilo
    liGen.append((_("Window style") + ":", configuracion.estilos()))

    liTraducciones = configuracion.listaTraducciones()
    trActual = configuracion.traductor if configuracion.traductor else "en"
    li = [trActual]
    for k, trad, porc, author in liTraducciones:
        rotulo = "%s" % trad
        if int(porc) < 90:
            rotulo += " (%s%%)" % porc
        li.append((k, rotulo))
    liGen.append((_("Language") + ":", li))
    liGen.append(separador)
    liGen.append((_("Check for updates at startup") + ":",
                  configuracion.checkforupdate))

    # Engines
    liEng = [separador]
    liMedidas = [
        configuracion.centipawns,
        (True, "%s = 100 %s  ->   64, 19, -19, +23, -120, +130" %
         (_("One pawn"), _("points"))),
        (False, "%s = 1.00 %s ->   0.64, 0.19, -0.19, +0.23, -1.20, +1.30" %
         (_("One pawn"), _("points")))
    ]
    liEng.append((_("By showing scores from the engines") + ":", liMedidas))
    liEng.append(separador)
    liEng.append((_("OS 64bits BMI2 compatible") + ":", configuracion.bmi2))
    liEng.append(separador)
    liEng.append((_("Do not work in background when possible") + ":",
                  configuracion.notbackground))
    liEng.append(separador)
    liEng.append((_("Save engines log") + ":", configuracion.siLogEngines))

    # Aspect
    liAsp = []

    liAsp.append((_("By default") + ":", False))
    liAsp.append(separador)

    ## font general
    liAsp.append((FormLayout.FontCombobox(_("Font")), configuracion.familia))
    liAsp.append(separador)

    ## Menus
    liAsp.append((None, _("Menus") + ":"))
    liAsp.append((FormLayout.Spinbox(_("Font size"), 5, 64,
                                     60), configuracion.puntosMenu))
    liAsp.append((_("Bold") + ":", configuracion.boldMenu))

    ## Toolbars
    liAsp.append(separador)
    liAsp.append((None, _("Toolbars") + ":"))
    liAsp.append((FormLayout.Spinbox(_("Font size"), 5, 64,
                                     60), configuracion.puntosTB))
    liAsp.append((_("Bold") + ":", configuracion.boldTB))
    li = ((_("Only display the icon"), QtCore.Qt.ToolButtonIconOnly),
          (_("Only display the text"), QtCore.Qt.ToolButtonTextOnly),
          (_("The text appears beside the icon"),
           QtCore.Qt.ToolButtonTextBesideIcon),
          (_("The text appears under the icon"),
           QtCore.Qt.ToolButtonTextUnderIcon))
    config = FormLayout.Combobox(_("Icons"), li)
    liAsp.append((config, configuracion.iconsTB))

    ## PGN table
    liAsp.append(separador)
    liAsp.append((None, _("PGN table") + ":"))
    liAsp.append((FormLayout.Spinbox(_("Width"), 283, 1000,
                                     70), configuracion.anchoPGN))
    liAsp.append((FormLayout.Spinbox(_("Height of each row"), 18, 99,
                                     40), configuracion.altoFilaPGN))
    liAsp.append((FormLayout.Spinbox(_("Font size"), 10, 99,
                                     40), configuracion.puntosPGN))
    liAsp.append(
        (_("PGN always in English") + ":", configuracion.siNomPiezasEN))
    liAsp.append((_("PGN with figurines") + ":", configuracion.figurinesPGN))

    liAsp.append(separador)
    liAsp.append((FormLayout.Spinbox(_("Font size of information labels"), 8,
                                     30, 40), configuracion.tamFontRotulos))

    # Sonidos
    liSon = [separador]
    liSon.append(separador)
    # Si a_adimos sonido tras cada jugada
    liSon.append(
        (_("Beep after opponent's move") + ":", configuracion.siSuenaBeep))
    liSon.append(separador)
    liSon.append((None, _("Sound on in") + ":"))
    liSon.append((_("Results") + ":", configuracion.siSuenaResultados))
    liSon.append((_("Rival moves") + ":", configuracion.siSuenaJugada))
    liSon.append(separador)
    liSon.append((_("Activate sounds with our moves") + ":",
                  configuracion.siSuenaNuestro))
    liSon.append(separador)

    # Tutor
    liTT = [separador]
    liTT.append((_("Engine") + ":", configuracion.ayudaCambioTutor()))
    liTT.append((_("Duration of tutor analysis (secs)") + ":",
                 float(configuracion.tiempoTutor / 1000.0)))
    liDepths = [("--", 0)]
    for x in range(1, 51):
        liDepths.append((str(x), x))
    config = FormLayout.Combobox(_("Depth"), liDepths)
    liTT.append((config, 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)
    liTT.append((config, configuracion.tutorMultiPV))
    liTT.append(separador)
    liTT.append((_("Tutor enabled"), configuracion.tutorActivoPorDefecto))
    liTT.append(separador)

    # Mostrando el tutor
    # kTutorH, kTutorH2_1, kTutorH1_2, kTutorV
    liPosTutor = [
        configuracion.vistaTutor, (kTutorH, _("Horizontal")),
        (kTutorH2_1, _("Horizontal") + " 2+1"),
        (kTutorH1_2, _("Horizontal") + " 1+2"), (kTutorV, _("Vertical"))
    ]
    liTT.append((_("Tutor boards position") + ":", liPosTutor))
    liTT.append(separador)
    liTT.append(separador)
    liTT.append((None, _("Sensitivity")))
    liTT.append((FormLayout.Spinbox(_("Minimum difference in points"), 0, 1000,
                                    70), configuracion.tutorDifPts))
    liTT.append((FormLayout.Spinbox(_("Minimum difference in %"), 0, 1000,
                                    70), configuracion.tutorDifPorc))

    # Perfomance
    perf = configuracion.perfomance
    liPR = [separador]

    def d(num):
        return " (%s %d)" % (_("default"), num)

    liPR.append((None, _("Bad moves: lost points to consider a move as bad")))
    liPR.append((FormLayout.Spinbox(_("Bad move") + d(90), 20, 1000,
                                    60), perf.bad_lostp))
    liPR.append((FormLayout.Spinbox(_("Very bad move") + d(200), 50, 1000,
                                    60), perf.very_bad_lostp))
    liPR.append(separador)
    liPR.append((FormLayout.Spinbox(
        _("Degree of effect of bad moves on the game elo") + d(2), 0, 5,
        40), perf.bad_factor))
    liPR.append(separador)
    liPR.append((
        None,
        _("Good moves: minimum depth required by the engine to discover the move"
          )))
    liPR.append((FormLayout.Spinbox(_("Good move") + d(3), 2, 20,
                                    40), perf.good_depth))
    liPR.append((FormLayout.Spinbox(_("Very good move") + d(6), 3, 20,
                                    40), perf.very_good_depth))

    # Modo no competitivo
    liNC = [separador]
    liNC.append((FormLayout.Spinbox(_("Lucas-Elo"), 0, 3200,
                                    70), configuracion.eloNC))
    liNC.append((FormLayout.Spinbox(_("Tourney-Elo"), 0, 3200,
                                    70), configuracion.micheloNC))
    liNC.append((FormLayout.Spinbox(_("Fics-Elo"), 0, 3200,
                                    70), configuracion.ficsNC))
    liNC.append((FormLayout.Spinbox(_("Fide-Elo"), 0, 3200,
                                    70), configuracion.fideNC))
    liNC.append((FormLayout.Spinbox(_("Lichess-Elo"), 0, 3200,
                                    70), configuracion.lichessNC))

    # Salvado automatico
    liSA = [separador]

    config = FormLayout.Fichero(_("Autosave to a PGN file"), "pgn", True)
    liSA.append((config, configuracion.salvarFichero))
    liSA.append((_("Won games") + ":", configuracion.salvarGanados))
    liSA.append((_("Lost/Drawn games") + ":", configuracion.salvarPerdidos))
    liSA.append((_("Unfinished games") + ":", configuracion.salvarAbandonados))
    liSA.append(separador)
    liSA.append((_("Save as variant tutor's suggestion") + ":",
                 configuracion.guardarVariantesTutor))
    liSA.append(separador)
    config = FormLayout.Fichero(_("Autosave to a CSV file moves played"),
                                "csv", True)
    liSA.append((config, configuracion.salvarCSV))

    # Boards
    liB = [separador]

    liB.append((_("Visual effects") + ":", configuracion.efectosVisuales))

    drap = {
        1: 100,
        2: 150,
        3: 200,
        4: 250,
        5: 300,
        6: 350,
        7: 400,
        8: 450,
        9: 500
    }
    drapV = {}
    for x in drap:
        drapV[drap[x]] = x
    liB.append((FormLayout.Dial("%s (%s=1)" % (_("Speed"), _("Default")),
                                1,
                                len(drap),
                                siporc=False),
                drapV.get(configuracion.rapidezMovPiezas, 100)))
    liB.append(separador)

    liMouseSH = [
        configuracion.siAtajosRaton,
        (False,
         _("Type fixed: you must always indicate origin and destination")),
        (True, _("Type predictive: program tries to guess your intention"))
    ]
    liB.append((_("Mouse shortcuts") + ":", liMouseSH))
    liB.append((_("Show candidates") + ":", configuracion.showCandidates))
    liB.append(
        (_("Show arrows of variants") + ":", configuracion.showVariantes))
    liB.append((_("Always promote to queen\nALT key allows to change") + ":",
                configuracion.autocoronacion))
    liB.append((_("Show cursor when engine is thinking") + ":",
                configuracion.cursorThinking))
    liB.append(separador)
    liB.append((_("Enable captured material window by default") + ":",
                configuracion.siActivarCapturas))
    liMat = [
        configuracion.tipoMaterial, ("D", _("Difference material")),
        ("C", _("Captured material at beginning")),
        ("M", _("Material advantage"))
    ]
    liB.append((_("Show material") + ":", liMat))
    liB.append(separador)
    liB.append((_("Enable information panel by default") + ":",
                configuracion.siActivarInformacion))
    liB.append(separador)
    liB.append((_X(_("Enable %1"), _("DGT board")) + ":", configuracion.siDGT))
    liB.append(separador)
    # liT.append((FormLayout.Dial(_("Opacity of tool icon"), 1, 9, siporc=False), configuracion.opacityToolBoard))
    liB.append(
        (_("Show configuration icon"), configuracion.opacityToolBoard > 6))
    liPos = [
        configuracion.positionToolBoard, ("B", _("Bottom")), ("T", _("Top"))
    ]
    liB.append((_("Configuration icon position") + ":", liPos))
    liB.append(separador)
    liB.append((_("Show icon when position has graphic information"),
                configuracion.directorIcon))

    liB.append(separador)

    lista = []
    lista.append((liGen, _("General"), ""))
    lista.append((liSon, _("Sounds"), ""))
    lista.append((liTT, _("Tutor"), ""))
    lista.append((liB, _("Boards"), ""))
    lista.append((liEng, _("Engines"), ""))
    lista.append((liAsp, _("Appearance"), ""))
    lista.append((liPR, _("Performance"), ""))
    lista.append((liSA, _("Autosave"), ""))
    lista.append((liNC, _("Non competitive mode"), ""))

    # Editamos
    resultado = FormLayout.fedit(lista,
                                 title=_("Configuration"),
                                 parent=parent,
                                 anchoMinimo=640,
                                 icon=Iconos.Opciones())

    if resultado:
        accion, resp = resultado

        liGen, liSon, liTT, liB, liEng, liAsp, liPR, liSA, liNC = resp

        (configuracion.jugador, configuracion.estilo, configuracion.traductor,
         configuracion.checkforupdate) = liGen

        porDefecto = liAsp[0]
        if porDefecto:
            liAsp = "", 11, False, 11, False, QtCore.Qt.ToolButtonTextUnderIcon, 283, 22, 10, False, True, 10
        else:
            del liAsp[0]
        (configuracion.familia, configuracion.puntosMenu,
         configuracion.boldMenu, configuracion.puntosTB, configuracion.boldTB,
         configuracion.iconsTB, configuracion.anchoPGN,
         configuracion.altoFilaPGN, configuracion.puntosPGN,
         configuracion.siNomPiezasEN, configuracion.figurinesPGN,
         configuracion.tamFontRotulos) = liAsp
        if configuracion.familia == "System":
            configuracion.familia = ""

        (configuracion.siSuenaBeep, configuracion.siSuenaResultados,
         configuracion.siSuenaJugada, configuracion.siSuenaNuestro) = liSon

        (configuracion.tutor.clave, tiempoTutor, configuracion.depthTutor,
         configuracion.tutorMultiPV, configuracion.tutorActivoPorDefecto,
         configuracion.vistaTutor, configuracion.tutorDifPts,
         configuracion.tutorDifPorc) = liTT
        configuracion.tiempoTutor = int(tiempoTutor * 1000)

        (configuracion.eloNC, configuracion.micheloNC, configuracion.ficsNC,
         configuracion.fideNC, configuracion.lichessNC) = liNC

        (configuracion.centipawns, configuracion.bmi2,
         configuracion.notbackground, configuracion.siLogEngines) = liEng

        (configuracion.efectosVisuales, rapidezMovPiezas,
         configuracion.siAtajosRaton, configuracion.showCandidates,
         configuracion.showVariantes, configuracion.autocoronacion,
         configuracion.cursorThinking, configuracion.siActivarCapturas,
         configuracion.tipoMaterial, configuracion.siActivarInformacion, siDGT,
         toolIcon, configuracion.positionToolBoard,
         configuracion.directorIcon) = liB
        configuracion.opacityToolBoard = 10 if toolIcon else 1
        configuracion.rapidezMovPiezas = drap[rapidezMovPiezas]
        if configuracion.siDGT != siDGT:
            if siDGT:
                DGT.ponON()
            configuracion.siDGT = siDGT

        perf.bad_lostp, perf.very_bad_lostp, perf.bad_factor, perf.good_depth, perf.very_good_depth = liPR
        perf.very_bad_factor = perf.bad_factor * 4

        (configuracion.salvarFichero, configuracion.salvarGanados,
         configuracion.salvarPerdidos, configuracion.salvarAbandonados,
         configuracion.guardarVariantesTutor, configuracion.salvarCSV) = liSA
        configuracion.salvarCSV = Util.dirRelativo(configuracion.salvarCSV)

        return True
    else:
        return False
예제 #41
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()
예제 #42
0
    def mas(self):
        path = QTVarios.select_pgn(self)
        if not path:
            return

        fpgn = PGN.PGN()

        dicDB = fpgn.leeFichero(self, path)
        if dicDB is None:
            return

        bd = SQLBase.DBBase(dicDB["PATHDB"])

        dClavesTam = dicDB["DCLAVES"]
        dbf = bd.dbf("GAMES", ",".join(dClavesTam.keys()))
        dbf.leer()

        nreccount = dbf.reccount()

        plant = ""
        shuffle = False
        reverse = False
        todos = range(1, nreccount + 1)
        li_regs = None
        while True:
            sep = FormLayout.separador
            liGen = []
            liGen.append((None, "%s: %d" % (_("Total games"), nreccount)))
            liGen.append(sep)
            config = FormLayout.Editbox(_("Select games") + "<br>" +
                                        _("By example:") + " -5,7-9,14,19-" +
                                        "<br>" + _("Empty means all games"),
                                        rx="[0-9,\-,\,]*")
            liGen.append((config, plant))

            liGen.append(sep)

            liGen.append((_("Shuffle") + ":", shuffle))

            liGen.append(sep)

            liGen.append((_("Reverse") + ":", reverse))

            liGen.append(sep)

            config = FormLayout.Spinbox(_("Max moves"), 0, 999, 50)
            liGen.append((config, 0))

            resultado = FormLayout.fedit(liGen,
                                         title=_("Select games"),
                                         parent=self,
                                         anchoMinimo=200,
                                         icon=Iconos.Opciones())
            if resultado:
                accion, liResp = resultado
                plant, shuffle, reverse, max_moves = liResp
                if plant:
                    ln = Util.ListaNumerosImpresion(plant)
                    li_regs = ln.selected(todos)
                else:
                    li_regs = todos
                nregs = len(li_regs)
                if 12 <= nregs <= 500:
                    break
                else:
                    QTUtil2.mensError(
                        self, "%s (%d)" %
                        (_("Number of games must be in range 12-500"), nregs))
                    li_regs = None
            else:
                break

        if li_regs:
            if shuffle:
                random.shuffle(li_regs)
            if reverse:
                li_regs.sort(reverse=True)
            li_regs = [x - 1 for x in li_regs]  # 0 init

            dic = {}
            dic["TOURNEY"] = os.path.basename(path)[:-4]
            games = dic["GAMES"] = []

            for recno in li_regs:
                pgn = dbf.leeOtroCampo(recno, "PGN")
                g = PGNReader.read1Game(pgn)
                pv = g.pv()
                if max_moves:
                    lipv = pv.strip().split(" ")
                    if len(lipv) > max_moves:
                        pv = " ".join(lipv[:max_moves])
                dt = {
                    "LABELS": [(k, v) for k, v in g.labels.iteritems()],
                    "XPV": LCEngine.pv2xpv(pv)
                }
                games.append(dt)

            self.litourneys.append(dic)

            li = [("%s (%d)" % (tourney["TOURNEY"], len(tourney["GAMES"])),
                   tourney) for tourney in self.litourneys]
            self.cbtourney.rehacer(li, dic)

        dbf.cerrar()
        bd.cerrar()
예제 #43
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.configuration.tutor.key
        engine_time = 5.0
        num_engines = 20
        key_engine = "alaric"
        ext_engines = []
        auto_analysis = True
        ask_movesdifferent = False
        times = [500, 1000, 2000, 4000, 8000]
        books = ["", "", "", "", ""]
        books_sel = ["", "", "", "", ""]

        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)
            ext_engines = training.get("EXT_ENGINES", ext_engines)
            auto_analysis = training.get("AUTO_ANALYSIS", auto_analysis)
            ask_movesdifferent = training.get("ASK_MOVESDIFFERENT",
                                              ask_movesdifferent)
            times = training.get("TIMES", times)
            books = training.get("BOOKS", books)
            books_sel = training.get("BOOKS_SEL", books_sel)

        separador = FormLayout.separador
        li_gen = [separador]

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

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

        dic_engines = self.configuration.dic_engines
        li_engines = EnginesBunch.lista(dic_engines)
        config = FormLayout.Spinbox(
            "%s: %s" % (_("Automatic selection"), _("number of engines")), 0,
            len(li_engines), 50)
        li_gen.append((config, num_engines))

        likeys = [(dic_engines[x].name, x) for x in li_engines]
        config = FormLayout.Combobox(
            "%s: %s" % (_("Automatic selection"), _("bunch of engines")),
            likeys)
        li_gen.append((config, key_engine))
        li_gen.append(separador)

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

        li_gen.append(separador)

        li_gen.append((_("Automatic analysis") + ":", auto_analysis))

        li_gen.append(separador)

        li_gen.append(
            (_("Ask when the moves are different from the line") + ":",
             ask_movesdifferent))

        li = [("--", "")]
        for key, cm in self.configuration.dic_engines.items():
            li.append((cm.nombre_ext(), key))
        li = sorted(li, key=operator.itemgetter(1))

        li_ext = []

        for x in range(16):
            config = FormLayout.Combobox("%s %d" % (_("Engine"), x + 1), li)
            key = ext_engines[x] if len(ext_engines) > x else ""
            li_ext.append((config, key))

        liLevels = [separador]
        list_books = Books.ListBooks()
        list_books.restore_pickle(self.configuration.file_books)
        list_books.check()
        libooks = [(bookx.name, bookx) for bookx in list_books.lista]
        libooks.insert(0, ("--", None))
        li_books_sel = (("", ""), (_("Uniform random"),
                                   "au"), (_("Proportional random"), "ap"),
                        (_("Always the highest percentage"), "mp"))
        for level in range(5):
            n = level + 1
            title = "%s %d" % (_("Level"), n)
            # liLevels.append((None, title))
            tm = times[level] / 1000.0 if len(times) > level else 0.0
            liLevels.append(
                ("%s. %s:" % (title, _("Time engines think in seconds")), tm))

            bk = books[level] if len(books) > level else ""
            book = list_books.buscaLibro(bk) if bk else None
            config = FormLayout.Combobox(_("Book"), libooks)
            liLevels.append((config, book))

            config = FormLayout.Combobox(_("Book selection mode"),
                                         li_books_sel)
            liLevels.append((config, books_sel[level]))

        lista = []
        lista.append((li_gen, _("Basic data"), ""))
        lista.append((li_ext, _("Manual engine selection"), ""))
        lista.append((liLevels, _("Levels"), ""))

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

        accion, liResp = resultado

        selMotoresExt = []
        li_gen, li_ext, liLevels = liResp

        for key in li_ext:
            if key:
                selMotoresExt.append(key)

        reg = {}

        (
            reg["COLOR"],
            reg["MANDATORY"],
            reg["CONTROL"],
            reg["LOST_POINTS"],
            reg["NUM_ENGINES"],
            reg["KEY_ENGINE"],
            reg["ENGINE_CONTROL"],
            reg["ENGINE_TIME"],
            reg["AUTO_ANALYSIS"],
            reg["ASK_MOVESDIFFERENT"],
        ) = li_gen
        reg["EXT_ENGINES"] = selMotoresExt

        if (len(selMotoresExt) + reg["NUM_ENGINES"]) == 0:
            reg["NUM_ENGINES"] = 1

        times = []
        books = []
        books_sel = []
        for x in range(5):
            tm = int(liLevels[x * 3] * 1000)
            bk = liLevels[x * 3 + 1]
            bk_mode = liLevels[x * 3 + 2]
            if tm:
                times.append(tm)
                books.append(bk.name if bk else "")
                books_sel.append(bk_mode)
        if len(times) == 0:
            times.append(500)
            books.append(None)
        reg["TIMES"] = times
        reg["BOOKS"] = books
        reg["BOOKS_SEL"] = books_sel

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

        QTUtil2.message_bold(self, _("Created"))
 def xconfig(label, value):
     config = FormLayout.Editbox(label, 80, tipo=float, decimales=3)
     liGen.append((config, value))
예제 #45
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") + " - RodentII"),
        ("S", _("Best move")),
        ("L", _("Best move in one line")),
        ("J", _("Select move")),
        ("C", _("Threats")),
        ("E", _("Stockfish eval")),
    ]
    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]

        # Indexes only with Rodent II
        if tipo == "I":
            motor = "rodentII"
            if not kibitzer:  # para que no repita rodent II
                kibitzer = _("Indexes") + " - RodentII"

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

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

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

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

        listaKibitzersGrabar(configuracion, liKibitzers)

        return liKibitzers
    else:
        return None
예제 #46
0
def polyglotUnir(owner):
    lista = [(None, None)]

    dict1 = {"FICHERO": "", "EXTENSION": "bin", "SISAVE": False}
    lista.append((_("File") + " 1 :", dict1))
    dict2 = {"FICHERO": "", "EXTENSION": "bin", "SISAVE": False}
    lista.append((_("File") + " 2 :", dict2))
    dictr = {"FICHERO": "", "EXTENSION": "bin", "SISAVE": True}
    lista.append((_("Book to create") + ":", dictr))

    while True:
        resultado = FormLayout.fedit(lista,
                                     title=_("Merge two books in one"),
                                     parent=owner,
                                     anchoMinimo=460,
                                     icon=Iconos.Libros())
        if resultado:
            resultado = resultado[1]
            error = None
            f1 = resultado[0]
            f2 = resultado[1]
            fr = resultado[2]

            if (not f1) or (not f2) or (not fr):
                error = _("Not indicated all files")
            elif f1 == f2:
                error = _("File") + " 1 = " + _("File") + " 2"
            elif f1 == fr:
                error = _("File") + " 1 = " + _("Book to create")
            elif f2 == fr:
                error = _("File") + " 2 = " + _("Book to create")

            if error:
                dict1["FICHERO"] = f1
                dict2["FICHERO"] = f2
                dictr["FICHERO"] = fr
                QTUtil2.mensError(owner, error)
                continue
        else:
            return

        if VarGen.isWindows:
            exe = 'Engines/Windows/_tools/polyglot/polyglot.exe'
        else:
            exe = '%s/_tools/polyglot/polyglot' % VarGen.folder_engines

        li = [
            os.path.abspath(exe), 'merge-book', "-in1", f1, "-in2", f2, "-out",
            fr
        ]
        try:
            os.remove(fr)
        except:
            pass

        # Ejecutamos
        me = QTUtil2.unMomento(owner)

        process = subprocess.Popen(li,
                                   shell=True,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.STDOUT)

        # Mostramos el resultado
        txt = process.stdout.read()
        if os.path.isfile(fr):
            txt += "\n" + _X(_("Book created : %1"), fr)
        me.final()
        QTUtil2.mensaje(owner, txt)

        return
예제 #47
0
    def borrar(self):
        tam_dbop = len(self.dbop)
        if tam_dbop == 0:
            return
        menu = QTVarios.LCMenu(self)
        current = self.glines.recno() // 2
        if 0 <= current < tam_dbop:
            menu.opcion("current", "%s; %d" % (_("Remove line"), current + 1),
                        Iconos.Mover())
            menu.separador()
        if tam_dbop > 1:
            menu.opcion("lines", _("Remove a list of lines"),
                        Iconos.MoverLibre())
            menu.separador()
            menu.opcion("worst", _("Remove worst lines"), Iconos.Borrar())
            menu.separador()
        submenu = menu.submenu(_("Remove last move if the line ends with"),
                               Iconos.Final())
        submenu.opcion("last_white", _("White"), Iconos.Blancas())
        submenu.separador()
        submenu.opcion("last_black", _("Black"), Iconos.Negras())

        resp = menu.lanza()

        if resp == "current":
            self.dbop.saveHistory(_("Remove line %d") % (current + 1, ))
            del self.dbop[current]
            self.goto_inilinea()

        elif resp == "lines":
            liGen = [FormLayout.separador]
            config = FormLayout.Editbox('<div align="right">' + _("Lines") +
                                        "<br>" + _("By example:") +
                                        " -5,8-12,14,19-",
                                        rx=r"[0-9,\-,\,]*")
            liGen.append((config, ""))
            resultado = FormLayout.fedit(liGen,
                                         title=_("Remove a list of lines"),
                                         parent=self,
                                         anchoMinimo=460,
                                         icon=Iconos.OpeningLines())
            if resultado:
                accion, liResp = resultado
                clista = liResp[0]
                if clista:
                    ln = Util.ListaNumerosImpresion(clista)
                    li = ln.selected(range(1, tam_dbop + 1))
                    sli = []
                    cad = ""
                    for num in li:
                        if cad:
                            cad += "," + str(num)
                        else:
                            cad = str(num)
                        if len(cad) > 80:
                            if len(sli) == 4:
                                sli.append("...")
                            elif len(sli) < 4:
                                sli.append(cad)
                            cad = ""
                    if cad:
                        sli.append(cad)
                    cli = "\n".join(sli)
                    if QTUtil2.pregunta(
                            self,
                            _("Do you want to remove the next lines?") +
                            "\n\n" + cli):
                        um = QTUtil2.unMomento(self, _("Working..."))
                        self.dbop.removeLines([x - 1 for x in li], cli)
                        self.glines.refresh()
                        self.goto_inilinea()
                        um.final()
        elif resp == "worst":
            self.remove_worst()
        elif resp == "last_white":
            self.remove_lastmove(True)
        elif resp == "last_black":
            self.remove_lastmove(False)
        self.show_lines()
예제 #48
0
    def gmCrear(self):
        if self.torneo.numEngines() < 2:
            QTUtil2.mensError(self, _("You must create at least two engines"))
            return

        dicValores = VarGen.configuracion.leeVariables("crear_torneo")

        get = dicValores.get

        liGen = [(None, None)]

        config = FormLayout.Spinbox(_("Rounds"), 1, 999, 50)
        liGen.append((config, get("ROUNDS", 1)))

        liGen.append((None, None))

        config = FormLayout.Spinbox(_("Total minutes"), 1, 999, 50)
        liGen.append((config, get("MINUTES", 10)))

        config = FormLayout.Spinbox(_("Seconds added per move"), 0, 999, 50)
        liGen.append((config, get("SECONDS", 0)))

        liGen.append((None, _("Engines")))

        liEngines = self.torneo.liEngines()
        for pos, en in enumerate(liEngines):
            liGen.append((en.alias, get(en.huella(), True)))

        liGen.append((None, None))
        liGen.append((_("Select all"), False))

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

        def dispatch(valor):
            if reg.form is None:
                reg.form = valor
                reg.liEngines = []
                leng = len(liEngines)
                for x in range(leng):
                    reg.liEngines.append(valor.getWidget(x + 3))
                reg.selectall = valor.getWidget(leng + 3)
                reg.valorall = False

            else:
                QTUtil.refreshGUI()
                select = reg.selectall.isChecked()
                if select != reg.valorall:
                    for uno in reg.liEngines:
                        uno.setChecked(select)
                    reg.valorall = select
                QTUtil.refreshGUI()

        resultado = FormLayout.fedit(liGen,
                                     title=_("Games"),
                                     parent=self,
                                     icon=Iconos.Torneos(),
                                     dispatch=dispatch)
        if resultado is None:
            return

        accion, liResp = resultado
        dicValores["ROUNDS"] = rounds = liResp[0]
        dicValores["MINUTES"] = minutos = liResp[1]
        dicValores["SECONDS"] = segundos = liResp[2]

        liSel = []
        for num in range(self.torneo.numEngines()):
            en = liEngines[num]
            dicValores[en.huella()] = si = liResp[3 + num]
            if si:
                liSel.append(en.huella())

        VarGen.configuracion.escVariables("crear_torneo", dicValores)

        nSel = len(liSel)
        if nSel < 2:
            QTUtil2.mensError(self, _("You must create at least two engines"))
            return

        for r in range(rounds):
            for x in range(0, nSel - 1):
                for y in range(x + 1, nSel):
                    self.torneo.nuevoGame(liSel[x], liSel[y], minutos,
                                          segundos)
                    self.torneo.nuevoGame(liSel[y], liSel[x], minutos,
                                          segundos)

        self.gridGames.refresh()
        self.gridGames.gobottom()
        self.borraResult()
예제 #49
0
def massive_change_tags(owner, configuracion, num_selected):
    APPLY_ALL, APPLY_SELECTED = range(2)
    SAVE_NOTHING, SAVE_LABELS, SAVE_LABELS_VALUES = range(3)
    NUM_OTHERS = 4

    dic = configuracion.leeVariables("MASSIVE_CHANGE_TAGS")
    if not dic:
        dic = {}

    liBase = []
    sep = (None, None)

    def sepBase():
        liBase.append(sep)

    sepBase()

    liBase.append((None, _("Basic tags")))
    liBase.append(("%s:" % _("Event"), dic.get("EVENT", "")))
    liBase.append(("%s:" % _("Site"), dic.get("SITE", "")))
    liBase.append(("%s:" % _("Date"), dic.get("DATE", "")))

    sepBase()

    liBaseOther = [
        "Round", "White", "Black", "Result", "WhiteTitle", "BlackTitle",
        "WhiteElo", "BlackElo", "WhiteUSCF", "BlackUSCF", "WhiteNA", "BlackNA",
        "WhiteType", "BlackType", "EventDate", "EventSponsor", "Section",
        "Stage", "Board", "Opening", "Variation", "SubVariation", "ECO",
        "Time", "UTCTime", "UTCDate", "TimeControl", "SetUp", "Termination"
    ]
    li0 = ["", "Event", "Site", "Date"]
    li0.extend(liBaseOther)
    li = [[uno, uno] for uno in li0]
    combo = FormLayout.Combobox(_("Remove the tag (in English)"),
                                li,
                                si_editable=True)
    liBase.append((combo, ""))

    sepBase()

    liBase.append((None, _("Configuration")))

    liA = [(_("All read"), APPLY_ALL),
           ("%s [%d]" % (_("Only selected"), num_selected), APPLY_SELECTED)]
    config = FormLayout.Combobox(_("Apply to"), liA)
    liBase.append((config,
                   dic.get("APPLY",
                           APPLY_SELECTED if num_selected > 1 else APPLY_ALL)))
    sepBase()

    liBase.append((_("Overwrite"), dic.get("OVERWRITE", True)))
    sepBase()

    liS = [(_("Nothing"), SAVE_NOTHING), (_("Labels"), SAVE_LABELS),
           ("%s+%s" % (_("Labels"), _("Values")), SAVE_LABELS_VALUES)]
    config = FormLayout.Combobox(_("Save as default"), liS)
    liBase.append((config, dic.get("SAVE", SAVE_LABELS_VALUES)))

    liOther = [sep]

    for x in range(NUM_OTHERS):
        li = [[uno, uno] for uno in liBaseOther]
        previo = dic.get("OTHERS_TAG_%d" % x, "")
        li.insert(0, [previo, previo])
        if previo:
            li.insert(0, ["", ""])
        combo = FormLayout.Combobox("%s %d" % (_("Tag"), x + 1),
                                    li,
                                    si_editable=True)
        liOther.append((combo, previo))

        previo_value = dic.get("OTHERS_VALUE_%d" % x)
        rotulo = "%s %d" % (_("Value"), x + 1)
        if previo_value:
            li = [["", ""], [previo_value, previo_value]]
            combo = FormLayout.Combobox(rotulo, li, si_editable=True)
            liOther.append((combo, ""))
        else:
            liOther.append((rotulo, ""))
        liOther.append(sep)

    liOther.append(
        (None, "** %s" %
         _("All official tags must be indicated with their name in English.")))

    lista = []
    lista.append((liBase, _("Base"), ""))
    lista.append((liOther, _("Others"), ""))

    # Editamos
    resultado = FormLayout.fedit(lista,
                                 title=_("Massive change of tags"),
                                 parent=owner,
                                 anchoMinimo=640,
                                 icon=Iconos.PGN())
    if resultado:
        accion, resp = resultado
        liBase, liOther = resp

        dic = {}
        dic["EVENT"], dic["SITE"], dic["DATE"], dic["REMOVE"], dic[
            "APPLY"], dic["OVERWRITE"], dic["SAVE"] = liBase

        liTags = []
        for tag in ("Event", "Site", "Date"):
            tagu = tag.upper()
            if dic[tagu]:
                liTags.append((tag, dic[tagu]))

        for x in range(0, NUM_OTHERS * 2, 2):
            tag = liOther[x]
            if tag and tag.upper != "FEN":
                val = liOther[x + 1]
                ntag = x / 2
                dic["OTHERS_TAG_%d" % ntag] = tag
                dic["OTHERS_VALUE_%d" % ntag] = val
                if val:
                    liTags.append((tag, val))

        save = dic["SAVE"]

        if save == SAVE_NOTHING or save == SAVE_LABELS:
            for x in ("EVENT", "SITE", "DATE"):
                del dic[x]
            for x in range(NUM_OTHERS):
                key = "OTHERS_VALUE_%d" % x
                if key in dic:
                    del dic[key]
                if save == SAVE_NOTHING:
                    key = "OTHERS_TAG_%d" % x
                    if key in dic:
                        del dic[key]

        configuracion.escVariables("MASSIVE_CHANGE_TAGS", dic)

        if liTags or dic["REMOVE"]:
            return (liTags, dic["REMOVE"], dic["OVERWRITE"],
                    dic["APPLY"] == APPLY_ALL)

    return None
예제 #50
0
def crearTactic(procesador, wowner, liRegistros, rutinaDatos, name):
    # Se pide el name de la carpeta
    li_gen = [(None, None)]

    li_gen.append((_("Name") + ":", name))

    li_gen.append((None, None))

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

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

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

    rest_dir = Util.valid_filename(menuname)
    nom_dir = os.path.join(Code.configuration.folder_tactics(), rest_dir)
    nom_ini = os.path.join(nom_dir, "Config.ini")
    if os.path.isfile(nom_ini):
        dic_ini = Util.ini2dic(nom_ini)
        n = 1
        while True:
            if "TACTIC%d" % n in dic_ini:
                if "MENU" in dic_ini["TACTIC%d" % n]:
                    if dic_ini["TACTIC%d" %
                               n]["MENU"].upper() == menuname.upper():
                        break
                else:
                    break
                n += 1
            else:
                break
        nom_tactic = "TACTIC%d" % n
    else:
        nom_dir_tac = Code.configuration.folder_tactics()
        Util.create_folder(nom_dir)
        nom_tactic = "TACTIC1"
        dic_ini = {}
    nom_fns = os.path.join(nom_dir, "Puzzles.fns")
    if os.path.isfile(nom_fns):
        n = 1
        nom_fns = os.path.join(nom_dir, "Puzzles-%d.fns")
        while os.path.isfile(nom_fns % n):
            n += 1
        nom_fns = nom_fns % n

    # Se crea el file con los puzzles
    f = open(nom_fns, "wt", encoding="utf-8", errors="ignore")

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

    fen0 = FEN_INITIAL

    for n in range(nregs):

        if tmp_bp.is_canceled():
            break

        tmp_bp.pon(n + 1)

        recno = liRegistros[n]

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

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

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

        fen = dic_valores.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

        for other in ("TASK", "SOURCE"):
            v = xdic(other)
            if v:
                titulo += "<br>%s" % v

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

        f.write(txt)

    f.close()
    tmp_bp.cerrar()

    # Se crea el file de control
    dic_ini[nom_tactic] = d = {}
    d["MENU"] = menuname
    d["FILESW"] = "%s:100" % os.path.basename(nom_fns)
    d["POINTVIEW"] = pointview

    Util.dic2ini(nom_ini, dic_ini)

    QTUtil2.message_bold(
        wowner, ("%s<br>%s<br>  %s<br>    ➔%s<br>        ➔%s" %
                 (_("Tactic training %s created.") % menuname,
                  _("You can access this training from"), _("Trainings"),
                  _("Learn tactics by repetition"), rest_dir)))

    procesador.entrenamientos.rehaz()
예제 #51
0
def paramAnalisisMasivo(parent, configuracion, siVariosSeleccionados, siDatabase=False):
    alm = leeDicParametros(configuracion)

    # Datos
    liGen = [SEPARADOR]

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

    liGen.append(SEPARADOR)

    # # Time
    config = FormLayout.Editbox(_("Duration of engine analysis (secs)"), 40, tipo=float)
    liGen.append((config, alm.vtime / 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"), "WHITE"), (_("Black"), "BLACK"), (_("White & Black"), "BOTH")]
    config = FormLayout.Combobox(_("Analyze only color"), liJ)
    if alm.white and alm.black:
        color = "BOTH"
    elif alm.black:
        color = "BLACK"
    elif alm.white:
        color = "WHITE"
    else:
        color = "BOTH"
    liGen.append((config, color))

    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.restore_pickle(fvar)
    # Comprobamos que todos esten accesibles
    listaLibros.comprueba()
    defecto = listaLibros.lista[0]
    li = [("--", None)]
    for book in listaLibros.lista:
        if book.name == alm.book_name:
            defecto = book
        li.append((book.name, book))
    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.from_last_move))

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

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

    liVar = form_variations(alm)

    liBlunders, liBrilliancies = formBlundersBrilliancies(alm, configuracion)

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

    reg = Util.Record()
    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.refresh_gui()

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

    if resultado:
        accion, liResp = resultado

        liGen, liVar, liBlunders, liBrilliancies = liResp

        alm.engine, vtime, alm.depth, alm.timedepth, alm.multiPV, color, cjug, alm.book, alm.from_last_move, alm.delete_previous, alm.siVariosSeleccionados = liGen

        alm.vtime = int(vtime * 1000)
        alm.white = color != "BLACK"
        alm.black = color != "WHITE"
        cjug = cjug.strip()
        alm.li_players = cjug.upper().split(";") if cjug else None
        alm.book_name = alm.book.name if alm.book else None

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

        alm.include_variations, alm.limiteinclude_variations, alm.best_variation, alm.info_variation, alm.si_pdt, alm.one_move_variation = liVar

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

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

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

        return alm
    else:
        return None
예제 #52
0
    def __init__(self, owner, regMarker, xml=None, nombre=None):

        QtWidgets.QDialog.__init__(self, owner)

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

        self.configuracion = VarGen.configuracion

        if not regMarker:
            regMarker = TabVisual.PMarker()
            regMarker.xml = xml
            if nombre:
                regMarker.nombre = nombre

        liAcciones = [
            (_("Save"), Iconos.Aceptar(), self.grabar),
            None,
            (_("Cancel"), Iconos.Cancelar(), self.reject),
            None,
        ]
        tb = Controles.TBrutina(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, regMarker.nombre))

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

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

        # ( "poscelda", "n", 1 ),
        li = (
            ("%s-%s" % (_("Top"), _("Left")), 0),
            ("%s-%s" % (_("Top"), _("Right")), 1),
            ("%s-%s" % (_("Bottom"), _("Left")), 2),
            ("%s-%s" % (_("Bottom"), _("Right")), 3),
        )
        config = FormLayout.Combobox(_("Position in the square"), li)
        liGen.append((config, regMarker.poscelda))

        # orden
        config = FormLayout.Combobox(_("Order concerning other items"),
                                     QTUtil2.listaOrdenes())
        liGen.append((config, regMarker.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:
            regMarker.a1h8 = a1h8
            regMarker.siMovible = True
            marker = self.tablero.creaMarker(regMarker, siEditando=True)
            self.liEjemplos.append(marker)
예제 #53
0
    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.Tablero(self, confTablero, siDirector=False)
        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)
예제 #54
0
def formBlundersBrilliancies(alm, configuracion):
    liBlunders = [SEPARADOR]

    liBlunders.append((FormLayout.Editbox(
        _("Is considered wrong move when the loss of points is greater than"),
        tipo=int,
        ancho=50), alm.kblunders))
    liBlunders.append(SEPARADOR)

    def fileNext(base, ext):
        return Util.fileNext(configuracion.dirPersonalTraining, base, ext)

    path_pgn = fileNext("Blunders", "pgn")

    liBlunders.append((None, _("Generate a training file with these moves")))

    config = FormLayout.Editbox(_("Tactics name"), rx="[^\\\:/|?*^%><()]*")
    liBlunders.append((config, ""))

    config = FormLayout.Fichero(_("PGN Format"),
                                "%s (*.pgn)" % _("PGN Format"),
                                True,
                                anchoMinimo=280,
                                ficheroDefecto=path_pgn)
    liBlunders.append((config, ""))

    liBlunders.append((_("Also add complete game to PGN") + ":", False))

    liBlunders.append(SEPARADOR)

    eti = '"%s"' % _("Find best move")
    liBlunders.append(
        (_X(_("Add to the training %1 with the name"), eti) + ":", ""))

    liBrilliancies = [SEPARADOR]

    liBrilliancies.append((FormLayout.Spinbox(_("Minimum depth"), 3, 30,
                                              50), alm.dpbrilliancies))

    liBrilliancies.append((FormLayout.Spinbox(_("Minimum gain points"), 30,
                                              30000, 50), alm.ptbrilliancies))
    liBrilliancies.append(SEPARADOR)

    path_fns = fileNext("Brilliancies", "fns")
    path_pgn = fileNext("Brilliancies", "pgn")

    liBrilliancies.append(
        (None, _("Generate a training file with these moves")))

    config = FormLayout.Fichero(_("List of FENs"),
                                "%s (*.fns)" % _("List of FENs"),
                                True,
                                anchoMinimo=280,
                                ficheroDefecto=path_fns)
    liBrilliancies.append((config, ""))

    config = FormLayout.Fichero(_("PGN Format"),
                                "%s (*.pgn)" % _("PGN Format"),
                                True,
                                anchoMinimo=280,
                                ficheroDefecto=path_pgn)
    liBrilliancies.append((config, ""))

    liBrilliancies.append((_("Also add complete game to PGN"), False))

    liBrilliancies.append(SEPARADOR)

    eti = '"%s"' % _("Find best move")
    liBrilliancies.append(
        (_X(_("Add to the training %1 with the name"), eti) + ":", ""))

    return liBlunders, liBrilliancies
예제 #55
0
    def new(self):
        recno = self.ghistorico.recno()
        if recno >= 0:
            key = self.li_histo[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, position, color, esatacada, esatacante = liGen

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

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

            self.work(recno)
예제 #56
0
    def trainNewEngines(self):
        training = self.dbop.trainingEngines()
        color = "WHITE"
        mandatory = 5
        control = 10
        lost_points = 20
        engine_control = self.configuracion.tutor.clave
        engine_time = 5.0
        num_lista = 0

        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_lista = training.get("NUM_LISTA", num_lista)

        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)

        licombo = [("%2d. %s" % (n + 1, ",".join(x)), n)
                   for n, x in enumerate(self.dbop.listaEngines())]
        config = FormLayout.Combobox(_("Bunch of engines"), licombo)
        liGen.append((config, num_lista))
        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_LISTA"], reg["ENGINE_CONTROL"], reg["ENGINE_TIME"]) = liResp

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

        QTUtil2.mensaje(self, _("Created"))
예제 #57
0
    def create(self):
        name = os.path.basename(self.dbGames.nomFichero)[:-4]
        maxdepth = self.dbGames.depthStat()
        depth = maxdepth
        minGames = min(self.dbGames.reccountTotal() * 10 / 100, 5)
        pointview = 2
        inicio = 0
        mov = self.movActivo()

        while True:
            liGen = [(None, None)]
            liGen.append(( _("Name") + ":", name ))

            liGen.append((FormLayout.Spinbox(_("Depth"), 2, maxdepth, 50), depth))

            liGen.append((None, None))

            liGen.append((FormLayout.Spinbox(_("Minimum games"), 1, 99, 50), minGames))

            liGen.append((None, None))

            liPointV = [pointview,
                        ( 0, _("White") ),
                        ( 1, _("Black") ),
                        ( 2, "%s + %s" % (_("White"), _("Draw") ) ),
                        ( 3, "%s + %s" % (_("Black"), _("Draw") ) ),
            ]
            liGen.append((_("Point of view") + ":", liPointV))

            liGen.append((None, None))

            if mov:
                liInicio = [inicio,
                            ( 0, _("The beginning") ),
                            ( 1, _("Current move") ),
                ]
                liGen.append((_("Start from") + ":", liInicio))

            resultado = FormLayout.fedit(liGen, title=_("Create new guide"), parent=self, anchoMinimo=460,
                                         icon=Iconos.TutorialesCrear())
            if resultado is None:
                return

            accion, liResp = resultado
            name = liResp[0].strip()
            if not name:
                return
            depth = liResp[1]
            minGames = liResp[2]
            pointview = liResp[3]
            if mov:
                inicio = liResp[4]

            ok = True
            for una in self.bookGuide.getTodas():
                if una.strip().upper() == name.upper():
                    QTUtil2.mensError(self, _("The name is repeated"))
                    ok = False
                    continue
            if ok:
                break

        # Grabamos
        um = QTUtil2.unMomento(self)

        # Read stats
        siWhite = pointview % 2 == 0
        siDraw = pointview > 1
        pv = ""
        if mov:
            if inicio > 0:
                pv = self.pvBase + " " + mov["pvmove"]
                pv = pv.strip()

        fichPVs = self.dbGames.flistAllpvs(depth, minGames, siWhite, siDraw, pv)

        # Write to bookGuide
        self.bookGuide.grabarFichSTAT(name, fichPVs)

        # BookGuide
        self.wmoves.inicializa()

        um.final()
예제 #58
0
    def __init__(self, owner, regFlecha, siNombre):

        QtGui.QDialog.__init__(self, owner)

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

        self.siNombre = siNombre

        if not regFlecha:
            regFlecha = TabVisual.PFlecha()

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

        # Tablero
        confTablero = owner.tablero.confTablero.copia(
            owner.tablero.confTablero.id())
        confTablero.anchoPieza(32)
        self.tablero = Tablero.Tablero(self, confTablero, siDirector=False)
        self.tablero.crea()
        self.tablero.copiaPosicionDe(owner.tablero)

        # Datos generales
        liGen = []

        if siNombre:
            # nombre de la flecha que se usara en los menus del tutorial
            config = FormLayout.Editbox(_("Name"), ancho=120)
            liGen.append((config, regFlecha.nombre))

        # ( "forma", "t", "a" ), # a = abierta -> , c = cerrada la cabeza, p = poligono cuadrado,
        liFormas = (
            (_("Opened"), "a"),
            (_("Head closed"), "c"),
            (_("Polygon  1"), "1"),
            (_("Polygon  2"), "2"),
            (_("Polygon  3"), "3"),
        )
        config = FormLayout.Combobox(_("Form"), liFormas)
        liGen.append((config, regFlecha.forma))

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

        # liGen.append( (None,None) )

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

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

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

        # liGen.append( (None,None) )

        # ( "redondeos", "l", False ),
        liGen.append((_("Rounded edges"), regFlecha.redondeos))

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

        # liGen.append( (None,None) )

        # ( "altocabeza", "n", 1 ), # altura de la cabeza
        config = FormLayout.Spinbox(_("Head height"), 0, 100, 50)
        liGen.append((config, regFlecha.altocabeza))

        # ( "ancho", "n", 10 ), # ancho de la base de la flecha si es un poligono
        config = FormLayout.Spinbox(_("Base width"), 1, 100, 50)
        liGen.append((config, regFlecha.ancho))

        # ( "vuelo", "n", 5 ), # vuelo de la flecha respecto al ancho de la base
        config = FormLayout.Spinbox(
            _("Additional width of the base of the head"), 1, 100, 50)
        liGen.append((config, regFlecha.vuelo))

        # ( "descuelgue", "n", 2 ), # vuelo hacia arriba
        config = FormLayout.Spinbox(_("Height of the base angle of the head"),
                                    -100, 100, 50)
        liGen.append((config, regFlecha.descuelgue))

        # liGen.append( (None,None) )

        # ( "destino", "t", "c" ), # c = centro, m = minimo
        config = FormLayout.Combobox(_("Target position"), tiposDestino())
        liGen.append((config, regFlecha.destino))

        # liGen.append( (None,None) )

        # orden
        config = FormLayout.Combobox(_("Order concerning other items"),
                                     QTUtil2.listaOrdenes())
        liGen.append((config, regFlecha.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
        self.tablero.borraMovibles()
        liMovs = ["d2d6", "a8h8", "h5b7"]
        self.liEjemplos = []
        for a1h8 in liMovs:
            regFlecha.a1h8 = a1h8
            regFlecha.siMovible = True
            flecha = self.tablero.creaFlecha(regFlecha)
            self.liEjemplos.append(flecha)
예제 #59
0
    def file(self):
        menu = QTVarios.LCMenu(self)
        menu.opcion("saveas", _("Save a copy"), Iconos.GrabarComo())
        menu.separador()
        menu.opcion("restorefrom", _("Restore from"), Iconos.Recuperar())
        menu.separador()
        submenu = menu.submenu(_("Create new"), Iconos.Nuevo())
        submenu.opcion("new_UNED", _("UNED chess school"), Iconos.Uned())
        submenu.separador()
        submenu.opcion("new_UWE", _("Uwe Auerswald"), Iconos.Uwe())
        submenu.separador()
        submenu.opcion("new_SM", _("Singular moves"), Iconos.Singular())
        menu.separador()
        submenu = menu.submenu(_("Export to"), Iconos.DatabaseMas())
        submenu.opcion("save_pgn", _("A PGN file"), Iconos.FichPGN())
        submenu.separador()
        submenu.opcion("save_db", _("Database"), Iconos.Database())

        resp = menu.lanza()
        if resp is None:
            return
        if resp == "saveas":
            liGen = [(None, None)]
            config = FormLayout.Editbox(_("Name"), ancho=160)
            liGen.append((config, ""))

            resultado = FormLayout.fedit(liGen,
                                         title=_("Name"),
                                         parent=self,
                                         icon=Iconos.GrabarComo())
            if resultado:
                accion, liResp = resultado
                fich = name = liResp[0]
                if name.lower()[-4:] != ".wsm":
                    fich += ".wsm"
                path = os.path.join(self.configuration.carpeta_results, fich)
                ok = True
                if Util.exist_file(path):
                    ok = QTUtil2.pregunta(
                        self,
                        _X(
                            _("The file %1 already exists, what do you want to do?"
                              ), fich),
                        label_yes=_("Overwrite"),
                        label_no=_("Cancel"),
                    )
                if ok:
                    shutil.copy(self.dbwashing.file, path)
        elif resp == "restorefrom":
            li = []
            for fich in os.listdir(self.configuration.carpeta_results):
                if fich.endswith(".wsm") and fich != self.dbwashing.filename:
                    li.append(fich[:-4])
            if not li:
                QTUtil2.message_bold(self, _("There is no file"))
                return
            menu = QTVarios.LCMenu(self)
            for fich in li:
                menu.opcion(fich, fich, Iconos.PuntoRojo())
            resp = menu.lanza()
            if resp:
                if QTUtil2.pregunta(
                        self, "%s\n%s" %
                    (_("Current data will be removed and overwritten."),
                     _("Are you sure?"))):
                    shutil.copy(
                        os.path.join(self.configuration.carpeta_results,
                                     resp + ".wsm"), self.dbwashing.file)
                    self.wreload = True
                    self.save_video()
                    self.accept()
        elif resp.startswith("new_"):
            tactic = resp[4:]
            if QTUtil2.pregunta(
                    self, "%s\n%s" %
                (_("Current data will be removed and overwritten."),
                 _("Are you sure?"))):
                self.dbwashing.new(tactic)
                self.wreload = True
                self.save_video()
                self.accept()

        elif resp.startswith("save_"):

            def other_pc():
                for engine in self.washing.liEngines:
                    if engine.state == Washing.ENDED:
                        game = self.dbwashing.restoreGame(engine)
                        pc = Game.Game()
                        pc.assign_other_game(game)
                        dt = engine.date if engine.date else Util.today()
                        if engine.color:
                            white = self.configuration.x_player
                            black = engine.name
                            result = "1-0"
                            whiteelo = str(self.configuration.x_elo)
                            blackelo = engine.elo
                        else:
                            black = self.configuration.x_player
                            white = engine.name
                            result = "0-1"
                            blackelo = str(self.configuration.x_elo)
                            whiteelo = engine.elo
                        tags = [
                            ["Site", "Lucas Chess"],
                            ["Event", _("The Washing Machine")],
                            ["Date",
                             "%d-%d-%d" % (dt.year, dt.month, dt.day)],
                            ["White", white],
                            ["Black", black],
                            ["WhiteElo", whiteelo],
                            ["BlackElo", blackelo],
                            ["Result", result],
                        ]
                        ap = game.opening
                        if ap:
                            tags.append(["ECO", ap.eco])
                            tags.append(["Opening", ap.trNombre])
                        pc.set_tags(tags)
                        yield pc

            if resp == "save_db":
                ext = "lcg"
                path = QTUtil2.salvaFichero(
                    self,
                    _("Database of complete games"),
                    self.configuration.ficheroDBgames,
                    _("File") + " %s (*.%s)" % (ext, ext),
                    False,
                )
                if path:
                    if not path.lower().endswith(".lcdb"):
                        path += ".lcdb"
                    me = QTUtil2.mensEspera.start(self, _("Saving..."))
                    dbn = DBgames.DBgames(path)
                    for pc in other_pc():
                        dbn.insert(pc)
                    me.final()
                    QTUtil2.message_bold(self, _X(_("Saved to %1"), path))
            else:
                w = WindowSavePGN.WSaveVarios(self, self.configuration)
                if w.exec_():
                    ws = WindowSavePGN.FileSavePGN(self, w.dic_result)
                    if ws.open():
                        ws.um()
                        for n, pc in enumerate(other_pc()):
                            if n or not ws.is_new:
                                ws.write("\n\n")
                        ws.write(pc.pgn())
                    ws.close()
                    ws.um_final()
예제 #60
0
    def gm_crear_queued(self):
        li_engines = self.torneo.list_engines()
        n_engines = len(li_engines)
        if n_engines < 2:
            QTUtil2.message_error(self,
                                  _("You must create at least two engines"))
            return

        dicValores = self.configuration.read_variables("crear_torneo")

        get = dicValores.get

        form = FormLayout.FormLayout(self, _("Games"), Iconos.Torneos())

        form.separador()
        form.spinbox(_("Rounds"), 1, 999, 50, get("ROUNDS", 1))

        form.separador()
        form.float(_("Total minutes"), get("MINUTES", 10.00))

        form.separador()
        form.float(_("Seconds added per move"), get("SECONDS", 0.0))

        form.add_tab(_("Options"))

        li_groups = Util.div_list(li_engines, 30)
        for ngroup, group in enumerate(li_groups):
            for en in group:
                form.checkbox(en.key, get(en.huella, True))
            form.add_tab(_("Engines"))

        resp = form.run()
        if resp is None:
            return

        accion, li_resp = resp

        options = li_resp[0]

        dicValores["ROUNDS"] = rounds = options[0]
        dicValores["MINUTES"] = minutos = options[1]
        dicValores["SECONDS"] = seconds = options[2]

        li_resp_engines = []
        for group in li_resp[1:]:
            li_resp_engines.extend(group)
        liSel = []
        for num in range(self.torneo.num_engines()):
            en = li_engines[num]
            dicValores[en.huella] = si = li_resp_engines[num]
            if si:
                liSel.append(en.huella)

        self.configuration.write_variables("crear_torneo", dicValores)

        nSel = len(liSel)
        if nSel < 2:
            QTUtil2.message_error(self, _("You must use at least two engines"))
            return

        for r in range(rounds):
            for x in range(nSel - 1):
                for y in range(x + 1, nSel):
                    self.torneo.nuevoGame(liSel[x], liSel[y], minutos, seconds)
                    self.torneo.nuevoGame(liSel[y], liSel[x], minutos, seconds)

        self.gridGamesQueued.refresh()
        self.gridGamesQueued.gobottom()
        self.rotulos_tabs()