Example #1
0
    def appendFrom(self, wowner, otraGuide):
        self.grabar()

        otroFichero = self.pathGuide(otraGuide)
        otraConexion = sqlite3.connect(otroFichero)
        otraConexion.text_factory = lambda x: unicode(x, "utf-8", "ignore")

        cursor = otraConexion.cursor()
        cursor.execute("pragma table_info(%s)" % self.tablaDatos)
        liCamposOtra = cursor.fetchall()
        cursor.close()
        if not liCamposOtra:
            return False

        st = set()
        for x in liCamposOtra:
            st.add(x[1])  # nombre
        liselect = ("XPV", "PV", "NAG", "ADV", "COMMENT", "FEN", "MARK",
                    "GRAPHICS", "XDATA")
        libasic = ("XPV", "PV", "FEN")
        li = []
        for x in liselect:
            if x not in st:
                if x in libasic:
                    otraConexion.close()
                    QTUtil2.mensError(wowner,
                                      _("This guide file is not valid"))
                    return False
            else:
                li.append(x)
        select = ",".join(li)
        dbfOtra = SQLDBF.DBF(otraConexion, self.tablaDatos, select)
        dbfOtra.leer()
        reccount = dbfOtra.reccount()

        bp = QTUtil2.BarraProgreso(wowner, otraGuide, "", reccount).mostrar()

        liReg = []
        for recno in range(reccount):
            bp.pon(recno)
            if bp.siCancelado():
                break

            dbfOtra.goto(recno)
            reg = dbfOtra.registroActual()
            liReg.append(reg)
        dbfOtra.cerrar()
        otraConexion.close()

        def dispatch(recno):
            bp.pon(recno)

        if liReg:
            dbf = SQLDBF.DBF(self.conexion, self.tablaDatos, select)
            dbf.insertarLista(liReg, dispatch)
            dbf.cerrar()

        bp.cerrar()

        return len(liReg) > 0
Example #2
0
 def ta_remove(self):
     if QTUtil2.pregunta(self, _("Are you sure?")):
         total = len(self.dbop.db_fenvalues)
         mensaje = _("Move") + "  %d/" + str(total)
         tmpBP = QTUtil2.BarraProgreso(self, "", "", total)
         self.dbop.removeAnalisis(tmpBP, mensaje)
         tmpBP.cerrar()
         self.glines.refresh()
    def export_create_polyglot(self, path_bin, uniform):
        total = len(self.db_entries)

        bp = QTUtil2.BarraProgreso(self.wpolyglot, _("Create book"),
                                   os.path.basename(path_bin), total)
        wpoly = FasterCode.PolyglotWriter(path_bin)

        bp.mostrar()
        li_current = []
        key_current = 0

        def save():
            if not li_current:
                return
            factor = None
            if not uniform:
                weight_max = max(xentry.weight for xentry in li_current)
                if weight_max >= 32767:
                    factor = 32767 / weight_max
            for xentry in li_current:
                if xentry.weight > 0:
                    if uniform:
                        xentry.weight = 100
                    elif factor:
                        xentry.weight = max(int(factor * xentry.weight), 1)
                    if xentry.score > 32767:
                        xentry.score = 32767
                    if xentry.depth > 255:
                        xentry.depth = 255
                    if xentry.learn > 255:
                        xentry.learn = 255
                    wpoly.write(xentry)

        for entry in self.db_entries.get_all():
            bp.inc()
            if entry is None:
                break
            if entry.key != key_current:
                save()
                key_current = entry.key
                li_current = [
                    entry,
                ]
            else:
                li_current.append(entry)
        save()

        wpoly.close()
        bp.close()
        QTUtil2.message_bold(self.wpolyglot, "%s\n%s" % (_("Saved"), path_bin))
