Example #1
0
    def damePGNtemporal(self, wowner):
        total = self.dbGames.reccount()
        if total < 1:
            return None
        fichTemporalPGN = self.configuracion.ficheroTemporal("pgn")
        pb = QTUtil2.BarraProgreso1(wowner, _("Creating temporary PGN file..."), formato1="%p%")
        pb.mostrar()
        pb.ponTotal(total)

        with open(fichTemporalPGN, "wb") as q:
            for recno in range(self.dbGames.reccount()):
                pb.pon(recno)
                if pb.siCancelado():
                    fichTemporalPGN = None
                    break
                pgn, result = self.dbGames.leePGNRecno(recno)
                if result:
                    result = result.replace(" ", "")
                    if result in ("1-0", "0-1", "1/2-1/2"):
                        jg = pgn.strip().replace("e.p.", "").replace("#+", "#")
                        if not jg.endswith(result):
                            jg += " " + result
                        q.write(jg + "\n\n")
            pb.close()
            return fichTemporalPGN
    def tg_exportar_PGN(self):
        resp = self.tg_exportar("pgn")
        if not resp:
            return
        li, modo, path = resp

        try:
            fpgn = codecs.open(path, modo, 'utf-8', 'ignore')
        except:
            QTUtil2.mensError(self, "%s : %s\n" % (_("Unable to save"), path))
            return

        pb = QTUtil2.BarraProgreso1(self, _("Exporting..."))
        pb.mostrar()
        total = len(li)
        pb.ponTotal(total)

        if modo == "a":
            fpgn.write("\n\n")
        for n, recno in enumerate(li):
            p = self.dbGamesFEN.leePartidaRecno(recno)
            pb.pon(n + 1)
            if pb.siCancelado():
                break
            fpgn.write(p.pgn())
            fpgn.write("\n\n")

        fpgn.close()
        pb.cerrar()
        QTUtil2.mensaje(self, _X(_("Saved to %1"), path))
Example #3
0
    def tg_exportar_PGN(self):
        li = self.listaSelected()
        if li:
            w = PantallaSavePGN.WSaveVarios(self, self.configuracion)
            if w.exec_():
                ws = PantallaSavePGN.FileSavePGN(self, w.dic_result)
                if ws.open():
                    pb = QTUtil2.BarraProgreso1(self, _("Saving..."), formato1="%p%")
                    pb.mostrar()
                    pb.ponTotal(len(li))
                    for n, recno in enumerate(li):
                        pb.pon(n)
                        pgn, result = self.dbGames.leePGNRecno(recno)
                        if pb.siCancelado():
                            break
                        if n > 0 or not ws.is_new:
                            ws.write("\n\n")
                        pgn = pgn.strip().replace("e.p.", "").replace("#+", "#")
                        if result in ( "*", "1-0", "0-1", "1/2-1/2"):
                            if not pgn.endswith(result):
                                pgn += " " + result
                        ws.write(pgn + "\n\n")

                    pb.close()
                    ws.close()
Example #4
0
    def reindexar(self, depth=None):
        if depth is None or self.wb_database.is_temporary:
            # if not QTUtil2.pregunta(self, _("Do you want to rebuild stats?")):
            #     return

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

            config = FormLayout.Spinbox(_("Depth"), 0, 255, 50)
            li_gen.append((config, self.dbGames.depth_stat()))

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

            accion, li_resp = resultado

            depth = li_resp[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.is_canceled()

        self.dbGames.rebuild_stat(dispatch, depth)
        bpTmp.cerrar()
        self.start()
Example #5
0
    def tw_exportar_pgn(self, only_selected):
        w = PantallaSavePGN.WSaveVarios(self, self.configuracion)
        if w.exec_():
            ws = PantallaSavePGN.FileSavePGN(self, w.dic_result)
            if ws.open():
                sp = "\r\n" if ws.crlf else "\n"
                pb = QTUtil2.BarraProgreso1(self, _("Saving..."), formato1="%p%")
                pb.mostrar()
                if only_selected:
                    li_sel = self.grid.recnosSeleccionados()
                else:
                    li_sel = list(range(self.dbGames.reccount()))
                pb.ponTotal(len(li_sel))
                for n, recno in enumerate(li_sel):
                    pb.pon(n)
                    pgn, result = self.dbGames.leePGNRecno(recno, sp)
                    if pb.is_canceled():
                        break
                    if n > 0 or not ws.is_new:
                        ws.write(sp + sp)
                    if result in ("*", "1-0", "0-1", "1/2-1/2"):
                        if not pgn.endswith(result):
                            pgn += " " + result
                    ws.write(pgn + sp)

                pb.close()
                ws.close()
Example #6
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))

        config = FormLayout.Spinbox(_("Depth"), 3, 255, 50)
        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.inicio()
