示例#1
0
文件: PGN.py 项目: JERUKA9/lucaschess
def rawPGN(pgn):
    g = PGNreader.read1Game(pgn)
    p = Partida.Partida(fen=g.fen)
    p.leerPV(g.pv())

    txt = ""
    for k,v in g.labels.iteritems():
        txt += "[%s \"%s\"]\n"%(k,v)
    txt += "\n\n"
    txt += p.pgnBase()

    return txt
示例#2
0
def rawPGN(pgn):
    g = PGNreader.read1Game(pgn)
    p = Partida.Partida(fen=g.fen)
    p.leerPV(g.pv())

    txt = ""
    for k, v in g.labels.iteritems():
        txt += "[%s \"%s\"]\n" % (k, v)
    txt += "\n\n"
    txt += p.pgnBase()

    return txt
示例#3
0
    def leerPGN(self, fichero, dlTmp):
        erroneos = duplicados = importados = 0

        # 1.File pgn -> temporal clean
        for n, g in enumerate(PGNreader.readGames(fichero), 1):
            if n % 100 == 0:
                if not dlTmp.actualiza(n, erroneos, duplicados, importados):
                    break
                if n % 10000 == 0:
                    self.dbf.commit()
            if g.erroneo:
                erroneos += 1
                continue
            pv = g.pv()
            if not pv:
                erroneos += 1
                continue
            pgn = g.pgn

            get = g.labels.get
            if get("FEN", None):
                erroneos += 1
                continue

            def get(label):
                if label in g.labels:
                    return g.labels[label]
                return ""

            event = get("EVENT")
            site = get("SITE")
            date = get("DATE")
            white = get("WHITE")
            black = get("BLACK")
            result = get("RESULT")
            eco = get("ECO")
            whiteelo = get("WHITEELO")
            blackelo = get("BLACKELO")

            if self.append(pv, event, site, date, white, black, result, eco,
                           whiteelo, blackelo, pgn, False):
                importados += 1
            else:
                duplicados += 1

        dlTmp.actualiza(n + 1, erroneos, duplicados, importados)

        dlTmp.ponSaving()
        self.dbf.commit()
        dlTmp.ponContinuar()

        return
示例#4
0
    def liVariantesPV(self, jg):
        liResp = []
        if jg.variantes:
            fen = jg.posicionBase.fen()
            for una in jg.variantes.split("\n"):

                g = PGNreader.Game()
                g.fen = fen
                g.readBody(una)
                if g.plies():
                    liResp.append((g.move(0).desde, g.move(0).hasta))

        return liResp
示例#5
0
    def leerPGN(self, fichero, dlTmp):
        erroneos = duplicados = importados = 0

        # 1.File pgn -> temporal clean
        for n, g in enumerate(PGNreader.readGames(fichero)):
            if n == 10000:
                break
            if n % 100 == 0:
                if not dlTmp.actualiza(n, erroneos, duplicados, importados):
                    break
            if g.erroneo:
                erroneos += 1
                continue
            pv = g.pv()
            if not pv:
                erroneos += 1
                continue
            pgn = g.pgn

            get = g.labels.get
            if get("FEN", None):
                erroneos += 1
                continue

            def get(label):
                if label in g.labels:
                    return g.labels[label]
                return ""

            event = get("EVENT")
            site = get("SITE")
            date = get("DATE")
            white = get("WHITE")
            black = get("BLACK")
            result = get("RESULT")
            eco = get("ECO")
            whiteelo = get("WHITEELO")
            blackelo = get("BLACKELO")

            if self.append(pv, event, site, date, white, black, result, eco, whiteelo, blackelo, pgn, False):
                importados += 1
            else:
                duplicados += 1

        dlTmp.actualiza(n + 1, erroneos, duplicados, importados)

        dlTmp.ponSaving()
        self.dbf.commit()
        dlTmp.ponContinuar()

        return
    def read_line(self, line):
        li = line.strip().split("|")
        self.fen, self.label, pgn_moves = li[0], li[1], li[2]

        self.pgn = '[FEN "%s"]\n\n%s' % (self.fen, pgn_moves)
        g = PGNreader.read1Game(self.pgn)
        self.pv = g.pv()
        self.limoves = self.pv.split(" ")

        nmoves = len(self.limoves)
        self.num_moves = int(len(self.limoves) / 2)
        if nmoves % 2 == 1:
            self.num_moves += 1
        return self