Example #4
0
    def importarPGN(self, owner, gamebase, ficheroPGN, maxDepth, variations):

        dlTmp = QTUtil2.BarraProgreso(owner, _("Import"), _("Working..."),
                                      Util.filesize(ficheroPGN)).mostrar()

        self.saveHistory(_("Import"), _("PGN with variations"),
                         os.path.basename(ficheroPGN))

        cursor = self._conexion.cursor()

        base = gamebase.pv() if gamebase else self.getconfig("BASEPV")

        sql_insert = "INSERT INTO LINES( XPV ) VALUES( ? )"
        sql_update = "UPDATE LINES SET XPV=? WHERE XPV=?"

        for n, (nbytes, game) in enumerate(Game.read_games(ficheroPGN)):
            dlTmp.pon(nbytes)

            li_pv = game.all_pv("", variations)
            for pv in li_pv:
                li = pv.split(" ")[:maxDepth]
                pv = " ".join(li)

                if base and not pv.startswith(base) or base == pv:
                    continue
                xpv = FasterCode.pv_xpv(pv)
                updated = False
                for npos, xpv_ant in enumerate(self.li_xpv):
                    if xpv_ant.startswith(xpv):
                        updated = True
                        break
                    if xpv.startswith(xpv_ant) and xpv > xpv_ant:
                        cursor.execute(sql_update, (xpv, xpv_ant))
                        self.li_xpv[npos] = xpv
                        updated = True
                        break
                if not updated:
                    if len(xpv) > 0:
                        cursor.execute(sql_insert, (xpv, ))
                        self.li_xpv.append(xpv)

            if n % 50:
                self._conexion.commit()

        cursor.close()
        self.li_xpv.sort()
        self._conexion.commit()
        dlTmp.cerrar()
Example #5
0
def update_file(titulo, urlfichero, tam):
    shutil.rmtree("actual", ignore_errors=True)
    Util.create_folder("actual")

    # Se trae el file
    global progreso, is_beginning
    progreso = QTUtil2.BarraProgreso(None, titulo, _("Updating..."),
                                     100).mostrar()
    is_beginning = True

    def hook(bloques, tambloque, tamfichero):
        global progreso, is_beginning
        if is_beginning:
            total = tamfichero / tambloque
            if tambloque * total < tamfichero:
                total += 1
            progreso.ponTotal(total)
            is_beginning = False
        progreso.inc()

    local_file = urlfichero.split("/")[-1]
    local_file = "actual/%s" % local_file
    urllib.request.urlretrieve(urlfichero, local_file, hook)

    is_canceled = progreso.is_canceled()
    progreso.cerrar()

    if is_canceled:
        return False

    # Comprobamos que se haya traido bien el file
    if tam != Util.filesize(local_file):
        return False

    # Se descomprime
    zp = zipfile.ZipFile(local_file, "r")
    zp.extractall("actual")

    # Se ejecuta act.py
    exec(open("actual/act.py").read())

    return True
    def import_polyglot(self):
        dic = self.configuration.read_variables("POLYGLOT_IMPORT")

        folder = dic.get("FOLDER_BIN", "")

        path_bin = QTUtil2.leeFichero(self.wpolyglot,
                                      folder,
                                      "bin",
                                      titulo=_("Polyglot bin file name"))
        if not path_bin:
            return

        dic["FOLDER_BIN"] = os.path.dirname(path_bin)
        self.configuration.write_variables("POLYGLOT_IMPORT", dic)

        total = Util.filesize(path_bin) // 16
        if total <= 0:
            return

        collisions = "replace"
        if len(self.db_entries) > 0:
            collisions = self.menu_collisions()
            if not collisions:
                return

        bp = QTUtil2.BarraProgreso(self.wpolyglot, _("Import"),
                                   os.path.basename(path_bin), total)

        pol_import = FasterCode.Polyglot(path_bin)
        for entry in pol_import:
            bp.inc()
            self.db_entries.replace_entry(entry, collisions)
        self.db_entries.commit()
        pol_import.close()
        bp.close()
        QTUtil2.message_bold(self.wpolyglot,
                             "%s\n%s" % (_("Imported"), path_bin))
        self.wpolyglot.set_position(self.wpolyglot.position, False)
Example #7
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()
    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.configuracion.tiempoTutor / 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))

            xgestor = self.procesador.creaGestorMotor(self.configuracion.tutor,
                                                      ms,
                                                      0,
                                                      siMultiPV=False)

            st_borrar = set()

            ok = True

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

                if tmpBP.siCancelado():
                    ok = False
                    break

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

                max_puntos = -999999
                max_pv = None
                dicPV = dic[fen]
                for pv in dicPV:
                    if tmpBP.siCancelado():
                        ok = False
                        break
                    LCEngine.setFen(fen)
                    LCEngine.movePV(pv[:2], pv[2:4], pv[4:])
                    mrm = xgestor.analiza(fen)
                    rm = mrm.mejorMov()
                    pts = rm.puntosABS()
                    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()

            xgestor.terminar()

            if ok:
                li_borrar = list(st_borrar)
                n = len(li_borrar)
                if n:
                    self.dbop.removeLines(li_borrar, _("Remove worst lines"))
                    QTUtil2.mensaje(self, _("Removed %d lines") % n)
                else:
                    QTUtil2.mensaje(self, _("Done"))