Example #7
0
    def databases(self):
        dic = self.configuration.read_variables("VERSION11")
        titulo = _("Select the folder with the %s to be imported") % _(
            "Databases")
        QTUtil2.message(self.wowner, titulo)
        folder = QTUtil2.leeCarpeta(self.wowner,
                                    dic.get("FOLDER", "../.."),
                                    titulo=titulo)
        if not folder:
            return
        um = QTUtil2.unMomento(
            self.wowner,
            _("Working...") + "\n This is a very slow process")
        dic["FOLDER"] = folder
        self.configuration.write_variables("VERSION11", dic)

        ini_curdir = os.curdir
        os.chdir(os.path.join(Code.folder_OS, "Version11"))
        self.py27("ConversionDB.py", "folder", folder)
        os.chdir(ini_curdir)
        um.final()

        pb = QTUtil2.BarraProgreso1(self.wowner,
                                    _("Importing"),
                                    formato1="%p%")
        pb.mostrar()

        entry: os.DirEntry
        for entry in os.scandir(folder):
            if entry.name.endswith(".convert_end"):
                if not self.phase2(pb, entry):
                    break

        pb.cerrar()
Example #8
0
    def importarSummary(self, ventana, partidabase, ficheroSummary, depth, siWhite, onlyone, minMoves):
        titulo = _("Importing the summary of a database")
        bp = QTUtil2.BarraProgreso1(ventana, titulo)
        bp.ponTotal(0)
        bp.ponRotulo(_X(_("Reading %1"), os.path.basename(ficheroSummary)))
        bp.mostrar()

        dbSTAT = DBgames.TreeSTAT(ficheroSummary)

        if depth == 0:
            depth = 99999

        pvBase = partidabase.pv()
        len_partidabase = len(partidabase)

        liPartidas = []

        def hazPV(lipv_ant):
            if bp.siCancelado():
                return
            n_ant = len(lipv_ant)
            siWhite1 = n_ant % 2 == 0

            pv_ant = " ".join(lipv_ant) if n_ant else ""
            liChildren = dbSTAT.children(pv_ant, False)

            if len(liChildren) == 0 or len(lipv_ant) > depth:
                p = Partida.Partida()
                p.leerLIPV(lipv_ant)
                if len(p) > len_partidabase:
                    liPartidas.append(p)
                    bp.ponTotal(len(liPartidas))
                    bp.pon(len(liPartidas))
                return

            if siWhite1 == siWhite:
                tt_max = 0
                limax = []
                for alm in liChildren:
                    tt = alm.W + alm.B + alm.O + alm.D
                    if tt > tt_max:
                        tt_max = tt
                        limax = [alm]
                    elif tt == tt_max and not onlyone:
                        limax.append(alm)
                liChildren = limax

            for alm in liChildren:
                li = lipv_ant[:]
                li.append(alm.move)
                hazPV(li)

        hazPV(pvBase.split(" ") if pvBase else [])

        bp.ponRotulo(_("Writing..."))
        self.guardaPartidas("%s,%s" % (_("Database summary"), os.path.basename(ficheroSummary)), liPartidas)
        bp.cerrar()

        return True