示例#7
0
    def leeTexto(self, texto):
        game = PGNreader.read1Game(texto)
        if game.erroneo:
            return False
        cp = ControlPosicion.ControlPosicion()
        cp.leeFen(game.fen)
        p = Partida.Partida(cp)
        p.firstComment = game.moves.firstComment

        for mv in game.moves.liMoves:
            cpBase = ControlPosicion.ControlPosicion()
            cpBase.leeFen(mv.fenPrev)
            cpActual = ControlPosicion.ControlPosicion()
            cpActual.leeFen(mv.fen)
            jg = Jugada.Jugada()
            jg.ponDatos(cpBase, cpActual, mv.desde, mv.hasta, mv.coronacion)

            if mv.criticas:
                li = []
                for una in mv.criticas:
                    if una:
                        if una.isdigit():
                            li.append(una)
                        elif una[0] == "$":
                            una = una[1:]
                            if una:
                                li.append(una)
                        elif una[0] in "?!":
                            jg.criticaDirecta = una
                jg.critica = " ".join(li)
            if mv.comentarios:
                jg.comentario = "\n".join(mv.comentarios)
            if mv.variantes:
                li = []
                for una in mv.variantes:
                    li.append(una.toPGN())
                jg.variantes = "\n\n".join(li)
            p.append_jg(jg)
        if game.moves:
            p.ultPosicion = cpActual if game.moves.liMoves else cp.copia()
        self.partida = p
        self.dic = game.labels
        self.siError = False
        self.texto = texto
        return True
示例#8
0
    def mueve(self, fila, siBlancas):
        siEmpiezaConNegras = self.gestor.partida.siEmpiezaConNegras

        if fila == 0 and siBlancas and siEmpiezaConNegras:
            return

        lj = self.gestor.partida.liJugadas
        pos = fila * 2
        if not siBlancas:
            pos += 1
        if siEmpiezaConNegras:
            pos -= 1

        tam_lj = len(lj)
        if tam_lj:

            siUltimo = (pos + 1) >= tam_lj
            if siUltimo:
                pos = tam_lj - 1

            jg = self.gestor.partida.jugada(pos)
            self.gestor.ponPosicion(jg.posicion)

            lipvvar = []
            if self.showVariantes:
                if jg.variantes:
                    fen = jg.posicionBase.fen()
                    for una in jg.variantes.split("\n"):

                        g = PGNreader.Game()
                        g.fen = fen
                        g.readBody(una)
                        if g.plies():
                            lipvvar.append((g.move(0).desde, g.move(0).hasta))
            self.gestor.ponFlechaSC(jg.desde, jg.hasta, lipvvar)

            if siUltimo:
                self.gestor.ponRevision(False)
                if self.gestor.siJuegaHumano and self.gestor.estado == kJugando:
                    self.gestor.activaColor(self.gestor.siJugamosConBlancas)
            else:
                self.gestor.ponRevision(self.gestor.estado == kJugando)
                self.gestor.desactivaTodas()
            self.gestor.refresh()
示例#9
0
    def leerPGN(self, fichero, dlTmp):

        erroneos = duplicados = importados = 0

        for n, g in enumerate(PGNreader.readGames(fichero)):

            if n % 100 == 0:
                if not dlTmp.actualiza(n + 1, erroneos, duplicados,
                                       importados):
                    break
            if g.erroneo:
                erroneos += 1
                continue
            pgn = g.pgn
            pv = g.pv()

            get = g.labels.get
            fen = get("FEN", None)
            if not fen:
                erroneos += 1
                continue
            event = get("EVENT", "")
            site = get("SITE", "")
            date = get("DATE", "")
            white = get("WHITE", "")
            black = get("BLACK", "")
            result = get("RESULT", "")

            if self.append(pv, event, site, date, white, black, result, fen,
                           pgn, False):
                importados += 1
            else:
                duplicados += 1

        dlTmp.actualiza(n + 1, erroneos, duplicados, importados)

        dlTmp.ponSaving()
        self.dbf.commit()
        dlTmp.ponContinuar()

        return