Example #9
0
    def crearFNS(self):

        configuracion = self.gestor.configuracion
        Util.creaCarpeta(configuracion.dirPersonalTraining)
        resp = QTUtil2.salvaFichero(self, _("File to save"),
                                    configuracion.dirPersonalTraining,
                                    _("List of FENs") + " (*.fns)", False)
        if not resp:
            return
        modo = "w"
        if Util.existeFichero(resp):
            yn = QTUtil2.preguntaCancelar(
                self,
                _X(_("The file %1 already exists, what do you want to do?"),
                   resp),
                si=_("Append"),
                no=_("Overwrite"))
            if yn is None:
                return
            if yn:
                modo = "a"
        f = codecs.open(resp, modo, 'utf-8', 'ignore')

        liSeleccionadas = self.grid.recnosSeleccionados()
        nSeleccionadas = len(liSeleccionadas)
        siSeleccionadas = nSeleccionadas > 1

        if siSeleccionadas:
            nregs = nSeleccionadas
        else:
            nregs = self.dbf.reccount()

        tmpBP = QTUtil2.BarraProgreso(self, _("List of FENs"), _("Game"),
                                      nregs)
        tmpBP.mostrar()

        # eventAnt = ""

        for n in range(nregs):

            if tmpBP.siCancelado():
                break

            tmpBP.pon(n + 1)

            if siSeleccionadas:
                n = liSeleccionadas[n]

            self.dbf.goto(n)
            self.grid.goto(n, 0)

            jugadas = self.dbf.leeOtroCampo(n,
                                            "PGN").replace("\n", " ").replace(
                                                "\r", "").strip()

            dic = self.dbf.dicValores()

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

            fen = dic["FEN"]
            if not fen:
                if not jugadas.strip("*"):
                    continue
                fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
            event = xdic("EVENT")
            # if event:
            # eventAnt = event
            # else:
            # event = eventAnt
            site = xdic("SITE")
            date = xdic("DATE")
            if site == event:
                es = event
            else:
                es = event + " " + site
            es = es.strip()
            if date:
                if es:
                    es += " (%s)" % date
                else:
                    es = date
            white = xdic("WHITE")
            black = xdic("BLACK")
            wb = ("%s-%s" % (white, black)).strip("-")
            titulo = ""
            if es:
                titulo += "<br>%s" % es
            if wb:
                titulo += "<br>%s" % wb

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

            f.write(txt)

        f.close()
        tmpBP.cerrar()
        QTUtil2.mensaje(self, "%s" % _X(_("Saved to %1"), resp))
        self.gestor.procesador.entrenamientos.rehaz()
Example #10
0
def crearTactic(procesador, wowner, liRegistros, rutinaDatos):
    # Se pide el nombre de la carpeta
    liGen = [(None, None)]

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

    liGen.append((None, None))

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

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

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

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

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

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

    fen0 = ControlPosicion.FEN_INICIAL

    for n in range(nregs):

        if tmpBP.siCancelado():
            break

        tmpBP.pon(n + 1)

        recno = liRegistros[n]

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

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

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

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

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

        f.write(txt)

    f.close()
    tmpBP.cerrar()

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

    Util.dic8ini(nomIni, dicIni)

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

    procesador.entrenamientos.rehaz()