Example #9
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()
Example #10
0
    def importarPolyglot(self, ventana, partida, bookW, bookB, titulo, depth, siWhite, onlyone, minMoves):
        bp = QTUtil2.BarraProgreso1(ventana, titulo, formato1="%m")
        bp.ponTotal(0)
        bp.ponRotulo(_X(_("Reading %1"), "..."))
        bp.mostrar()

        cp = partida.ultPosicion

        setFen = LCEngine.setFen
        makeMove = LCEngine.makeMove
        getFen = LCEngine.getFen

        def hazFEN(fen, lipv_ant, control):
            if bp.siCancelado():
                return
            siWhite1 = " w " in fen
            book = bookW if siWhite1 else bookB
            liPV = book.miraListaPV(fen, siWhite1 == siWhite, onlyone=onlyone)
            if liPV and len(lipv_ant) < depth:
                for pv in liPV:
                    setFen(fen)
                    makeMove(pv)
                    fenN = getFen()
                    lipv_nue = lipv_ant[:]
                    lipv_nue.append(pv)
                    hazFEN(fenN, lipv_nue, control)
            else:
                p = Partida.Partida()
                p.leerLIPV(lipv_ant)
                control.liPartidas.append(p)
                control.num_partidas += 1
                bp.ponTotal(control.num_partidas)
                bp.pon(control.num_partidas)
                if control.num_partidas and control.num_partidas % 1000 == 0:
                    self.guardaPartidas(control.rotulo, control.liPartidas, minMoves, with_history=control.with_history)
                    control.liPartidas = []
                    control.with_history = False

        control = Util.Almacen()
        control.liPartidas = []
        control.num_partidas = 0
        control.with_history = True
        control.rotulo = "%s,%s,%s" % (_("Polyglot book"), bookW.nombre, bookB.nombre)

        hazFEN(cp.fen(), partida.lipv(), control)

        bp.ponRotulo(_("Writing..."))

        if control.liPartidas:
            self.guardaPartidas(control.rotulo, control.liPartidas, minMoves, with_history=control.with_history)
        bp.cerrar()

        return True
Example #11
0
    def importarPolyglot(self, ventana, partida, bookW, bookB, titulo, depth,
                         siWhite, onlyone, minMoves):
        bp = QTUtil2.BarraProgreso1(ventana, titulo)
        bp.ponTotal(0)
        bp.ponRotulo(_X(_("Reading %1"), "..."))
        bp.mostrar()

        cp = partida.ultPosicion

        liPartidas = []

        setFen = LCEngine.setFen
        makeMove = LCEngine.makeMove
        getFen = LCEngine.getFen

        def hazFEN(fen, lipv_ant):
            if bp.siCancelado():
                return
            siWhite1 = " w " in fen
            book = bookW if siWhite1 else bookB
            liPV = book.miraListaPV(fen, siWhite1 == siWhite, onlyone=onlyone)
            if liPV and len(lipv_ant) < depth:
                for pv in liPV:
                    setFen(fen)
                    makeMove(pv)
                    fenN = getFen()
                    lipv_nue = lipv_ant[:]
                    lipv_nue.append(pv)
                    hazFEN(fenN, lipv_nue)
            else:
                p = Partida.Partida()
                p.leerLIPV(lipv_ant)
                liPartidas.append(p)
                bp.ponTotal(len(liPartidas))
                bp.pon(len(liPartidas))

        hazFEN(cp.fen(), partida.lipv())

        bp.ponRotulo(_("Writing..."))

        self.guardaPartidas(
            "%s,%s,%s" % (_("Polyglot book"), bookW.nombre, bookB.nombre),
            liPartidas, minMoves)
        bp.cerrar()

        return True