示例#10
0
文件: PGN.py 项目: JERUKA9/lucaschess
    def leeTexto(self, texto):
        game = PGNreader.read1Game(unicode(texto))
        cp = ControlPosicion.ControlPosicion()
        cp.leeFen(game.fen)
        p = Partida.Partida(cp)
        p.firstComment = game.moves.firstComment

        for mv in game.moves.liMoves:
            cpBase = ControlPosicion.ControlPosicion()
            cpBase.leeFen(mv.fenPrev)
            cpActual = ControlPosicion.ControlPosicion()
            cpActual.leeFen(mv.fen)
            jg = Jugada.Jugada()
            jg.ponDatos(cpBase, cpActual, mv.desde, mv.hasta, mv.coronacion)
            if mv.criticas:
                li = []
                for una in mv.criticas:
                    if una:
                        if una.isdigit():
                            li.append(una)
                        elif una[0] == "$":
                            una = una[1:]
                            if una:
                                li.append(una)
                        elif una[0] in "?!":
                            jg.criticaDirecta = una
                jg.critica = " ".join(li)
            if mv.comentarios:
                jg.comentario = "\n".join(mv.comentarios)
            if mv.variantes:
                li = []
                for una in mv.variantes:
                    li.append(una.toPGN())
                jg.variantes = "\n\n".join(li)
            p.liJugadas.append(jg)
        if game.moves:
            p.ultPosicion = cpActual if game.moves.liMoves else cp.copia()
        self.partida = p
        self.dic = game.labels
        self.siError = False
        self.texto = texto
示例#11
0
    def leerPGN(self, fichero, dlTmp):

        erroneos = duplicados = importados = 0

        for n, g in enumerate(PGNreader.readGames(fichero)):

            if n % 100 == 0:
                if not dlTmp.actualiza(n + 1, erroneos, duplicados, importados):
                    break
            if g.erroneo:
                erroneos += 1
                continue
            pgn = g.pgn
            pv = g.pv()

            get = g.labels.get
            fen = get("FEN", None)
            if not fen:
                erroneos += 1
                continue
            event = get("EVENT", "")
            site = get("SITE", "")
            date = get("DATE", "")
            white = get("WHITE", "")
            black = get("BLACK", "")
            result = get("RESULT", "")

            if self.append(pv, event, site, date, white, black, result, fen, pgn, False):
                importados += 1
            else:
                duplicados += 1

        dlTmp.actualiza(n + 1, erroneos, duplicados, importados)

        dlTmp.ponSaving()
        self.dbf.commit()
        dlTmp.ponContinuar()

        return
示例#12
0
    def importarPGN(self, owner, partidabase, ficheroPGN, maxDepth):
        erroneos = duplicados = importados = 0
        dlTmp = QTVarios.ImportarFicheroPGN(owner)
        dlTmp.hideDuplicados()
        dlTmp.show()

        cursor = self._conexion.cursor()

        base = self.getconfig("BASEPV")
        njugbase = partidabase.numJugadas()
        n = 0

        sql_insert = "INSERT INTO LINES( XPV, LINE ) VALUES( ?, ? )"
        sql_update = "UPDATE LINES SET XPV=?, LINE=? WHERE XPV=?"
        for n, g in enumerate(PGNreader.readGames(ficheroPGN), 1):
            if not dlTmp.actualiza(n, erroneos, duplicados, importados):
                break
            if g.erroneo:
                erroneos += 1
                continue
            if not g.moves:
                erroneos += 1
                continue

            def haz_partida(partida, liMoves):
                njg = len(partida)
                if len(liMoves) + njg > maxDepth:
                    liMoves = liMoves[:maxDepth - njg]
                pv = " ".join([move.pv for move in liMoves])
                partida.leerPV(pv)
                pv = partida.pv()
                if base and not pv.startswith(base) or partida.numJugadas(
                ) <= njugbase:
                    return
                xpv = LCEngine.pv2xpv(pv)
                if xpv in self.li_xpv:
                    return
                line_blob = partida.save2blob()
                updated = False
                for npos, xpv_ant in enumerate(self.li_xpv):
                    if xpv.startswith(xpv_ant):
                        cursor.execute(sql_update, (xpv, line_blob, xpv_ant))
                        self.li_xpv[npos] = xpv
                        updated = True
                        break
                if not updated:
                    cursor.execute(sql_insert, (xpv, line_blob))
                    self.li_xpv.append(xpv)

                for njug, move in enumerate(liMoves):
                    if move.variantes:
                        for lim in move.variantes:
                            p = partida.copia(
                                njug - 1) if njug > 0 else Partida.Partida()
                            haz_partida(p, lim.liMoves)

            partida = Partida.Partida()
            haz_partida(partida, g.moves.liMoves)
            if n % 50:
                self._conexion.commit()

        cursor.close()
        self.li_xpv.sort()
        self._conexion.commit()

        dlTmp.actualiza(n, erroneos, duplicados, importados)
        dlTmp.ponContinuar()