Example #11
0
    def importarPGN(self, owner, partidabase, ficheroPGN, maxDepth,
                    variations):

        dlTmp = QTUtil2.BarraProgreso(owner, _("Import"), _("Working..."),
                                      Util.filesize(ficheroPGN)).mostrar()

        self.saveHistory(_("Import"), _("PGN with variations"),
                         os.path.basename(ficheroPGN))

        cursor = self._conexion.cursor()

        base = partidabase.pv() if partidabase else self.getconfig("BASEPV")

        sql_insert = "INSERT INTO LINES( XPV ) VALUES( ? )"
        sql_update = "UPDATE LINES SET XPV=? WHERE XPV=?"

        for n, (nbytes, p) in enumerate(Game.read_games(ficheroPGN)):
            dlTmp.pon(nbytes)

            def haz_partida(game, mx):
                njg = len(game)
                if njg > mx:
                    game.li_moves = game.li_moves[:mx]
                pv = game.pv()
                if base and not pv.startswith(base):
                    return
                xpv = FasterCode.pv_xpv(pv)
                updated = False
                for npos, xpv_ant in enumerate(self.li_xpv):
                    if xpv_ant.startswith(xpv):
                        return
                    if xpv.startswith(xpv_ant):
                        cursor.execute(sql_update, (xpv, xpv_ant))
                        self.li_xpv[npos] = xpv
                        updated = True
                        break
                if not updated:
                    cursor.execute(sql_insert, (xpv, ))
                    self.li_xpv.append(xpv)

                if variations != "N":  # None
                    for njug, move in enumerate(game.li_moves):
                        ok = True
                        if variations != "A":
                            if variations == "W":
                                if njug % 2 == 1:
                                    ok = False
                            elif variations == "B":
                                if njug % 2 == 0:
                                    ok = False
                        if ok:
                            for pvar in move.variations.list_games():
                                if len(pvar):
                                    if mx - njug > 0:
                                        haz_partida(pvar, mx - njug)

            haz_partida(p, maxDepth)
            if n % 50:
                self._conexion.commit()

        cursor.close()
        self.li_xpv.sort()
        self._conexion.commit()
        dlTmp.cerrar()
Example #12
0
    def gm(self):

        liSelec = self.grid.recnosSeleccionados()

        # Datos
        liGen = [(None, None)]

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

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

        liGen.append((_("Only selected games") + ":", len(liSelec) > 1))

        li = [
            1, (0, _("Both sides")), (1, _("Only the winning side")),
            (2, _("The winning side and both if drawn"))
        ]

        liGen.append((_("Which side") + ":", li))

        eti = _("Play like a grandmaster")
        eti = _X(_('Create training to %1'), eti)
        resultado = FormLayout.fedit(liGen,
                                     title=eti,
                                     parent=self,
                                     anchoMinimo=460,
                                     icon=Iconos.GranMaestro())

        if not resultado:
            return
        accion, liGen = resultado
        nombre = liGen[0]
        jugador = liGen[1]
        siSelec = liGen[2]
        result = liGen[3]

        if not nombre:
            return

        liJugadores = jugador.upper().split(";") if jugador else None

        # Se crea el objeto de ejecucion
        fgm = GM.FabGM(self.gestor.configuracion, nombre, liJugadores)

        # Se pasan todas las partidas
        if not siSelec:
            liSelec = range(self.dbf.reccount())

        nregs = len(liSelec)
        mensaje = _("Game") + "  %d/" + str(nregs)
        tmpBP = QTUtil2.BarraProgreso(self, eti, "", nregs).mostrar()

        for n, recno in enumerate(liSelec):

            if tmpBP.siCancelado():
                break

            self.dbf.goto(recno)

            if n:
                tmpBP.pon(n)
            tmpBP.mensaje(mensaje % (n + 1, ))

            jugadas = self.dbf.leeOtroCampo(n, "PGN")

            pgn = PGN.UnPGN()
            pgn.leeTexto(jugadas)

            fgm.masMadera(pgn, pgn.partida, result)

        siCancelado = tmpBP.siCancelado()
        tmpBP.cerrar()

        if not siCancelado:
            # Se ejecuta
            siCreado = fgm.xprocesa()

            if siCreado:
                liCreados = [nombre]
                liNoCreados = None
            else:
                liNoCreados = [nombre]
                liCreados = None
            mensajeEntrenamientos(self, liCreados, liNoCreados)