Example #12
0
    def tg_exportar_PGN(self):
        li = self.grid.recnosSeleccionados()
        if li:
            if len(li) > 1:
                menu = QTVarios.LCMenu(self)
                menu.opcion(True, _("All read"), Iconos.PuntoVerde())
                menu.separador()
                menu.opcion(False, _("Only selected"), Iconos.PuntoAzul())
                resp = menu.lanza()
                if resp is None:
                    return
                siTodos = resp
            else:
                siTodos = True

            if siTodos:
                li = range(self.dbGames.reccount())

            w = PantallaSavePGN.WSaveVarios(self, self.configuracion)
            if w.exec_():
                ws = PantallaSavePGN.FileSavePGN(self, w.dic_result)
                if ws.open():
                    pb = QTUtil2.BarraProgreso1(self,
                                                _("Saving..."),
                                                formato1="%p%")
                    pb.mostrar()
                    pb.ponTotal(len(li))
                    for n, recno in enumerate(li):
                        pb.pon(n)
                        pgn, result = self.dbGames.leePGNRecno(recno)
                        if pb.siCancelado():
                            break
                        if n > 0 or not ws.is_new:
                            ws.write("\n\n")
                        ws.write(pgn)

                    pb.close()
                    ws.close()
    def tw_rebuild(self):
        pb = QTUtil2.BarraProgreso1(self, _("Working..."), formato1="%p%")
        pb.mostrar()
        liFields = ["RESULT", "XPV", "WHITE", "BLACK"]
        dicOpenings = {"white": {}, "black": {}}
        dicMoves = {"white": {}, "black": {}}
        dic_hap = {}
        nombre = self.player
        alias1 = self.leeVariable("ALIAS1")
        alias2 = self.leeVariable("ALIAS2")
        alias3 = self.leeVariable("ALIAS3")

        liplayer = (nombre, alias1, alias2, alias3)

        filtro = "WHITE = '%s' or BLACK = '%s'" % (nombre, nombre)
        for alias in (alias1, alias2, alias3):
            if alias:
                filtro += "or WHITE = '%s' or BLACK = '%s'" % (alias, alias)
        pb.ponTotal(self.dbGames.countData(filtro))

        for n, alm in enumerate(self.dbGames.yieldData(liFields, filtro)):
            pb.pon(n)
            if pb.siCancelado():
                return
            result = alm.RESULT
            if result in ("1-0", "0-1", "1/2-1/2"):
                white = alm.WHITE
                black = alm.BLACK

                resultw = "win" if result == "1-0" else (
                    "lost" if result == "0-1" else "draw")
                resultb = "win" if result == "0-1" else (
                    "lost" if result == "1-0" else "draw")

                if white in liplayer:
                    side = "white"
                    result = resultw
                elif black in liplayer:
                    side = "black"
                    result = resultb
                else:
                    continue
                xpv = alm.XPV
                if not xpv:
                    continue

                # openings
                ap = self.ap.baseXPV(xpv)
                hap = hash(ap)
                dco = dicOpenings[side]
                if hap not in dic_hap:
                    dic_hap[hap] = ap
                if hap not in dco:
                    dco[hap] = {"win": 0, "draw": 0, "lost": 0}
                dco[hap][result] += 1

                # moves
                listapvs = LCEngine.xpv2pv(xpv).split(" ")
                dcm = dicMoves[side]
                pvt = ""
                for pv in listapvs:
                    if pvt:
                        pvt += " " + pv
                    else:
                        pvt = pv
                    if pvt not in dcm:
                        dcm[pvt] = {"win": 0, "draw": 0, "lost": 0, "games": 0}
                    dcm[pvt][result] += 1
                    dcm[pvt]["games"] += 1

        pb.close()

        um = QTUtil2.unMomento(self, _("Working..."))

        def color3(x, y, z):
            if x > y and x > z:
                return 0
            if x < y and x < z:
                return 2
            return 1

        def color2(x, y):
            if x > y:
                return 0
            if x < y:
                return 2
            return 1

        def z(x):
            return "%0.2f" % x

        color = None
        info = None
        indicadorInicial = None
        liNAGs = []
        siLine = False

        data = [[], [], [], []]
        for side in ("white", "black"):
            dtemp = []
            tt = 0
            for hap in dicOpenings[side]:
                dt = dicOpenings[side][hap]
                w, d, l = dt["win"], dt["draw"], dt["lost"]
                t = w + d + l
                tt += t
                ap = dic_hap[hap]
                dic = {
                    "opening": ap.trNombre,
                    "opening_obj": ap,
                    "games": t,
                    "win": w,
                    "draw": d,
                    "lost": l,
                    "pwin": z(w * 100.0 / t),
                    "pdraw": z(d * 100.0 / t),
                    "plost": z(l * 100.0 / t),
                    "pdrawlost": z((d + l) * 100.0 / t),
                    "pdrawwin": z((w + d) * 100.0 / t),
                }
                dic["winc"] = dic["pwinc"] = color3(w, d, l)
                dic["drawc"] = dic["pdrawc"] = color3(d, w, l)
                dic["lostc"] = dic["plostc"] = color3(l, w, d)
                dic["pdrawlostc"] = color2(d + l, d + w)
                dic["pdrawwinc"] = color2(d + w, d + l)
                p = Partida.Partida()
                p.leerPV(ap.a1h8)
                dic["partida"] = p
                dtemp.append(dic)

            for d in dtemp:
                d["pgames"] = z(d["games"] * 100.0 / tt)
            dtemp.sort(key=lambda x: "%5d%s" %
                       (99999 - x["games"], x["opening"]),
                       reverse=False)
            if side == "white":
                data[OPENINGS_WHITE] = dtemp
            else:
                data[OPENINGS_BLACK] = dtemp

            # moves
            dtemp = []
            dc = dicMoves[side]
            st_rem = set()

            listapvs = dicMoves[side].keys()
            listapvs.sort()

            sipar = 1 if side == "white" else 0

            for pv in listapvs:
                if dc[pv]["games"] == 1:
                    lipv = pv.split(" ")
                    nlipv = len(lipv)
                    if nlipv > 1:
                        pvant = " ".join(lipv[:-1])
                        if pvant in st_rem or dc[pvant]["games"] == 1 and (
                                nlipv) % 2 == sipar:
                            st_rem.add(pv)

            for pv in st_rem:
                del dc[pv]

            listapvs = dicMoves[side].keys()
            listapvs.sort()
            antlipv = []
            for npv, pv in enumerate(listapvs):
                dt = dicMoves[side][pv]
                w, d, l = dt["win"], dt["draw"], dt["lost"]
                t = w + d + l
                tt += t
                lipv = pv.split(" ")
                nli = len(lipv)
                dic = {
                    "pv": pv,
                    "games": t,
                    "win": w,
                    "draw": d,
                    "lost": l,
                    "pwin": z(w * 100.0 / t),
                    "pdraw": z(d * 100.0 / t),
                    "plost": z(l * 100.0 / t),
                    "pdrawlost": z((d + l) * 100.0 / t),
                    "pdrawwin": z((w + d) * 100.0 / t),
                    "nivel": nli,
                }
                # p = Partida.Partida()
                # p.leerPV(pv)
                dic["partida"] = None
                li_pgn = Partida.lipv_lipgn(lipv)
                nliant = len(antlipv)
                agrisar = True
                for x in range(100):
                    iswhite = (x % 2) == 0
                    pgn = li_pgn[x] if x < nli else ""
                    # pgn = p.jugada(x).pgnBaseSP() if x < nli else ""
                    if agrisar:
                        if x >= nliant:
                            agrisar = False
                        elif x < nli:
                            if lipv[x] != antlipv[x]:
                                agrisar = False
                    dic[str(
                        x
                    )] = pgn, iswhite, color, info, indicadorInicial, liNAGs, agrisar, siLine
                antlipv = lipv
                dic["winc"] = dic["pwinc"] = color3(w, d, l)
                dic["drawc"] = dic["pdrawc"] = color3(d, w, l)
                dic["lostc"] = dic["plostc"] = color3(l, w, d)
                dic["pdrawlostc"] = color2(d + l, d + w)
                dic["pdrawwinc"] = color2(d + w, d + l)
                dtemp.append(dic)

            liorder = []

            def ordena(empieza, nivel):
                li = []
                for n, uno in enumerate(dtemp):
                    if uno["nivel"] == nivel and uno["pv"].startswith(empieza):
                        li.append(uno)
                li.sort(key=lambda x: "%5d%5d" % (x["games"], x["win"]),
                        reverse=True)
                for uno in li:
                    liorder.append(uno)
                    ordena(uno["pv"], nivel + 1)

            ordena("", 1)
            if side == "white":
                data[MOVES_WHITE] = liorder
                self.movesWhite = range(len(liorder))
            else:
                data[MOVES_BLACK] = liorder
                self.movesBlack = range(len(liorder))

        um.final()

        self.data = data
        self.gridOpeningWhite.refresh()
        self.gridOpeningBlack.refresh()
        self.gridMovesWhite.refresh()
        self.gridMovesBlack.refresh()