示例#13
0
    def importarPGN(self, owner, partidabase, ficheroPGN, maxDepth, variations):

        erroneos = duplicados = importados = 0
        dlTmp = QTVarios.ImportarFicheroPGN(owner)
        dlTmp.hideDuplicados()
        dlTmp.show()

        self.saveHistory(_("Import"), _("PGN with variants"), 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, g in enumerate(PGNreader.readGames(ficheroPGN), 1):
            if not dlTmp.actualiza(n, erroneos, duplicados, importados):
                break
            if g.erroneo:
                erroneos += 1
                continue
            if not g.moves:
                erroneos += 1
                continue

            def haz_partida(liMoves):
                njg = len(liMoves)
                if njg > maxDepth:
                    liMoves = liMoves[:maxDepth]
                pv = " ".join([move.pv for move in liMoves])
                partida = Partida.Partida()
                partida.leerPV(pv)
                pv = partida.pv()
                if base and not pv.startswith(base):
                    return
                xpv = LCEngine.pv2xpv(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(liMoves):
                        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 lim in move.variantes:
                                limovnv = [liMoves[j].clona() for j in range(njug)]
                                for move in limovnv:
                                    move.variantes = []
                                limovnv.extend(lim.liMoves)
                                haz_partida(limovnv)

            haz_partida(g.moves.liMoves)
            if n % 50:
                self._conexion.commit()

        cursor.close()
        self.li_xpv.sort()
        self._conexion.commit()

        dlTmp.actualiza(n, erroneos, duplicados, importados)
        dlTmp.ponContinuar()
示例#14
0
    def lanza(self, siFavoritos=True):

        self.comprueba()

        liFavoritos = None
        if siFavoritos:
            liFav = self.procesador.configuracion.liFavoritos
            if liFav:
                li = []
                for elem in liFav:
                    if elem in self.dicMenu:
                        li.append(self.dicMenu[elem])
                liFavoritos = li

        if liFavoritos:
            menu = self.menuFavoritos(liFavoritos)
        else:
            menu = self.menu

        resp = menu.lanza()

        if resp:
            siStr = type(resp) == type("")
            if siStr:
                if resp == "menu_global":
                    self.lanza(False)

                elif resp == "gm":
                    self.entrenaGM()

                elif resp.startswith("mate"):
                    self.jugarMate(int(resp[-1]))

                elif resp == "bmt":
                    self.bmt()

                elif resp == "polyglot":
                    self.entrenaBooks()

                elif resp.startswith("boxing"):
                    self.boxing(resp[6:])

                elif resp in ["j60_rival", "j60_jugador"]:
                    self.jugar60(resp == "j60_jugador")

                elif resp == "aperturas":
                    self.aperturas()

                elif resp == "dailytest":
                    self.dailyTest()

                elif resp == "potencia":
                    self.potencia()

                elif resp == "visualiza":
                    self.visualiza()

                elif resp.startswith("tactica|"):
                    nada, tipo, nombre, carpeta, ini = resp.split("|")
                    self.tacticas(tipo, nombre, carpeta, ini)

                elif resp.startswith("remtactica|"):
                    nada, carpeta, nombre = resp.split("|")
                    self.tacticaRemove(carpeta, nombre)

                elif resp.startswith("puente_"):
                    self.puente(int(resp[7:]))

                elif resp.startswith("horses_"):
                    test = int(resp[7])
                    icl, icn, tit = self.horsesDef[test]
                    icon = VarGen.todasPiezas.icono(icl, icn)
                    self.horses(test, tit, icon)

                elif resp.startswith("ep_"):
                    um = self.procesador.unMomento()
                    entreno = resp[3:].replace("\\", "/")
                    if "/" in entreno:
                        dicTraining = TrListas.dicTraining()
                        titentreno = ""
                        for x in entreno[:-4].split("/")[1:]:
                            titentreno += dicTraining.get(x, x) + "/"
                        titentreno = titentreno[:-1]
                    f = PGNreader.openCodec(entreno)
                    todo = f.read().strip()
                    f.close()
                    liEntrenamientos = todo.split("\n")
                    nPosiciones = len(liEntrenamientos)
                    um.final()
                    if nPosiciones == 0:
                        return
                    elif nPosiciones == 1:
                        pos = 1
                        jump = False
                    else:
                        db = Util.DicSQL(self.configuracion.ficheroTrainings)
                        posUltimo = db[entreno]
                        if posUltimo is None:
                            posUltimo = 1
                        resp = DatosNueva.numPosicion(self.procesador.pantalla,
                                                     titentreno, nPosiciones, posUltimo)
                        if resp is None:
                            return
                        pos, tipo, jump = resp
                        db.close()
                        if tipo.startswith( "r" ):
                            if tipo == "rk":
                                random.seed(pos)
                            random.shuffle(liEntrenamientos)
                    self.procesador.entrenaPos(pos, nPosiciones, titentreno, liEntrenamientos, entreno, jump)

                elif resp == "learnPGN":
                    self.learnPGN()

                elif resp == "lucaselo":
                    self.procesador.lucaselo(False)

                elif resp == "micelo":
                    self.procesador.micelo(False)

                elif resp.startswith("fics"):
                    self.procesador.ficselo(False, int(resp[4:]))

                elif resp.startswith("fide"):
                    self.procesador.fideelo(False, int(resp[4:]))

                elif resp.startswith("map_"):
                    nada, mapa = resp.split("_")
                    self.procesador.trainingMap(mapa)

            else:
                if resp <= -100:
                    self.menu = None  # ya que puede cambiar y la etiqueta es diferente
                    mem = Memoria.Memoria(self.procesador)
                    mem.lanza(abs(resp) - 100)
示例#15
0
    def grabarPGN(self, ventana, ficheroPGN, maxDepth):

        select = "XPV,PV,COMMENT,NAG,ADV,FEN,POS"
        SQLDBF.DBF(self.conexion, self.tablaDatos, select)

        erroneos = duplicados = importados = 0
        dlTmp = QTVarios.ImportarFicheroPGN(ventana)
        dlTmp.hideDuplicados()
        dlTmp.show()

        select = "XPV,PV,COMMENT,NAG,ADV,FEN,POS"
        dbf = SQLDBF.DBF(self.conexion, self.tablaDatos, select)
        dnag = {"!!": 3, "!": 1, "?": 2, "??": 4, "!?": 5, "?!": 6}

        for n, g in enumerate(PGNreader.readGames(ficheroPGN)):

            if not dlTmp.actualiza(n + 1, erroneos, duplicados, importados):
                break
            if g.erroneo:
                erroneos += 1
                continue
            if not g.moves:
                erroneos += 1
                continue

            liReg = []

            def addMoves(moves, depth, seq):
                for mv in moves.liMoves:
                    if depth > maxDepth:
                        break
                    seqM1 = seq
                    pv = mv.pv
                    seq += LCEngine.pv2xpv(pv)
                    reg = SQLDBF.Almacen()
                    reg.PV = pv
                    reg.XPV = seq
                    reg.COMMENT = "\n".join(mv.comentarios)
                    reg.FEN = mv.fen
                    reg.NAG = 0
                    reg.ADV = 0
                    self.ultPos += 1
                    reg.POS = self.ultPos
                    for critica in mv.criticas:
                        if critica.isdigit():
                            t = int(critica)
                            if t in (4, 2, 1, 3, 5, 6):
                                reg.NAG = t
                            elif t in (11, 14, 15, 16, 17, 18, 19):
                                reg.ADV = t
                        else:
                            if critica in dnag:
                                reg.NAG = dnag[critica]
                    liReg.append(reg)
                    if mv.variantes:
                        for variante in mv.variantes:
                            addMoves(variante, depth, seqM1)
                    depth += 1

            addMoves(g.moves, 1, "")
            if liReg:
                dbf.insertarLista(liReg, None)

        dbf.cerrar()
        dlTmp.actualiza(n, erroneos, duplicados, importados)
        dlTmp.ponContinuar()

        return len(liReg) > 0
示例#16
0
    def grabarPGN(self, ventana, ficheroPGN, maxDepth):

        select = "XPV,PV,COMMENT,NAG,ADV,FEN,POS"
        SQLDBF.DBF(self.conexion, self.tablaDatos, select)

        erroneos = duplicados = importados = 0
        dlTmp = QTVarios.ImportarFicheroPGN(ventana)
        dlTmp.hideDuplicados()
        dlTmp.show()

        select = "XPV,PV,COMMENT,NAG,ADV,FEN,POS"
        dbf = SQLDBF.DBF(self.conexion, self.tablaDatos, select)
        dnag = {"!!": 3, "!": 1, "?": 2, "??": 4, "!?": 5, "?!": 6}

        for n, g in enumerate(PGNreader.readGames(ficheroPGN, siFast=False)):

            if not dlTmp.actualiza(n + 1, erroneos, duplicados, importados):
                break
            if g.erroneo:
                erroneos += 1
                continue
            if not g.moves:
                erroneos += 1
                continue

            liReg = []

            def addMoves(moves, depth, seq):
                for mv in moves.liMoves:
                    if depth > maxDepth:
                        break
                    seqM1 = seq
                    pv = mv.pv
                    seq += Movimientos.pv2xpv(pv)
                    reg = SQLDBF.Almacen()
                    reg.PV = pv
                    reg.XPV = seq
                    reg.COMMENT = "\n".join(mv.comentarios)
                    reg.FEN = mv.fen
                    reg.NAG = 0
                    reg.ADV = 0
                    self.ultPos += 1
                    reg.POS = self.ultPos
                    for critica in mv.criticas:
                        if critica.isdigit():
                            t = int(critica)
                            if t in (4, 2, 1, 3, 5, 6):
                                reg.NAG = t
                            elif t in (11, 14, 15, 16, 17, 18, 19):
                                reg.ADV = t
                        else:
                            if critica in dnag:
                                reg.NAG = dnag[critica]
                    liReg.append(reg)
                    if mv.variantes:
                        for variante in mv.variantes:
                            addMoves(variante, depth, seqM1)
                    depth += 1

            addMoves(g.moves, 1, "")
            if liReg:
                dbf.insertarLista(liReg, None)

        dbf.cerrar()
        dlTmp.actualiza(n, erroneos, duplicados, importados)
        dlTmp.ponContinuar()

        return len(liReg) > 0
示例#17
0
 def numPlies(self, jugadas):
     game = PGNreader.read1Game(jugadas)
     return game.plies()
示例#18
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
示例#19
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.items()],
                    "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()
示例#20
0
文件: PGN.py 项目: JERUKA9/lucaschess
 def numPlies(self, jugadas):
     game = PGNreader.read1Game(jugadas)
     return game.plies()
示例#21
0
文件: PGN.py 项目: JERUKA9/lucaschess
    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 tama_o 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
示例#22
0
    def lanza(self, siFavoritos=True):

        self.comprueba()

        liFavoritos = None
        if siFavoritos:
            liFav = self.procesador.configuracion.liFavoritos
            if liFav:
                li = []
                for elem in liFav:
                    if elem in self.dicMenu:
                        li.append(self.dicMenu[elem])
                liFavoritos = li

        if liFavoritos:
            menu = self.menuFavoritos(liFavoritos)
        else:
            menu = self.menu

        resp = menu.lanza()

        if resp:
            siStr = type(resp) == type("")
            if siStr:
                if resp == "menu_global":
                    self.lanza(False)

                elif resp == "gm":
                    self.entrenaGM()

                elif resp.startswith("mate"):
                    self.jugarMate(int(resp[-1]))

                elif resp == "bmt":
                    self.bmt()

                elif resp == "polyglot":
                    self.entrenaBooks()

                elif resp.startswith("boxing"):
                    self.boxing(resp[6:])

                elif resp in ["j60_rival", "j60_jugador"]:
                    self.jugar60(resp == "j60_jugador")

                elif resp == "aperturas":
                    self.aperturas()

                elif resp == "dailytest":
                    self.dailyTest()

                elif resp == "potencia":
                    self.potencia()

                elif resp == "visualiza":
                    self.visualiza()

                elif resp.startswith("tactica|"):
                    nada, tipo, nombre, carpeta, ini = resp.split("|")
                    self.tacticas(tipo, nombre, carpeta, ini)

                elif resp.startswith("remtactica|"):
                    nada, carpeta, nombre = resp.split("|")
                    self.tacticaRemove(carpeta, nombre)

                elif resp.startswith("puente_"):
                    self.puente(int(resp[7:]))

                elif resp.startswith("horses_"):
                    test = int(resp[7])
                    icl, icn, tit = self.horsesDef[test]
                    icon = VarGen.todasPiezas.icono(icl, icn)
                    self.horses(test, tit, icon)

                elif resp.startswith("ep_"):
                    um = self.procesador.unMomento()
                    entreno = resp[3:].replace("\\", "/")
                    if "/" in entreno:
                        dicTraining = TrListas.dicTraining()
                        titentreno = ""
                        for x in entreno[:-4].split("/")[1:]:
                            titentreno += dicTraining.get(x, x) + "/"
                        titentreno = titentreno[:-1]
                    f = PGNreader.openCodec(entreno)
                    todo = f.read().strip()
                    f.close()
                    liEntrenamientos = todo.split("\n")
                    nPosiciones = len(liEntrenamientos)
                    um.final()
                    if nPosiciones == 0:
                        return
                    elif nPosiciones == 1:
                        pos = 1
                        jump = False
                    else:
                        db = Util.DicSQL(self.configuracion.ficheroTrainings)
                        posUltimo = db[entreno]
                        if posUltimo is None:
                            posUltimo = 1
                        resp = DatosNueva.numPosicion(self.procesador.pantalla,
                                                      titentreno, nPosiciones,
                                                      posUltimo)
                        if resp is None:
                            return
                        pos, tipo, jump = resp
                        db.close()
                        if tipo.startswith("r"):
                            if tipo == "rk":
                                random.seed(pos)
                            random.shuffle(liEntrenamientos)
                    self.procesador.entrenaPos(pos, nPosiciones, titentreno,
                                               liEntrenamientos, entreno, jump)

                elif resp == "learnPGN":
                    self.learnPGN()

                elif resp == "lucaselo":
                    self.procesador.lucaselo(False)

                elif resp == "micelo":
                    self.procesador.micelo(False)

                elif resp.startswith("fics"):
                    self.procesador.ficselo(False, int(resp[4:]))

                elif resp.startswith("fide"):
                    self.procesador.fideelo(False, int(resp[4:]))

                elif resp.startswith("map_"):
                    nada, mapa = resp.split("_")
                    self.procesador.trainingMap(mapa)

            else:
                if resp <= -100:
                    self.menu = None  # ya que puede cambiar y la etiqueta es diferente
                    mem = Memoria.Memoria(self.procesador)
                    mem.lanza(abs(resp) - 100)