Example #13
0
    def creaDB(self, ventana, fichero, uno):

        titulo = os.path.basename(fichero)
        tmpBP = QTUtil2.BarraProgreso(ventana, titulo, _("Working..."),
                                      Util.tamFichero(fichero)).mostrar()

        dClaves = Util.SymbolDict(
        )  # contiene tam maximo de los campos a mostrar

        def iniDB():
            fichDB = uno["PATHDB"]
            Util.borraFichero(fichDB)
            bd = SQLBase.DBBase(fichDB)

            tb = SQLBase.TablaBase("GAMES")
            tb.liCampos = []
            for clave in dClaves:
                tb.liCampos.append(SQLBase.Campo(clave.upper(), 'VARCHAR'))
            if "PLIES" not in dClaves:
                tb.liCampos.append(SQLBase.Campo("PLIES", 'VARCHAR'))
                dClaves["PLIES"] = 4
            if "PGN" not in dClaves:
                tb.liCampos.append(SQLBase.Campo("PGN", 'TEXT'))
            cursor = bd.conexion.cursor()
            tb.crearBase(cursor)
            cursor.close()
            dbf = bd.dbf("GAMES", (",".join(dClaves.keys())) + ",PGN")
            return bd, dbf

        jg = 0
        dbf = None
        for g in PGNreader.readGames(fichero):

            if tmpBP.siCancelado():
                break

            tmpBP.pon(g.nbytes)

            if g.erroneo:
                continue

            if not dbf:
                for clave, valor in g.labels.iteritems():
                    if valor == "?":
                        continue
                    dClaves[clave] = len(valor)
                bd, dbf = iniDB()

            else:
                for clave, valor in g.labels.iteritems():
                    if valor == "?":
                        continue
                    tam = len(valor)
                    if clave not in dClaves:
                        dbf.nuevaColumna(clave.upper(), 'VARCHAR')
                        dClaves[clave] = tam
                    else:
                        if dClaves[clave] < tam:
                            dClaves[clave] = tam

            dic = {}
            for k, v in g.labels.iteritems():
                if v == "?":
                    continue
                dic[k] = v
            dic["PGN"] = g.pgn
            pv = g.pv()
            dic["PLIES"] = pv.count(" ") + 1 if pv else 0
            jg += 1
            dbf.soloGrabar(dic, jg % 10000 == 0)

        if not dbf:
            bd, dbf = iniDB()
        dbf.commit()  # Graba los ultimos
        dbf.cerrar()
        bd.cerrar()

        tmpBP.close()

        uno["DCLAVES"] = dClaves

        return True
Example #14
0
 def pb(self, total):
     self._pb = QTUtil2.BarraProgreso(self.owner, self.file, "", total)
     self._pb_total = total
     self.pb_pos(0)
Example #15
0
def analysis_game(manager):
    game = manager.game
    procesador = manager.procesador
    main_window = manager.main_window

    alm = WindowAnalysisParam.analysis_parameters(main_window,
                                                  procesador.configuration,
                                                  True)

    if alm is None:
        return

    li_moves = []
    lni = Util.ListaNumerosImpresion(alm.num_moves)
    num_move = int(game.primeraJugada())
    is_white = not game.if_starts_with_black
    for nRaw in range(game.num_moves()):
        must_save = lni.siEsta(num_move)
        if must_save:
            if is_white:
                if not alm.white:
                    must_save = False
            elif not alm.black:
                must_save = False
        if must_save:
            li_moves.append(nRaw)
        is_white = not is_white
        if is_white:
            num_move += 1

    mensaje = _("Analyzing the move....")
    num_moves = len(li_moves)
    tmp_bp = QTUtil2.BarraProgreso(main_window, _("Analysis"), mensaje,
                                   num_moves).show_top_right()

    ap = AnalyzeGame(procesador, alm, False, li_moves)

    def dispatch_bp(pos, ntotal, njg):
        tmp_bp.mensaje(mensaje + " %d/%d" % (pos + 1, ntotal))
        move = game.move(njg)
        manager.set_position(move.position)
        manager.main_window.pgnColocate(njg / 2, (njg + 1) % 2)
        manager.board.put_arrow_sc(move.from_sq, move.to_sq)
        manager.put_view()

    ap.dispatch_bp(dispatch_bp)

    ap.xprocesa(game, tmp_bp)

    not_canceled = not tmp_bp.is_canceled()
    ap.terminar(not_canceled)

    if not_canceled:
        li_creados = []
        li_no_creados = []

        if alm.tacticblunders:
            if ap.siTacticBlunders:
                li_creados.append(alm.tacticblunders)
            else:
                li_no_creados.append(alm.tacticblunders)

        for x in (alm.pgnblunders, alm.fnsbrilliancies, alm.pgnbrilliancies):
            if x:
                if Util.exist_file(x):
                    li_creados.append(x)
                else:
                    li_no_creados.append(x)

        if alm.bmtblunders:
            if ap.si_bmt_blunders:
                li_creados.append(alm.bmtblunders)
            else:
                li_no_creados.append(alm.bmtblunders)
        if alm.bmtbrilliancies:
            if ap.si_bmt_brilliancies:
                li_creados.append(alm.bmtbrilliancies)
            else:
                li_no_creados.append(alm.bmtbrilliancies)

        if li_creados or li_no_creados:
            WDB_Utils.mensajeEntrenamientos(main_window, li_creados,
                                            li_no_creados)

    tmp_bp.cerrar()

    manager.goto_end()

    if not_canceled:
        if alm.show_graphs:
            manager.show_analysis()