Example #14
0
    def tg_exportar_PGN(self):
        li = self.grid.recnosSeleccionados()
        if li:
            if len(li) > 1:
                menu = QTVarios.LCMenu(self)
                menu.opcion(True, _("All read"), Iconos.PuntoVerde())
                menu.separador()
                menu.opcion(False, _("Only selected"), Iconos.PuntoAzul())
                resp = menu.lanza()
                if resp is None:
                    return
                siTodos = resp
            else:
                siTodos = True

            if siTodos:
                li = range(self.dbGamesFEN.reccount())

            # Fichero donde aadir
            pathPGN = QTUtil2.salvaFichero(self, _("Export"), self.configuracion.dirPGN,
                                           _("File") + " pgn (*.pgn)",
                                           False)
            if pathPGN:
                carpeta, nomf = os.path.split(pathPGN)
                if carpeta != self.configuracion.dirPGN:
                    self.configuracion.dirPGN = carpeta
                    self.configuracion.graba()

                # Grabamos
                modo = "w"
                if Util.existeFichero(pathPGN):
                    yn = QTUtil2.preguntaCancelar(self,
                                                  _X(_("The file %1 already exists, what do you want to do?"), pathPGN),
                                                  si=_("Append"), no=_("Overwrite"))
                    if yn is None:
                        return
                    if yn:
                        modo = "a"
                try:
                    fpgn = codecs.open(pathPGN, modo, 'utf-8', 'ignore')
                except:
                    QTUtil2.mensError(self, "%s : %s\n" % (_("Unable to save"), pathPGN.replace("/", "\\")))
                    return

                pb = QTUtil2.BarraProgreso1(self, _("Exporting..."))
                pb.mostrar()
                total = len(li)
                pb.ponTotal(total)

                if modo == "a":
                    fpgn.write("\n\n")
                for n, recno in enumerate(li):
                    pgn = self.dbGamesFEN.leePGNRecno(recno)
                    pb.pon(n + 1)
                    if pb.siCancelado():
                        break
                    fpgn.write(pgn)
                    fpgn.write("\n\n")

                fpgn.close()
                pb.cerrar()
                QTUtil2.mensaje(self, _X(_("Saved to %1"), pathPGN.replace("/", "\\")))