Example #16
0
    def createTactics(self):
        nameTactic = os.path.basename(self.entreno)[:-4]

        nomDir = os.path.join(self.configuracion.dirPersonalTraining,
                              "Tactics", nameTactic)
        if os.path.isdir(nomDir):
            nom = nomDir + "-%d"
            n = 1
            while os.path.isdir(nom % n):
                n += 1
            nomDir = nom % n
        nomIni = os.path.join(nomDir, "Config.ini")
        nomTactic = "TACTIC1"
        nomDirTac = os.path.join(VarGen.configuracion.dirPersonalTraining,
                                 "Tactics")
        Util.creaCarpeta(nomDirTac)
        Util.creaCarpeta(nomDir)
        nomFNS = os.path.join(nomDir, "Puzzles.fns")

        # Se leen todos los fens
        f = open(self.entreno)
        liBase = []
        for linea in f:
            liBase.append(linea.strip())
        f.close()

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

        tmpBP = QTUtil2.BarraProgreso(self.pantalla, nameTactic,
                                      _("Working..."), nregs)
        tmpBP.mostrar()

        for n in range(nregs):

            if tmpBP.siCancelado():
                break

            tmpBP.pon(n + 1)

            linea = liBase[n]
            li = linea.split("|")
            fen = li[0]
            if len(li) < 3 or not li[2]:
                # tutor a trabajar
                mrm = self.xrival.analiza(fen)
                if not mrm.liMultiPV:
                    continue
                rm = mrm.liMultiPV[0]
                p = Partida.Partida(fen=fen)
                p.leerPV(rm.pv)
                pts = rm.puntosABS()
                jg = p.jugada(0)
                for pos, rm1 in enumerate(mrm.liMultiPV):
                    if pos:
                        if rm1.puntosABS() == pts:
                            p1 = Partida.Partida(fen=fen)
                            p1.leerPV(rm1.pv)
                            if pos > 1:
                                jg.variantes += "\n"
                            jg.variantes += p1.pgnBaseRAW()
                        else:
                            break

                jugadas = p.pgnBaseRAW()
                txt = fen + "||%s\n" % jugadas
            else:
                txt = linea

            f.write(txt)

        f.close()
        tmpBP.cerrar()

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

        Util.dic8ini(nomIni, dicIni)

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

        self.procesador.entrenamientos.rehaz()
Example #17
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()
Example #18
0
    def importarPGN(self, owner, gamebase, ficheroPGN, maxDepth, with_variations, with_comments):

        dlTmp = QTUtil2.BarraProgreso(owner, _("Import"), _("Working..."), Util.filesize(ficheroPGN)).mostrar()

        self.saveHistory(_("Import"), _("PGN with variations"), os.path.basename(ficheroPGN))

        dic_comments = {}

        cursor = self._conexion.cursor()

        base = gamebase.pv() if gamebase else self.getconfig("BASEPV")

        sql_insert = "INSERT INTO LINES( XPV ) VALUES( ? )"
        sql_update = "UPDATE LINES SET XPV=? WHERE XPV=?"

        for n, (nbytes, game) in enumerate(Game.read_games(ficheroPGN)):
            dlTmp.pon(nbytes)

            li_pv = game.all_pv("", with_variations)
            for pv in li_pv:
                li = pv.split(" ")[:maxDepth]
                pv = " ".join(li)

                if base and not pv.startswith(base) or base == pv:
                    continue
                xpv = FasterCode.pv_xpv(pv)
                updated = False
                for npos, xpv_ant in enumerate(self.li_xpv):
                    if xpv_ant.startswith(xpv):
                        updated = True
                        break
                    if xpv.startswith(xpv_ant) and xpv > xpv_ant:
                        cursor.execute(sql_update, (xpv, xpv_ant))
                        self.li_xpv[npos] = xpv
                        updated = True
                        break
                if not updated:
                    if len(xpv) > 0:
                        cursor.execute(sql_insert, (xpv,))
                        self.li_xpv.append(xpv)

            if with_comments:
                dic_comments_game = game.all_comments(with_variations)
                for fenm2, dic in dic_comments_game.items():
                    d = self.getfenvalue(fenm2)
                    if "C" in dic:
                        d["COMENTARIO"] = dic["C"]
                    if "N" in dic:
                        for nag in dic["N"]:
                            if nag in (11, 14, 15, 16, 17, 18, 19):
                                d["VENTAJA"] = nag
                            elif 0 < nag < 7:
                                d["VALORACION"] = nag
                    if d:
                        dic_comments[fenm2] =  d

            if n % 50:
                self._conexion.commit()

        cursor.close()
        self.li_xpv.sort()
        self._conexion.commit()
        dlTmp.cerrar()
        if with_comments and dic_comments:
            self.db_fenvalues.set_faster_mode()
            um = QTUtil2.unMomento(owner)
            for fenm2, dic_comments_game in dic_comments.items():
                self.setfenvalue(fenm2, dic_comments_game)
            self.db_fenvalues.set_normal_mode()
            um.final()
Example #19
0
def analizaPartida(gestor):
    partida = gestor.partida
    procesador = gestor.procesador
    pantalla = gestor.pantalla
    pgn = gestor.pgn

    alm = PantallaAnalisisParam.paramAnalisis(pantalla,
                                              procesador.configuracion, True)

    if alm is None:
        return

    liJugadas = []
    lni = Util.ListaNumerosImpresion(alm.jugadas)
    numJugada = int(partida.primeraJugada())
    siBlancas = not partida.siEmpiezaConNegras
    for nRaw in range(partida.numJugadas()):
        siGrabar = lni.siEsta(numJugada)
        if siGrabar:
            if siBlancas:
                if not alm.blancas:
                    siGrabar = False
            elif not alm.negras:
                siGrabar = False
        if siGrabar:
            liJugadas.append(nRaw)
        siBlancas = not siBlancas
        if siBlancas:
            numJugada += 1

    mensaje = _("Analyzing the move....")
    numJugadas = len(liJugadas)
    tmpBP = QTUtil2.BarraProgreso(pantalla, _("Analysis"), mensaje,
                                  numJugadas).mostrarAD()

    ap = AnalizaPartida(procesador, alm, False, liJugadas)

    def dispatchBP(pos, ntotal, njg):
        tmpBP.mensaje(mensaje + " %d/%d" % (pos + 1, ntotal))
        jg = partida.jugada(njg)
        gestor.ponPosicion(jg.posicion)
        gestor.pantalla.pgnColocate(njg / 2, (njg + 1) % 2)
        gestor.tablero.ponFlechaSC(jg.desde, jg.hasta)
        gestor.ponVista()

    ap.dispatchBP(dispatchBP)

    ap.xprocesa(pgn.dicCabeceraActual(), partida, tmpBP, pgn.actual())

    notCanceled = not tmpBP.siCancelado()
    ap.terminar(notCanceled)

    if notCanceled:
        liCreados = []
        liNoCreados = []

        if alm.tacticblunders:
            if ap.siTacticBlunders:
                liCreados.append(alm.tacticblunders)
            else:
                liNoCreados.append(alm.tacticblunders)

        for x in (alm.pgnblunders, alm.fnsbrilliancies, alm.pgnbrilliancies):
            if x:
                if Util.existeFichero(x):
                    liCreados.append(x)
                else:
                    liNoCreados.append(x)

        if alm.bmtblunders:
            if ap.siBMTblunders:
                liCreados.append(alm.bmtblunders)
            else:
                liNoCreados.append(alm.bmtblunders)
        if alm.bmtbrilliancies:
            if ap.siBMTbrilliancies:
                liCreados.append(alm.bmtbrilliancies)
            else:
                liNoCreados.append(alm.bmtbrilliancies)

        if liCreados or liNoCreados:
            PantallaPGN.mensajeEntrenamientos(pantalla, liCreados, liNoCreados)

    tmpBP.cerrar()

    gestor.ponteAlFinal()

    if notCanceled:
        if alm.showGraphs:
            gestor.showAnalisis()