Example #15
0
    def import_polyglot(self, ventana, game, bookW, bookB, titulo, depth, siWhite, onlyone, minMoves, excl_transpositions):
        bp = QTUtil2.BarraProgreso1(ventana, titulo, formato1="%m")
        bp.ponTotal(0)
        bp.ponRotulo(_X(_("Reading %1"), "..."))
        bp.mostrar()

        st_fenm2 = set()
        set_fen = FasterCode.set_fen
        make_move = FasterCode.make_move
        get_fen = FasterCode.get_fen
        control = Util.Record()
        control.liPartidas = []
        control.num_games = 0
        control.with_history = True
        control.label = "%s,%s,%s" % (_("Polyglot book"), bookW.name, bookB.name)

        def hazFEN(fen, lipv_ant, control):
            if bp.is_canceled():
                return
            if len(lipv_ant) > depth:
                return
            if excl_transpositions:
                fen_m2 = FasterCode.fen_fenm2(fen)
                if fen_m2 in st_fenm2:
                    return
                st_fenm2.add(fen_m2)

            siWhite1 = " w " in fen
            book = bookW if siWhite1 else bookB
            li_posible_moves = book.miraListaPV(fen, siWhite1 == siWhite, onlyone=onlyone)
            if li_posible_moves and len(lipv_ant) < depth:
                for pv in li_posible_moves:
                    set_fen(fen)
                    make_move(pv)
                    fenN = get_fen()
                    lipv_nue = lipv_ant[:]
                    lipv_nue.append(pv)
                    hazFEN(fenN, lipv_nue, control)
            else:
                p = Game.Game()
                p.leerLIPV(lipv_ant)
                if p.si3repetidas():
                    return
                control.liPartidas.append(p)
                control.num_games += 1
                bp.ponTotal(control.num_games)
                bp.pon(control.num_games)
                if control.num_games and control.num_games % 3751 == 0:
                    self.guardaPartidas(control.label, control.liPartidas, minMoves, with_history=control.with_history)
                    control.liPartidas = []
                    control.with_history = False

        li_games = self.get_all_games() if game is None else [game]

        for game in li_games:
            cp = game.last_position
            hazFEN(cp.fen(), game.lipv(), control)

        bp.ponRotulo(_("Writing..."))

        if control.liPartidas:
            self.guardaPartidas(control.label, control.liPartidas, minMoves, with_history=control.with_history)
        bp.cerrar()

        return True