Example #20
0
    def remove_worst(self):
        form = FormLayout.FormLayout(self, _("Remove worst lines"),
                                     Iconos.OpeningLines())
        form.separador()
        liJ = [(_("White"), "WHITE"), (_("Black"), "BLACK")]
        form.combobox(_("Side"), liJ, "WHITE")
        form.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))
        form.combobox(_("Book"), libooks, None)
        form.separador()

        form.float(_("Duration of engine analysis (secs)"),
                   float(self.configuration.x_tutor_mstime / 1000.0))
        form.separador()

        resultado = form.run()
        if resultado:
            color, book, segs = resultado[1]
            ms = int(segs * 1000)
            if ms == 0:
                return
            if book:
                book.polyglot()
            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)

                dic_a1h8 = dic[fen]
                st_a1h8 = set(dic_a1h8.keys())
                li = []
                if book:
                    li_moves = book.get_list_moves(fen)
                    if li_moves:
                        # (from_sq, to_sq, promotion, "%-5s -%7.02f%% -%7d" % (pgn, pc, w), 1.0 * w / maxim))
                        li = [(m[0] + m[1] + m[2], m[4]) for m in li_moves
                              if m[0] + m[1] + m[2] in st_a1h8]
                        if li:
                            li.sort(key=lambda x: x[1], reverse=True)
                            st_ya = set(x[0] for x in li)
                            for a1h8 in st_a1h8:
                                if a1h8 not in st_ya:
                                    li.append((a1h8, 0))

                if len(li) == 0:
                    mrm = xmanager.analiza(fen)
                    for a1h8 in dic_a1h8:
                        rm, pos = mrm.buscaRM(a1h8)
                        li.append((a1h8, pos))
                    li.sort(key=lambda x: x[1])

                for a1h8, pos in li[1:]:
                    for num_linea in dic_a1h8[a1h8]:
                        st_borrar.add(num_linea)

            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"))
Example #21
0
    def create_tactics(self):
        name_tactic = os.path.basename(self.entreno)[:-4]

        nom_dir = os.path.join(self.configuracion.dirPersonalTraining,
                               "Tactics", name_tactic)
        if os.path.isdir(nom_dir):
            nom = nom_dir + "-%d"
            n = 1
            while os.path.isdir(nom % n):
                n += 1
            nom_dir = nom % n
        nom_ini = os.path.join(nom_dir, "Config.ini")
        nom_tactic = "TACTIC1"
        nom_dir_tac = os.path.join(Code.configuracion.dirPersonalTraining,
                                   "Tactics")
        Util.create_folder(nom_dir_tac)
        Util.create_folder(nom_dir)
        nom_fns = os.path.join(nom_dir, "Puzzles.fns")

        # Se leen todos los fens
        with open(self.entreno, "rt", errors="ignore") as f:
            liBase = [linea.strip() for linea in f if linea.strip()]

        # Se crea el fichero con los puzzles
        nregs = len(liBase)
        tmpBP = QTUtil2.BarraProgreso(self.main_window, name_tactic,
                                      _("Working..."), nregs)
        tmpBP.mostrar()
        with open(nom_fns, "wt") as q:
            for n in range(nregs):

                if tmpBP.is_canceled():
                    break

                tmpBP.pon(n + 1)

                linea = liBase[n]
                li = linea.split("|")
                fen = li[0]
                if len(li) < 3 or not li[2]:
                    # tutor a trabajar
                    mrm = self.xrival.analiza(fen)
                    if not mrm.li_rm:
                        continue
                    rm = mrm.li_rm[0]
                    p = Game.Game(fen=fen)
                    p.read_pv(rm.pv)
                    pts = rm.centipawns_abs()
                    move = p.move(0)
                    for pos, rm1 in enumerate(mrm.li_rm):
                        if pos:
                            if rm1.centipawns_abs() == pts:
                                p1 = Game.Game(fen=fen)
                                p1.read_pv(rm1.pv)
                                move.add_variation(p1)
                            else:
                                break

                    num_moves = p.pgnBaseRAW()
                    txt = fen + "||%s\n" % num_moves
                else:
                    txt = linea

                q.write(txt + "\n")

        tmpBP.cerrar()

        # Se crea el fichero de control
        dicIni = {}
        dicIni[nom_tactic] = d = {}
        d["MENU"] = name_tactic
        d["FILESW"] = "%s:100" % os.path.basename(nom_fns)

        nom_dir = Util.relative_path(os.path.realpath(nom_dir))

        Util.dic2ini(nom_ini, dicIni)

        name = os.path.basename(nom_dir)

        QTUtil2.message(
            self.main_window,
            _X(_("Tactic training %1 created."), nom_dir),
            explanation=_X(
                _("You can access this training from menu Train - Learn tactics by repetition - %1"
                  ), name),
        )

        self.procesador.entrenamientos.rehaz()