Example #16
0
    def tw_rebuild(self):
        if not self.test_players_in_db():
            return

        self.rebuilding = True
        pb = QTUtil2.BarraProgreso1(self, _("Working..."), formato1="%p%")
        pb.mostrar()
        liFields = ["RESULT", "XPV", "WHITE", "BLACK"]
        dicOpenings = {"white": {}, "black": {}}
        dicMoves = {"white": {}, "black": {}}
        dic_hap = {}
        name = self.player
        alias1 = self.leeVariable("ALIAS1")
        alias2 = self.leeVariable("ALIAS2")
        alias3 = self.leeVariable("ALIAS3")

        liplayer = (name, alias1, alias2, alias3)

        filtro = "WHITE = '%s' or BLACK = '%s'" % (name, name)
        for alias in (alias1, alias2, alias3):
            if alias:
                filtro += "or WHITE = '%s' or BLACK = '%s'" % (alias, alias)
        pb.ponTotal(self.dbGames.count_data(filtro))

        for n, alm in enumerate(self.dbGames.yield_data(liFields, filtro)):
            pb.pon(n)
            if pb.is_canceled():
                self.rebuilding = False
                return
            result = alm.RESULT
            if result in ("1-0", "0-1", "1/2-1/2"):
                white = alm.WHITE
                black = alm.BLACK

                resultw = "win" if result == "1-0" else (
                    "lost" if result == "0-1" else "draw")
                resultb = "win" if result == "0-1" else (
                    "lost" if result == "1-0" else "draw")

                if white in liplayer:
                    side = "white"
                    result = resultw
                elif black in liplayer:
                    side = "black"
                    result = resultb
                else:
                    continue
                xpv = alm.XPV
                if not xpv or "|" in xpv:
                    continue

                # openings
                ap = self.ap.base_xpv(xpv)
                hap = hash(ap)
                dco = dicOpenings[side]
                if not (hap in dic_hap):
                    dic_hap[hap] = ap
                if not (hap in dco):
                    dco[hap] = {"win": 0, "draw": 0, "lost": 0}
                dco[hap][result] += 1

                # moves
                listapvs = FasterCode.xpv_pv(xpv).split(" ")
                dcm = dicMoves[side]
                pvt = ""
                for pv in listapvs:
                    if pvt:
                        pvt += " " + pv
                    else:
                        pvt = pv
                    if not (pvt in dcm):
                        dcm[pvt] = {"win": 0, "draw": 0, "lost": 0, "games": 0}
                    dcm[pvt][result] += 1
                    dcm[pvt]["games"] += 1

        pb.close()

        um = QTUtil2.unMomento(self, _("Working..."), physical_pos="ad")

        def color3(x, y, z):
            if x > y and x > z:
                return 0
            if x < y and x < z:
                return 2
            return 1

        def color2(x, y):
            if x > y:
                return 0
            if x < y:
                return 2
            return 1

        def z(x):
            return "%0.2f" % x

        color = None
        info = None
        indicadorInicial = None
        li_nags = []
        siLine = False

        data = [[], [], [], []]
        for side in ("white", "black"):
            dtemp = []
            tt = 0
            for hap in dicOpenings[side]:
                dt = dicOpenings[side][hap]
                win, draw, lost = dt["win"], dt["draw"], dt["lost"]
                t = win + draw + lost
                tt += t
                ap = dic_hap[hap]
                dic = {
                    "opening": ap.trNombre,
                    "opening_obj": ap,
                    "games": t,
                    "win": win,
                    "draw": draw,
                    "lost": lost,
                    "pwin": z(win * 100.0 / t),
                    "pdraw": z(draw * 100.0 / t),
                    "plost": z(lost * 100.0 / t),
                    "pdrawlost": z((draw + lost) * 100.0 / t),
                    "pdrawwin": z((win + draw) * 100.0 / t),
                    "winc": color3(win, draw, lost),
                    "pwinc": color3(win, draw, lost),
                    "drawc": color3(draw, win, lost),
                    "pdrawc": color3(draw, win, lost),
                    "lostc": color3(lost, win, draw),
                    "plostc": color3(lost, win, draw),
                    "pdrawlostc": color2(draw + lost, draw + win),
                    "pdrawwinc": color2(draw + win, draw + lost),
                }
                p = Game.Game()
                p.read_pv(ap.a1h8)
                dic["game"] = p
                dtemp.append(dic)

            for draw in dtemp:
                draw["pgames"] = z(draw["games"] * 100.0 / tt)
            dtemp.sort(key=lambda x: "%5d%s" %
                       (99999 - x["games"], x["opening"]),
                       reverse=False)
            if side == "white":
                data[OPENINGS_WHITE] = dtemp
            else:
                data[OPENINGS_BLACK] = dtemp

            # moves
            dtemp = []
            dc = dicMoves[side]
            st_rem = set()

            listapvs = list(dicMoves[side].keys())
            listapvs.sort()

            sipar = 1 if side == "white" else 0

            for pv in listapvs:
                if dc[pv]["games"] == 1:
                    lipv = pv.split(" ")
                    nlipv = len(lipv)
                    if nlipv > 1:
                        pvant = " ".join(lipv[:-1])
                        if pvant in st_rem or dc[pvant]["games"] == 1 and (
                                nlipv) % 2 == sipar:
                            st_rem.add(pv)

            for pv in st_rem:
                del dc[pv]

            listapvs = list(dicMoves[side].keys())
            listapvs.sort()
            antlipv = []
            for npv, pv in enumerate(listapvs):
                dt = dicMoves[side][pv]
                win, draw, lost = dt["win"], dt["draw"], dt["lost"]
                t = win + draw + lost
                tt += t
                lipv = pv.split(" ")
                nli = len(lipv)
                dic = {
                    "pv": pv,
                    "games": t,
                    "win": win,
                    "draw": draw,
                    "lost": lost,
                    "pwin": z(win * 100.0 / t),
                    "pdraw": z(draw * 100.0 / t),
                    "plost": z(lost * 100.0 / t),
                    "pdrawlost": z((draw + lost) * 100.0 / t),
                    "pdrawwin": z((win + draw) * 100.0 / t),
                    "nivel": nli,
                    "game": None,
                }
                li_pgn = Game.lipv_lipgn(lipv)
                nliant = len(antlipv)
                agrisar = True
                for x in range(100):
                    iswhite = (x % 2) == 0
                    pgn = li_pgn[x] if x < nli else ""
                    if agrisar:
                        if x >= nliant:
                            agrisar = False
                        elif x < nli:
                            if lipv[x] != antlipv[x]:
                                agrisar = False
                    dic[str(
                        x
                    )] = pgn, iswhite, color, info, indicadorInicial, li_nags, agrisar, siLine
                antlipv = lipv
                dic["winc"] = dic["pwinc"] = color3(win, draw, lost)
                dic["drawc"] = dic["pdrawc"] = color3(draw, win, lost)
                dic["lostc"] = dic["plostc"] = color3(lost, win, draw)
                dic["pdrawlostc"] = color2(draw + lost, draw + win)
                dic["pdrawwinc"] = color2(draw + win, draw + lost)
                dtemp.append(dic)

            liorder = []

            def ordena(empieza, nivel):
                li = []
                for n, uno in enumerate(dtemp):
                    if uno["nivel"] == nivel and uno["pv"].startswith(empieza):
                        li.append(uno)
                li.sort(key=lambda x: "%5d%5d" % (x["games"], x["win"]),
                        reverse=True)
                for uno in li:
                    liorder.append(uno)
                    ordena(uno["pv"], nivel + 1)

            ordena("", 1)
            if side == "white":
                data[MOVES_WHITE] = liorder
                self.movesWhite = range(len(liorder))
            else:
                data[MOVES_BLACK] = liorder
                self.movesBlack = range(len(liorder))

        um.final()

        self.rebuilding = False
        self.data = data
        self.gridOpeningWhite.refresh()
        self.gridOpeningBlack.refresh()
        self.gridMovesWhite.refresh()
        self.gridMovesBlack.refresh()

        self.gridOpeningWhite.gotop()
        self.gridOpeningBlack.gotop()
        self.gridMovesWhite.gotop()
        self.gridMovesBlack.gotop()
        self.gridOpeningWhite.setFocus()