コード例 #1
0
    def miniatura(self):
        self.pensando(True)

        fichero = "./IntFiles/miniaturas.gm"
        tam = Util.tamFichero(fichero)
        pos = random.randint(0, tam - 600)
        with open(fichero) as fm:
            fm.seek(pos)
            fm.readline()
            linea = fm.readline()
            lig = linea.split("|")
            liTags = []
            pv = lig[-1]
            for n in range(len(lig) - 1):
                if "·" in lig[n]:
                    k, v = lig[n].split("·")
                    liTags.append((k, v))
            p = Partida.PartidaCompleta(liTags=liTags)
            p.leerPV(pv)
            txt = p.pgn()
            pgn = PGN.UnPGN()
            pgn.leeTexto(txt)
        self.pensando(False)
        if pgn.siError:
            return
        self.pgnPaste = txt
        self.mostrar(pgn, False)
コード例 #2
0
ファイル: GestorPGN.py プロジェクト: wassekaran/lucaschess_11
    def fichero(self, siNuestro=False, siBuscar=False, path=""):
        if path:
            if not os.path.isfile(path):
                return
        self.siFicheroNuestro = siNuestro
        if siNuestro:
            path = self.nuestroFichero
        elif siBuscar:
            # Elegimos el fichero
            files = QTVarios.select_pgns(self.pantalla)
            if not files:
                if self.muestraInicial:
                    self.finPartida()
                return
            if len(files) == 1:
                path = files[0]
            else:
                path = self.configuracion.ficheroTemporal("pgn")
                with open(path, "wb") as q:
                    for fich in files:
                        with open(fich, "rb") as f:
                            q.write(f.read())

        # ~ else ya esta el nombre

        fpgn = PGN.PGN()

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

        self.ficheroMostrar(dicDB, False)
コード例 #3
0
ファイル: GestorPartida.py プロジェクト: MarCialR/lucaschess
 def paste(self, texto):
     cp = ControlPosicion.ControlPosicion()
     try:
         if "." in texto or '"' in texto:
             unpgn = PGN.UnPGN()
             unpgn.leeTexto(texto)
             if unpgn.siError:
                 return
             self.bloqueApertura = None
             self.posicApertura = None
             self.fen = unpgn.dic.get("FEN", None)
             dic = self.creaDic()
             dic["PARTIDA"] = unpgn.partida.guardaEnTexto()
             dic["liPGN"] = unpgn.listaCabeceras()
             dic["FEN"] = self.fen
             dic["SIBLANCASABAJO"] = unpgn.partida.ultPosicion.siBlancas
             self.reiniciar(dic)
         else:
             cp.leeFen(str(texto))
             self.fen = cp.fen()
             self.bloqueApertura = None
             self.posicApertura = None
             self.reiniciar()
     except:
         pass
コード例 #4
0
def texto2partida(owner, texto):
    pgn = PGN.UnPGN()
    pgn.leeTexto(texto)
    if pgn.siError:
        QTUtil2.mensError(owner, _("This is not a valid PGN file"))
        return None
    return pgn.partida
コード例 #5
0
    def fichero(self, siNuestro=False, siBuscar=False, path=""):
        if path:
            if not os.path.isfile(path):
                return
        self.siFicheroNuestro = siNuestro
        if siNuestro:
            path = self.nuestroFichero
        elif siBuscar:
            # Elegimos el fichero
            path = QTUtil2.leeFichero(self.pantalla, self.configuracion.dirPGN,
                                      "pgn")
            if not path:
                if self.muestraInicial:
                    self.finPartida()
                return
            carpeta, fichero = os.path.split(path)
            if self.configuracion.dirPGN != carpeta:
                self.configuracion.dirPGN = carpeta
                self.configuracion.graba()
        # ~ else ya esta el nombre

        fpgn = PGN.PGN()

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

        self.ficheroMostrar(dicDB, False)
コード例 #6
0
    def editar(self, numero, siEngineActivo=False):
        import Code.Variantes as Variantes

        gestor = self.owner.wParent.gestor

        siCompetitivo = False
        if hasattr(gestor, "siCompetitivo"):
            if gestor.siCompetitivo:
                siCompetitivo = gestor.estado != kFinJuego

        if siCompetitivo:
            siEngineActivo = False

        fen = self.jg.posicionBase.fen()
        if numero == -1:
            pgn = ""
        else:
            pgn = self.liVariantes[numero].pgnBaseRAW()

        resp = Variantes.editaVariante(gestor.procesador, gestor, fen, pgn, siEngineActivo=siEngineActivo, siCompetitivo=siCompetitivo)
        if resp:
            lineaPGN, pv = resp
            fen = self.jg.posicionBase.fen()

            uno = PGN.UnPGN()
            uno.leeTexto('[FEN "%s"]\n%s' % (fen, lineaPGN))
            if numero == -1:
                self.liVariantes.append(uno.partida)
            else:
                self.liVariantes[numero] = uno.partida
            self.guardar()
            self.mostrar()
コード例 #7
0
def eligePartida(ventana, path=None):
    configuracion = VarGen.configuracion
    # Elegimos el fichero PGN
    if path is None:
        path = QTUtil2.leeFichero(ventana, configuracion.dirPGN, "pgn")
        if not path:
            return None
    carpeta, fichero = os.path.split(path)
    if configuracion.dirPGN != carpeta:
        configuracion.dirPGN = carpeta
        configuracion.graba()

    # Lo importamos
    fpgn = PGN.PGN(configuracion)

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

    # Los datos los tenemos en una BD.sql
    dClaves = dicDB["DCLAVES"]

    bd = SQL.Base.DBBase(dicDB["PATHDB"])

    dbf = bd.dbf("GAMES", ",".join(dClaves.keys()) + ",PGN")

    siSeguir, estadoWpgn, siSeHaBorradoAlgo = elegirPGN(ventana,
                                                        dbf,
                                                        dClaves,
                                                        None,
                                                        None,
                                                        siElegir=True)
    if siSeguir:
        reg = dbf.dicValores()

    dbf.cerrar()

    bd.cerrar()

    if not siSeguir:
        return None

    unpgn = PGN.UnPGN()
    unpgn.leeTexto(reg["PGN"])

    return unpgn
コード例 #8
0
    def readPGN(self, configuracion, pgn):
        from Code import PGN # evita el circulo vicioso
        unpgn = PGN.UnPGN()
        unpgn.leeTexto(pgn)
        self.recuperaDeTexto(unpgn.partida.guardaEnTexto())
        self.asignaApertura(configuracion)

        self.liTags = unpgn.listaCabeceras()
        return self
コード例 #9
0
    def readPGN(self, pgn):
        from Code import PGN  # evita el circulo vicioso

        unpgn = PGN.UnPGN()
        if not unpgn.leeTexto(pgn):
            return None
        self.recuperaDeTexto(unpgn.partida.guardaEnTexto())

        self.liTags = unpgn.listaCabeceras()
        return self
コード例 #10
0
def pgn_pks(estado, pgn, jugada_inicial=None):
    unpgn = PGN.UnPGN()
    unpgn.leeTexto(pgn)
    if jugada_inicial:
        jg = unpgn.partida.jugada(jugada_inicial)
        si_blancas_abajo = jg.posicionBase.siBlancas
    else:
        si_blancas_abajo = True

    return dict(VOLTEO=False, liPGN=unpgn.listaCabeceras(), FEN=unpgn.dic.get("FEN", None), ESTADO=estado,
                BLOQUEAPERTURA=None, POSICAPERTURA=None, SIJUEGAMOTOR=False, PARTIDA=unpgn.partida.guardaEnTexto(),
                SIBLANCASABAJO=si_blancas_abajo)
コード例 #11
0
ファイル: GestorPGN.py プロジェクト: wassekaran/lucaschess_11
 def jugadaDia(self):
     self.pensando(True)
     dia = Util.hoy().day
     lid = Util.LIdisk("./IntFiles/31.pkl")
     dic = lid[dia - 1]
     lid.close()
     txt = dic["PGN"]
     pgn = PGN.UnPGN()
     pgn.leeTexto(txt)
     self.pensando(False)
     if pgn.siError:
         return
     self.pgnPaste = txt
     self.mostrar(pgn, False)
コード例 #12
0
    def ponJugada(self, jg):
        self.jg = jg

        variantes = jg.variantes
        self.liVariantes = []
        if variantes:
            lista = variantes.split("\n\n")

            fen = self.jg.posicionBase.fen()

            for lineaPGN in lista:
                uno = PGN.UnPGN()
                uno.leeTexto('[FEN "%s"]\n%s' % (fen, lineaPGN))
                self.liVariantes.append(uno.partida)
        self.mostrar()
コード例 #13
0
    def current_pgn(self):
        pgn = ""
        for key, value in self.li_labels:
            key = key.strip()
            value = value.strip()
            if key and value:
                pgn += "[%s \"%s\"]\n" % (key, value)
        pgn += "\n%s\n" % self.em_body.texto().strip()
        if "\r\n" in pgn:
            pgn = pgn.replace("\r\n", "\n")
        pgn = pgn.replace("\n", "\r\n")

        if self.chb_remove_c_v.isChecked():
            pgn = PGN.rawPGN(pgn)

        return pgn
コード例 #14
0
    def inicio(self, route):
        GestorRoutes.inicio(self, route)

        tactica = self.route.get_tactic()
        self.dicFen, self.nDicMoves = PGN.leeEntDirigidoBaseM2(
            tactica.fen, tactica.pgn)

        self.rivalPensando = False

        cp = ControlPosicion.ControlPosicion()
        cp.leeFen(tactica.fen)

        self.fen = tactica.fen

        siBlancas = cp.siBlancas

        self.partida.reset(cp)
        self.partida.pendienteApertura = False

        self.siJuegaHumano = False
        self.estado = kJugando

        self.siJugamosConBlancas = siBlancas
        self.siRivalConBlancas = not siBlancas

        self.pantalla.ponActivarTutor(False)

        self.ayudasPGN = 0

        liOpciones = [k_mainmenu, k_ayuda]
        self.pantalla.ponToolBar(liOpciones)

        self.pantalla.activaJuego(True, False, siAyudas=False)
        self.pantalla.quitaAyudas(True)
        self.ponMensajero(self.mueveHumano)
        self.ponPosicion(self.partida.ultPosicion)
        self.mostrarIndicador(True)
        self.ponPiezasAbajo(siBlancas)
        self.ponRotulo1("<b>%s</b>" % tactica.label)
        self.ponRotulo2(route.mens_tactic(False))
        self.pgnRefresh(True)
        QTUtil.xrefreshGUI()

        self.ponPosicionDGT()

        self.siguienteJugada()
コード例 #15
0
 def paste(self):
     texto = QTUtil.traePortapapeles()
     if texto:
         pgn = PGN.UnPGN()
         try:
             pgn.leeTexto(str(texto))
         except:
             pgn.siError = True
         if pgn.siError:
             QTUtil2.mensError(
                 self.pantalla,
                 _("The text from the clipboard does not contain a chess game in PGN format"
                   ))
             self.finPartida()
             return
         self.pgnPaste = texto
         self.mostrar(pgn, False)
コード例 #16
0
ファイル: GestorPGN.py プロジェクト: MarCialR/lucaschess
    def fichero(self, siNuestro=False, siBuscar=False, path=""):
        if path:
            if not os.path.isfile(path):
                return
        self.siFicheroNuestro = siNuestro
        if siNuestro:
            path = self.nuestroFichero
        elif siBuscar:
            # Elegimos el fichero
            path = QTVarios.select_pgn(self.pantalla)
            if not path:
                if self.muestraInicial:
                    self.finPartida()
                return
        # ~ else ya esta el nombre

        fpgn = PGN.PGN()

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

        self.ficheroMostrar(dicDB, False)
コード例 #17
0
ファイル: GestorPartida.py プロジェクト: MarCialR/lucaschess
    def configurarGS(self):
        sep = (None, None, None)

        liMasOpciones = [
            ("rotacion", _("Auto-rotate board"), Iconos.JS_Rotacion()), sep,
            ("apertura", _("Opening"), Iconos.Apertura()), sep,
            ("posicion", _("Start position"), Iconos.Datos()), sep,
            ("pasteposicion", _("Paste FEN position"), Iconos.Pegar16()), sep,
            ("leerpgn", _("Read PGN"), Iconos.PGN_Importar()), sep,
            ("pastepgn", _("Paste PGN"), Iconos.Pegar16()), sep,
            ("voyager", _("Voyager 2"), Iconos.Voyager1()),
        ]
        resp = self.configurar(liMasOpciones, siCambioTutor=True, siSonidos=True)

        if resp == "rotacion":
            self.siVolteoAutomatico = not self.siVolteoAutomatico
            siBlancas = self.partida.ultPosicion.siBlancas
            if self.siVolteoAutomatico:
                if siBlancas != self.tablero.siBlancasAbajo:
                    self.tablero.rotaTablero()
        elif resp == "apertura":
            bl, ps = PantallaAperturas.dameApertura(self.pantalla, self.configuracion, self.bloqueApertura,
                                                    self.posicApertura)
            if bl:
                self.bloqueApertura = bl
                self.posicApertura = ps
                self.fen = None
                self.reiniciar()

        elif resp == "posicion":
            resp = XVoyager.xVoyagerFEN(self.pantalla, self.configuracion, self.fen)
            if resp is not None:
                self.fen = resp
                self.bloqueApertura = None
                self.posicApertura = None

                if self.xpgn:
                    siInicio = self.fen == ControlPosicion.FEN_INICIAL
                    li = self.xpgn.split("\n")
                    lin = []
                    siFen = False
                    for linea in li:
                        if linea.startswith("["):
                            if "FEN " in linea:
                                siFen = True
                                if siInicio:
                                    continue
                                linea = '[FEN "%s"]' % self.fen
                            lin.append(linea)
                        else:
                            break
                    if not siFen:
                        linea = '[FEN "%s"]' % self.fen
                        lin.append(linea)
                    self.liPGN = lin
                    self.xpgn = "\n".join(lin) + "\n\n*"

                self.reiniciar()

        elif resp == "pasteposicion":
            texto = QTUtil.traePortapapeles()
            if texto:
                cp = ControlPosicion.ControlPosicion()
                try:
                    cp.leeFen(str(texto))
                    self.fen = cp.fen()
                    self.bloqueApertura = None
                    self.posicApertura = None
                    self.reiniciar()
                except:
                    pass

        elif resp == "leerpgn":
            unpgn = PantallaPGN.eligePartida(self.pantalla)
            if unpgn:
                self.bloqueApertura = None
                self.posicApertura = None
                self.fen = unpgn.dic.get("FEN", None)
                dic = self.creaDic()
                dic["PARTIDA"] = unpgn.partida.guardaEnTexto()
                dic["liPGN"] = unpgn.listaCabeceras()
                dic["FEN"] = self.fen
                dic["SIBLANCASABAJO"] = unpgn.partida.ultPosicion.siBlancas
                self.reiniciar(dic)

        elif resp == "pastepgn":
            texto = QTUtil.traePortapapeles()
            if texto:
                unpgn = PGN.UnPGN()
                unpgn.leeTexto(texto)
                if unpgn.siError:
                    QTUtil2.mensError(self.pantalla, _("The text from the clipboard does not contain a chess game in PGN format"))
                    return
                self.bloqueApertura = None
                self.posicApertura = None
                self.fen = unpgn.dic.get("FEN", None)
                dic = self.creaDic()
                dic["PARTIDA"] = unpgn.partida.guardaEnTexto()
                dic["liPGN"] = unpgn.listaCabeceras()
                dic["FEN"] = self.fen
                dic["SIBLANCASABAJO"] = unpgn.partida.ultPosicion.siBlancas
                self.reiniciar(dic)

        elif resp == "voyager":
            ptxt = XVoyager.xVoyager(self.pantalla, self.configuracion, partida=self.partida)
            if ptxt:
                dic = self.creaDic()
                dic["PARTIDA"] = ptxt
                p = self.partida.copia()
                p.recuperaDeTexto(ptxt)
                dic["FEN"] = None if p.siFenInicial() else p.iniPosicion.fen()
                dic["SIBLANCASABAJO"] = self.tablero.siBlancasAbajo
                self.reiniciar(dic)
コード例 #18
0
    def configurarGS(self):
        mt = _("Engine").lower()
        mt = _X(_("Disable %1"), mt) if self.siJuegaMotor else _X(_("Enable %1"), mt)

        sep = (None, None, None)

        liMasOpciones = [
            ("rotacion", _("Auto-rotate board"), Iconos.JS_Rotacion()), sep,
            ("apertura", _("Opening"), Iconos.Apertura()), sep,
            ("posicion", _("Start position"), Iconos.Datos()), sep,
            ("pasteposicion", _("Paste FEN position"), Iconos.Pegar16()), sep,
            ("leerpgn", _("Read PGN"), Iconos.PGN_Importar()), sep,
            ("pastepgn", _("Paste PGN"), Iconos.Pegar16()), sep,
            ("motor", mt, Iconos.Motores()), sep,
            ("voyager", _("Voyager 2"), Iconos.Voyager1()),
        ]
        resp = self.configurar(liMasOpciones, siCambioTutor=True, siSonidos=True)

        if resp == "rotacion":
            self.siVolteoAutomatico = not self.siVolteoAutomatico
            siBlancas = self.partida.ultPosicion.siBlancas
            if self.siVolteoAutomatico:
                if siBlancas != self.tablero.siBlancasAbajo:
                    self.tablero.rotaTablero()
        elif resp == "apertura":
            me = self.unMomento()
            w = PantallaAperturas.WAperturas(self.pantalla, self.configuracion, self.bloqueApertura)
            me.final()
            if w.exec_():
                self.bloqueApertura = w.resultado()
                # self.posicApertura = ps
                self.fen = None
                self.reiniciar()

        elif resp == "posicion":
            self.startPosition()

        elif resp == "pasteposicion":
            texto = QTUtil.traePortapapeles()
            if texto:
                cp = ControlPosicion.ControlPosicion()
                try:
                    cp.leeFen(str(texto))
                    self.fen = cp.fen()
                    self.bloqueApertura = None
                    self.posicApertura = None
                    self.reiniciar()
                except:
                    pass

        elif resp == "leerpgn":
            unpgn = PantallaPGN.eligePartida(self.pantalla)
            if unpgn:
                self.bloqueApertura = None
                self.posicApertura = None
                self.fen = unpgn.dic.get("FEN", None)
                dic = self.creaDic()
                dic["PARTIDA"] = unpgn.partida.guardaEnTexto()
                dic["liPGN"] = unpgn.listaCabeceras()
                dic["FEN"] = self.fen
                dic["SIBLANCASABAJO"] = unpgn.partida.ultPosicion.siBlancas
                self.reiniciar(dic)

        elif resp == "pastepgn":
            texto = QTUtil.traePortapapeles()
            if texto:
                unpgn = PGN.UnPGN()
                unpgn.leeTexto(texto)
                if unpgn.siError:
                    QTUtil2.mensError(self.pantalla, _("The text from the clipboard does not contain a chess game in PGN format"))
                    return
                self.bloqueApertura = None
                self.posicApertura = None
                self.fen = unpgn.dic.get("FEN", None)
                dic = self.creaDic()
                dic["PARTIDA"] = unpgn.partida.guardaEnTexto()
                dic["liPGN"] = unpgn.listaCabeceras()
                dic["FEN"] = self.fen
                dic["SIBLANCASABAJO"] = unpgn.partida.ultPosicion.siBlancas
                self.reiniciar(dic)

        elif resp == "motor":
            self.ponRotulo1("")
            if self.siJuegaMotor:
                if self.xrival:
                    self.xrival.terminar()
                    self.xrival = None
                self.siJuegaMotor = False
            else:
                self.cambioRival()

        elif resp == "voyager":
            ptxt = Voyager.voyagerPartida(self.pantalla, self.partida)
            if ptxt:
                dic = self.creaDic()
                dic["PARTIDA"] = ptxt
                p = self.partida.copia()
                p.recuperaDeTexto(ptxt)
                dic["FEN"] = None if p.siFenInicial() else p.iniPosicion.fen()
                dic["SIBLANCASABAJO"] = self.tablero.siBlancasAbajo
                self.reiniciar(dic)
コード例 #19
0
ファイル: QTVarios.py プロジェクト: JERUKA9/lucaschess
def savePGN( owner, pgn ):
    configuracion = VarGen.configuracion
    dicVariables = configuracion.leeVariables("SAVEPGN")

    liGen = [(None, None)]

    liHistorico = dicVariables.get("LIHISTORICO")

    config = FormLayout.Fichero(_("File to save"), "pgn", True, liHistorico=liHistorico, anchoMinimo=300)
    liGen.append(( config, "" ))

    #Codec
    liCodecs = [k for k in set(v for k,v in aliases.iteritems())]
    liCodecs.sort()
    liCodecs = [(k,k) for k in liCodecs]
    liCodecs.insert( 0, (_("Same as file"), "file" ) )
    liCodecs.insert( 0, ("%s: UTF-8"%_("By default"), "default" ) )
    config = FormLayout.Combobox(_("Write with the codec"), liCodecs)
    codec = dicVariables.get("CODEC", "default")
    liGen.append(( config, codec ))

    #Overwrite
    liGen.append( ( _("Overwrite"), dicVariables.get("OVERWRITE", False)) )

    #Remove comments
    liGen.append( ( _("Remove comments and variations"), dicVariables.get("REMCOMMENTSVAR", False)) )

    # Editamos
    resultado = FormLayout.fedit(liGen, title=_("Save PGN"), parent=owner, icon=Iconos.PGN())
    if resultado is None:
        return

    accion, liResp = resultado
    fichero, codec, overwrite, remcommentsvar = liResp
    if not fichero:
        return
    if not liHistorico:
        liHistorico = []
    if fichero in liHistorico:
        del liHistorico[liHistorico.index(fichero)]
        chardet
    liHistorico.insert(0,fichero)

    dicVariables["LIHISTORICO"] = liHistorico[:20]
    dicVariables["CODEC"] = codec
    dicVariables["OVERWRITE"] = overwrite
    dicVariables["REMCOMMENTSVAR"] = remcommentsvar

    configuracion.escVariables("SAVEPGN",dicVariables)
    carpeta, name = os.path.split(fichero)
    if carpeta != configuracion.dirSalvados:
        configuracion.dirSalvados = carpeta
        configuracion.graba()

    if remcommentsvar:
        pgn = PGN.rawPGN(pgn)
    pgn = pgn.replace( "\n", "\r\n" )

    modo = "w" if overwrite else "a"
    if not overwrite:
        if not Util.existeFichero(fichero):
            modo = "w"
    if codec == "default":
        codec = "utf-8"
    elif codec == "file":
        codec = "utf-8"
        if Util.existeFichero(fichero):
            with open(fichero) as f:
                u = chardet.universaldetector.UniversalDetector()
                for n, x in enumerate(f):
                    u.feed(x)
                    if n == 1000:
                        break
                u.close()
                codec = u.result.get("encoding", "utf-8")

    try:
        f = codecs.open( fichero, modo, codec, 'ignore' )
        if modo == "a":
            f.write( "\r\n\r\n" )
        f.write(pgn)
        f.close()
        QTUtil2.mensajeTemporal( owner, _( "Saved" ), 1.2 )
    except:
        QTUtil.ponPortapapeles(pgn)
        QTUtil2.mensError(owner, "%s : %s\n\n%s" % (_("Unable to save"), fichero, _("It is saved in the clipboard to paste it wherever you want.") ))
コード例 #20
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()
コード例 #21
0
ファイル: GestorPGN.py プロジェクト: wassekaran/lucaschess_11
    def ficheroMostrar(self,
                       dicDB,
                       siRepite,
                       siAnterior=False,
                       siSiguiente=False):

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

        if (not siRepite) and self.siFicheroNuestro:
            orden = "ROWID DESC"
        else:
            orden = ""

        dClavesTam = dicDB["DCLAVES"]
        dbf = bd.dbf(
            "GAMES", ",".join(dClavesTam.keys()), orden=orden
        )  # La lectura se hace en la pantalla, para que la haga en el mismo sitio tanto siRepite como si no

        estadoWpgn = dicDB["ESTADOWPGN"] if siRepite else None

        if siAnterior or siSiguiente:
            siSeguir = True
            siSeHaBorradoAlgo = False
            dbf.leer()
            recno = estadoWpgn.recno
            if siAnterior:
                if recno > 0:
                    recno -= 1
            elif siSiguiente:
                if recno < dbf.reccount() - 1:
                    recno += 1
            dbf.goto(recno)
            estadoWpgn.recno = recno
        else:
            siSeguir, estadoWpgn, siSeHaBorradoAlgo = PantallaPGN.elegirPGN(
                self.pantalla, dbf, dClavesTam, self, estadoWpgn)

        if siSeguir:
            self.pensando(True)
            rid = dbf.rowid(dbf.recno)
            self.dicDB = dicDB
            dicDB["ESTADOWPGN"] = estadoWpgn
            dbf.cerrar()
            dbf = bd.dbfT("GAMES",
                          ",".join(dClavesTam.keys()) + ",PGN",
                          condicion="ROWID=%d" % rid)
            dbf.leer()
            dbf.gotop()
            dicDatos = dbf.dicValores()
            self.pgnPaste = dicDatos["PGN"]

            dbf.cerrar()
            pgn = PGN.UnPGN()
            pgn.leeTexto(self.pgnPaste)
            siMostrar = not pgn.siError
            self.pensando(False)
            if not siMostrar:
                QTUtil2.mensError(self.pantalla,
                                  _("This is not a valid PGN file"))

        else:
            siMostrar = False

        bd.cerrar()

        if siSeHaBorradoAlgo:
            fpgn = PGN.PGN()
            fpgn.borraReferenciaA(dicDB["FICHERO"])

        if siMostrar:
            self.mostrar(pgn, True)
        elif self.muestraInicial or self.finExit:
            self.finPartida()
コード例 #22
0
ファイル: PantallaPGN.py プロジェクト: garyliu33/lucaschess
    def masivo(self):

        liSeleccionadas = self.grid.recnosSeleccionados()
        nSeleccionadas = len(liSeleccionadas)

        alm = PantallaParamAnalisis.paramAnalisisMasivo(
            self, self.gestor.configuracion, nSeleccionadas > 1)
        if alm:

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

            tmpBP = QTUtil2.BarraProgreso2(self,
                                           _("Mass analysis"),
                                           formato2="%p%")
            tmpBP.ponTotal(1, nregs)
            tmpBP.ponRotulo(1, _("Game"))
            tmpBP.ponRotulo(2, _("Moves"))
            tmpBP.mostrar()

            import Code.Analisis

            ap = Code.Analisis.AnalizaPartida(self.gestor.procesador, alm,
                                              True)

            for n in range(nregs):

                if tmpBP.siCancelado():
                    break

                tmpBP.pon(1, n + 1)

                if alm.siVariosSeleccionados:
                    n = liSeleccionadas[n]

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

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

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

                ap.xprocesa(pgn.dic, pgn.partida, tmpBP, jugadas)

            if not tmpBP.siCancelado():
                ap.terminar(True)

                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)
                mensajeEntrenamientos(self, liCreados, liNoCreados)

            else:
                ap.terminar(False)

            tmpBP.cerrar()
コード例 #23
0
ファイル: GestorEntTac.py プロジェクト: garyliu33/lucaschess
    def inicio(self, tactica, posSiguiente=None):

        if hasattr(self, "reiniciando"):
            if self.reiniciando:
                return
        self.reiniciando = True

        self.tactica = tactica

        liOrden = self.tactica.listaOrden()

        self.numPosiciones = self.tactica.numPosiciones()
        self.posActual = self.tactica.posActual()

        numEnt = liOrden[self.posActual]

        self.siPenalizable = True
        self.puestosPenalizacion = self.tactica.puestosPenalizacion(self.posActual, len(liOrden))

        self.pointView = self.tactica.pointView()

        txtEntreno = self.tactica.unFNS(numEnt)

        if posSiguiente is None:
            self.posSiguiente = self.posActual + 1

        li = txtEntreno.split("|")

        fenInicial = li[0]
        if fenInicial.endswith(" 0"):
            fenInicial = fenInicial[:-1] + "1"

        self.fenInicial = fenInicial

        self.dicEtiquetasPGN = None
        siPartidaOriginal = False
        nli = len(li)
        if nli >= 2:
            etiDirigido = li[1]

            # # Solucion
            if nli >= 3:
                solucion = li[2]
                if solucion:
                    self.dicDirigidoFen = PGN.leeEntDirigido(fenInicial, solucion)

                ## Partida original
                if nli >= 4:
                    pgn = PGN.UnPGN()
                    if nli > 4:
                        txt = "|".join(li[3:])
                    else:
                        txt = li[3]
                    txt = txt.replace("]", "]\n").replace(" [", "[")
                    pgn.leeTexto(txt)
                    partida = pgn.partida
                    siEstaFen = False
                    njug = partida.numJugadas()
                    for n in range(njug - 1, -1, -1):
                        jg = partida.jugada(n)
                        if jg.posicion.fen() == fenInicial:
                            siEstaFen = True
                            if n + 1 != njug:
                                partida.liJugadas = partida.liJugadas[:n + 1]
                                partida.ultPosicion = jg.posicion.copia()
                            break
                    if siEstaFen:
                        siPartidaOriginal = True
                        self.partida = partida
                        self.pgn.partida = partida
                        self.dicEtiquetasPGN = pgn.dic
                        # for k, v in pgn.dic.iteritems():
                        # if k.upper() != "FEN":
                        # if etiDirigido:
                        # etiDirigido += "<br>"
                        # etiDirigido += "%s: <b>%s</b>"%(k,v)

        cp = ControlPosicion.ControlPosicion()
        cp.leeFen(fenInicial)

        self.fen = fenInicial

        siBlancas = cp.siBlancas

        if self.pointView:
            siBlancas = self.pointView == 1

        if not siPartidaOriginal:
            self.partida.reset(cp)

        self.partida.pendienteApertura = False

        self.tipoJuego = kJugEntTac

        self.siJuegaHumano = False
        self.siJuegaPorMi = True

        self.siJugamosConBlancas = siBlancas
        self.siRivalConBlancas = not siBlancas

        self.liVariantes = []

        self.rmRival = None

        self.siTutorActivado = False
        self.pantalla.ponActivarTutor(False)

        self.ayudasPGN = 0

        self.pantalla.activaJuego(True, False, siAyudas=False)
        self.pantalla.quitaAyudas(True, True)
        self.ponMensajero(self.mueveHumano)
        self.ponPosicion(self.partida.ultPosicion)
        self.mostrarIndicador(True)
        self.ponPiezasAbajo(siBlancas)
        # txttact = "%dx%d"%(tactica.numFNS(),len(tactica.JUMPS)+1)
        # txttact = "(%s)x%d"%(txttact,len(tactica.REPEAT))
        self.siShowText = tactica.siShowText()
        titulo = "<b>%s</b><br>" % (self.tactica.titulo,)  # txttact)
        self.tituloAmpliado = titulo + etiDirigido
        if self.siShowText:
            titulo = self.tituloAmpliado
        else:
            self.siShowText = len(etiDirigido) == 0

        liOpciones = [k_mainmenu]
        if not self.siShowText:
            liOpciones.append(k_showtext)
        if self.dicEtiquetasPGN:
            liOpciones.append(k_pgnInformacion)
        self.pantalla.ponToolBar(liOpciones)
        self.ponRotulo1(titulo)
        self.pgnRefresh(True)
        QTUtil.xrefreshGUI()

        self.ponPosicionDGT()

        self.siSeguirJugando = False
        self.xrival = self.procesador.creaGestorMotor(self.configuracion.tutor, min(self.configuracion.tiempoTutor, 5),
                                                      None)

        self.reiniciando = False

        self.rivalPensando = False

        if siPartidaOriginal:
            self.repiteUltimaJugada()

        self.ponSiguiente()

        self.estado = kJugando
        self.siguienteJugada()
コード例 #24
0
    def configurarGS(self):
        sep = (None, None, None)

        liMasOpciones = [
            ("rotacion", _("Auto-rotate board"), Iconos.JS_Rotacion()),
            sep,
            ("leerpgn", _("Read PGN"), Iconos.PGN_Importar()),
            sep,
            ("pastepgn", _("Paste PGN"), Iconos.Pegar16()),
            sep,
        ]
        if not self.siCompleta:
            liMasOpciones.extend([
                ("posicion", _("Start position"), Iconos.Datos()), sep,
                ("pasteposicion", _("Paste FEN position"), Iconos.Pegar16()),
                sep, ("voyager", _("Voyager 2"), Iconos.Voyager1())
            ])

        resp = self.configurar(liMasOpciones,
                               siCambioTutor=True,
                               siSonidos=True)

        if resp == "rotacion":
            self.siVolteoAutomatico = not self.siVolteoAutomatico
            siBlancas = self.partida.ultPosicion.siBlancas
            if self.siVolteoAutomatico:
                if siBlancas != self.tablero.siBlancasAbajo:
                    self.tablero.rotaTablero()

        elif resp == "posicion":
            ini_fen = self.partida.iniPosicion.fen()
            cur_fen = Voyager.voyagerFEN(self.pantalla, ini_fen)
            if cur_fen and cur_fen != ini_fen:
                self.partida.resetFEN(cur_fen)
                self.inicio(self.partida, self.siCompleta)

        elif resp == "pasteposicion":
            texto = QTUtil.traePortapapeles()
            if texto:
                cp = ControlPosicion.ControlPosicion()
                try:
                    cp.leeFen(str(texto))
                    self.fen = cp.fen()
                    self.posicApertura = None
                    self.reiniciar()
                except:
                    pass

        elif resp == "leerpgn":
            unpgn = PantallaPGN.eligePartida(self.pantalla)
            if unpgn:
                partida = unpgn.partida
                if self.siCompleta and not partida.siFenInicial():
                    return
                p = Partida.PartidaCompleta()
                p.leeOtra(partida)
                p.asignaApertura()
                p.setTags(unpgn.listaCabeceras())
                self.reinicio = p.save()
                self.reiniciar()

        elif resp == "pastepgn":
            texto = QTUtil.traePortapapeles()
            if texto:
                unpgn = PGN.UnPGN()
                unpgn.leeTexto(texto)
                if unpgn.siError:
                    QTUtil2.mensError(
                        self.pantalla,
                        _("The text from the clipboard does not contain a chess game in PGN format"
                          ))
                    return
                partida = unpgn.partida
                if self.siCompleta and not partida.siFenInicial():
                    return
                p = Partida.PartidaCompleta()
                p.leeOtra(partida)
                p.asignaApertura()
                p.setTags(unpgn.listaCabeceras())
                self.reinicio = p.save()
                self.reiniciar()

        elif resp == "voyager":
            ptxt = Voyager.voyagerPartida(self.pantalla, self.partida)
            if ptxt:
                dic = self.creaDic()
                dic["PARTIDA"] = ptxt
                p = self.partida.copia()
                p.recuperaDeTexto(ptxt)
                dic["FEN"] = None if p.siFenInicial() else p.iniPosicion.fen()
                dic["SIBLANCASABAJO"] = self.tablero.siBlancasAbajo
                self.reiniciar(dic)
コード例 #25
0
ファイル: PantallaPGN.py プロジェクト: garyliu33/lucaschess
    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)
コード例 #26
0
ファイル: GestorEntPos.py プロジェクト: Slyte159/lucaschess
    def inicio(self, posEntreno, numEntrenos, titEntreno, liEntrenos, siTutorActivado=None, jump=False):
        if hasattr(self, "reiniciando"):
            if self.reiniciando:
                return
        self.reiniciando = True

        if siTutorActivado is None:
            siTutorActivado = (VarGen.dgtDispatch is None) and self.configuracion.tutorActivoPorDefecto

        self.posEntreno = posEntreno
        self.guardaPosicion(posEntreno)
        self.numEntrenos = numEntrenos
        self.titEntreno = titEntreno
        self.liEntrenos = liEntrenos
        self.jump = jump

        self.liHistorico = [self.posEntreno]

        self.ayudas = 99999

        fenInicial = self.liEntrenos[self.posEntreno - 1].strip()
        self.fenInicial = fenInicial

        self.rivalPensando = False

        self.dicEtiquetasPGN = None

        # Dirigido
        etiDirigido = ""
        self.siDirigido = False
        self.siDirigidoSeguir = None
        self.siDirigidoVariantes = False
        siPartidaOriginal = False
        if "|" in fenInicial:
            li = fenInicial.split("|")

            fenInicial = li[0]
            if fenInicial.endswith(" 0"):
                fenInicial = fenInicial[:-1] + "1"

            nli = len(li)
            if nli >= 2:
                etiDirigido = li[1]

                # # Solucion
                if nli >= 3:
                    solucion = li[2]
                    if solucion:
                        self.dicDirigidoFen = PGN.leeEntDirigido(fenInicial, solucion)
                        self.siDirigido = self.dicDirigidoFen and len(self.dicDirigidoFen) > 0

                    ## Partida original
                    if nli >= 4:
                        if nli > 4:
                            txt = "|".join(li[3:])
                        else:
                            txt = li[3]
                        txt = txt.replace("]", "]\n").replace(" [", "[")
                        pgn = PGN.UnPGN()
                        pgn.leeTexto(txt)
                        partida = pgn.partida
                        siEstaFen = False
                        njug = partida.numJugadas()
                        for n in range(njug - 1, -1, -1):
                            jg = partida.jugada(n)
                            if jg.posicion.fen() == fenInicial:
                                siEstaFen = True
                                if n + 1 != njug:
                                    partida.liJugadas = partida.liJugadas[:n + 1]
                                    partida.ultPosicion = jg.posicion.copia()
                                break
                        if siEstaFen:
                            siPartidaOriginal = True
                            self.partida = partida
                            self.pgn.partida = partida
                            self.dicEtiquetasPGN = pgn.dic
                            # if etiDirigido:
                            # etiDirigido += "<br>"
                            # for k, v in pgn.dic.iteritems():
                            # if k.upper() != "FEN":
                            # if etiDirigido:
                            # etiDirigido += "<br>"
                            # etiDirigido += "%s: <b>%s</b>"%(k,v)

        cp = ControlPosicion.ControlPosicion()
        cp.leeFen(fenInicial)

        self.fen = fenInicial

        siBlancas = cp.siBlancas

        if not siPartidaOriginal:
            self.partida.reset(cp)

        self.partida.pendienteApertura = False

        self.tipoJuego = kJugEntPos

        self.siJuegaHumano = False
        self.estado = kJugando
        self.siJuegaPorMi = True

        self.siJugamosConBlancas = siBlancas
        self.siRivalConBlancas = not siBlancas

        self.liVariantes = []

        self.rmRival = None

        self.siTutorActivado = siTutorActivado
        self.pantalla.ponActivarTutor(self.siTutorActivado)

        self.ayudasPGN = 0

        liOpciones = [k_mainmenu, k_cambiar, k_reiniciar, k_atras]
        if self.dicEtiquetasPGN:
            liOpciones.append(k_pgnInformacion)
        if self.numEntrenos > 1:
            liOpciones.append(k_anterior)
            liOpciones.append(k_siguiente)
        liOpciones.extend((k_configurar, k_utilidades))
        self.liOpcionesToolBar = liOpciones
        self.pantalla.ponToolBar(liOpciones)

        self.pantalla.activaJuego(True, False, siAyudas=False)
        self.pantalla.quitaAyudas(False, False)
        self.ponMensajero(self.mueveHumano)
        self.ponPosicion(self.partida.ultPosicion)
        self.mostrarIndicador(True)
        self.ponPiezasAbajo(siBlancas)
        titulo = "<b>%s</b>" % TrListas.dicTraining().get(self.titEntreno, self.titEntreno)
        if etiDirigido:
            titulo += "<br>%s" % etiDirigido
        self.ponRotulo1(titulo)
        self.ponRotulo2("%d / %d" % (posEntreno, numEntrenos))
        self.pgnRefresh(True)
        QTUtil.xrefreshGUI()

        self.xrival = self.procesador.creaGestorMotor(self.configuracion.tutor, self.configuracion.tiempoTutor, None)

        self.siAnalizadoTutor = False

        self.ponPosicionDGT()

        if siPartidaOriginal:
            # self.ponteAlFinal()
            self.repiteUltimaJugada()

        self.reiniciando = False
        self.rivalPensando = False
        self.siguienteJugada()
コード例 #27
0
    def inicio(self, tactica, posSiguiente=None):

        if hasattr(self, "reiniciando"):
            if self.reiniciando:
                return
        self.reiniciando = True

        self.tactica = tactica

        liOrden = self.tactica.listaOrden()

        self.numPosiciones = self.tactica.numPosiciones()
        self.posActual = self.tactica.posActual()

        numEnt = liOrden[self.posActual]

        self.siPenalizable = True
        self.puestosPenalizacion = self.tactica.puestosPenalizacion(
            self.posActual, len(liOrden))

        self.pointView = self.tactica.pointView()

        txtEntreno = self.tactica.unFNS(numEnt)

        if posSiguiente is None:
            self.posSiguiente = self.posActual + 1

        li = txtEntreno.split("|")

        fenInicial = li[0]
        if fenInicial.endswith(" 0"):
            fenInicial = fenInicial[:-1] + "1"

        self.fenInicial = fenInicial

        self.dicEtiquetasPGN = None
        siPartidaOriginal = False
        nli = len(li)
        if nli >= 2:
            etiDirigido = li[1]

            # # Solucion
            if nli >= 3:
                solucion = li[2]
                if solucion:
                    self.dicDirigidoFenM2 = PGN.leeEntDirigidoM2(
                        fenInicial, solucion)

                # Partida original
                if nli >= 4:
                    pgn = PGN.UnPGN()
                    if nli > 4:
                        txt = "|".join(li[3:])
                    else:
                        txt = li[3]
                    txt = txt.replace("]", "]\n").replace(" [", "[")
                    pgn.leeTexto(txt)
                    partida = pgn.partida
                    siEstaFen = False
                    njug = partida.numJugadas()
                    for n in range(njug - 1, -1, -1):
                        jg = partida.jugada(n)
                        if jg.posicion.fen() == fenInicial:
                            siEstaFen = True
                            if n + 1 != njug:
                                partida.liJugadas = partida.liJugadas[:n + 1]
                                partida.ultPosicion = jg.posicion.copia()
                            break
                    if siEstaFen:
                        siPartidaOriginal = True
                        self.partida = partida
                        self.pgn.partida = partida
                        self.dicEtiquetasPGN = pgn.dic
                        # for k, v in pgn.dic.items():
                        # if k.upper() != "FEN":
                        # if etiDirigido:
                        # etiDirigido += "<br>"
                        # etiDirigido += "%s: <b>%s</b>"%(k,v)

        cp = ControlPosicion.ControlPosicion()
        cp.leeFen(fenInicial)

        self.fen = fenInicial

        siBlancas = cp.siBlancas

        if self.pointView:
            siBlancas = self.pointView == 1

        if not siPartidaOriginal:
            self.partida.reset(cp)

        self.partida.pendienteApertura = False

        self.tipoJuego = kJugEntTac

        self.siJuegaHumano = False
        self.siJuegaPorMi = True

        self.siJugamosConBlancas = siBlancas
        self.siRivalConBlancas = not siBlancas

        self.liVariantes = []

        self.rmRival = None

        self.siTutorActivado = False
        self.pantalla.ponActivarTutor(False)

        self.ayudasPGN = 0

        self.pantalla.activaJuego(True, False, siAyudas=False)
        self.pantalla.quitaAyudas(True, True)
        self.ponMensajero(self.mueveHumano)
        self.ponPosicion(self.partida.ultPosicion)
        self.mostrarIndicador(True)
        self.ponPiezasAbajo(siBlancas)
        # txttact = "%dx%d"%(tactica.numFNS(),len(tactica.JUMPS)+1)
        # txttact = "(%s)x%d"%(txttact,len(tactica.REPEAT))
        self.siShowText = tactica.siShowText()
        titulo = "<b>%s</b><br>" % (self.tactica.titulo, )  # txttact)
        self.tituloAmpliado = titulo + etiDirigido
        if self.siShowText:
            titulo = self.tituloAmpliado
        else:
            self.siShowText = len(etiDirigido) == 0

        liOpciones = [k_mainmenu]
        if not self.siShowText:
            liOpciones.append(k_showtext)
        if self.dicEtiquetasPGN:
            liOpciones.append(k_pgnInformacion)
        self.pantalla.ponToolBar(liOpciones)
        self.ponRotulo1(titulo)
        self.pgnRefresh(True)
        QTUtil.xrefreshGUI()

        self.ponPosicionDGT()

        self.siSeguirJugando = False
        tiempo = self.configuracion.tiempoTutor
        if tiempo < 1000 or tiempo > 5000:
            tiempo = 5000
        self.xrival = self.procesador.creaGestorMotor(self.configuracion.tutor,
                                                      tiempo, None)

        self.reiniciando = False

        self.rivalPensando = False

        if siPartidaOriginal:
            self.repiteUltimaJugada()

        self.ponSiguiente()

        self.estado = kJugando
        self.siguienteJugada()
コード例 #28
0
    def inicio(self,
               posEntreno,
               numEntrenos,
               titEntreno,
               liEntrenos,
               siTutorActivado=None,
               jump=False):
        if hasattr(self, "reiniciando"):
            if self.reiniciando:
                return
        self.reiniciando = True

        if siTutorActivado is None:
            siTutorActivado = (VarGen.dgtDispatch is None
                               ) and self.configuracion.tutorActivoPorDefecto

        self.posEntreno = posEntreno
        self.guardaPosicion(posEntreno)
        self.numEntrenos = numEntrenos
        self.titEntreno = titEntreno
        self.liEntrenos = liEntrenos
        self.jump = jump

        self.liHistorico = [self.posEntreno]

        self.ayudas = 99999

        fenInicial = self.liEntrenos[self.posEntreno - 1].strip()
        self.fenInicial = fenInicial

        self.rivalPensando = False

        self.dicEtiquetasPGN = None

        # Dirigido
        etiDirigido = ""
        self.siDirigido = False
        self.siDirigidoSeguir = None
        self.siDirigidoVariantes = False
        siPartidaOriginal = False
        if "|" in fenInicial:
            li = fenInicial.split("|")

            fenInicial = li[0]
            if fenInicial.endswith(" 0"):
                fenInicial = fenInicial[:-1] + "1"

            nli = len(li)
            if nli >= 2:
                etiDirigido = li[1]

                # # Solucion
                if nli >= 3:
                    solucion = li[2]
                    if solucion:
                        self.dicDirigidoFenM2 = PGN.leeEntDirigidoM2(
                            fenInicial, solucion)
                        self.siDirigido = len(self.dicDirigidoFenM2) > 0

                    # Partida original
                    if nli >= 4:
                        if nli > 4:
                            txt = "|".join(li[3:])
                        else:
                            txt = li[3]
                        txt = txt.replace("]", "]\n").replace(" [", "[")
                        pgn = PGN.UnPGN()
                        pgn.leeTexto(txt)
                        partida = pgn.partida
                        siEstaFen = False
                        njug = partida.numJugadas()
                        for n in range(njug - 1, -1, -1):
                            jg = partida.jugada(n)
                            if jg.posicion.fen() == fenInicial:
                                siEstaFen = True
                                if n + 1 != njug:
                                    partida.liJugadas = partida.liJugadas[:n +
                                                                          1]
                                    partida.ultPosicion = jg.posicion.copia()
                                break
                        if siEstaFen:
                            siPartidaOriginal = True
                            self.partida = partida
                            self.pgn.partida = partida
                            self.dicEtiquetasPGN = pgn.dic
                            # if etiDirigido:
                            # etiDirigido += "<br>"
                            # for k, v in pgn.dic.iteritems():
                            # if k.upper() != "FEN":
                            # if etiDirigido:
                            # etiDirigido += "<br>"
                            # etiDirigido += "%s: <b>%s</b>"%(k,v)

        cp = ControlPosicion.ControlPosicion()
        cp.leeFen(fenInicial)

        self.fen = fenInicial

        siBlancas = cp.siBlancas

        if not siPartidaOriginal:
            self.partida.reset(cp)

        self.partida.pendienteApertura = False

        self.tipoJuego = kJugEntPos

        self.siJuegaHumano = False
        self.estado = kJugando
        self.siJuegaPorMi = True

        self.siJugamosConBlancas = siBlancas
        self.siRivalConBlancas = not siBlancas

        self.liVariantes = []

        self.rmRival = None

        self.siTutorActivado = siTutorActivado
        self.pantalla.ponActivarTutor(self.siTutorActivado)

        self.ayudasPGN = 0

        liOpciones = [k_mainmenu, k_cambiar, k_reiniciar, k_atras]
        if self.dicEtiquetasPGN:
            liOpciones.append(k_pgnInformacion)
        liOpciones.extend((k_configurar, k_utilidades))
        if self.numEntrenos > 1:
            liOpciones.extend((k_anterior, k_siguiente))
        self.liOpcionesToolBar = liOpciones
        self.pantalla.ponToolBar(liOpciones)

        self.pantalla.activaJuego(True, False, siAyudas=False)
        self.pantalla.quitaAyudas(False, False)
        self.ponMensajero(self.mueveHumano)
        self.ponPosicion(self.partida.ultPosicion)
        self.mostrarIndicador(True)
        self.ponPiezasAbajo(siBlancas)
        titulo = "<b>%s</b>" % TrListas.dicTraining().get(
            self.titEntreno, self.titEntreno)
        if etiDirigido:
            titulo += "<br>%s" % etiDirigido
        self.ponRotulo1(titulo)
        self.ponRotulo2("%d / %d" % (posEntreno, numEntrenos))
        self.pgnRefresh(True)
        QTUtil.xrefreshGUI()

        if self.xrival is None:
            self.xrival = self.procesador.creaGestorMotor(
                self.configuracion.tutor, self.configuracion.tiempoTutor,
                self.configuracion.depthTutor)

        self.siAnalizadoTutor = False

        self.ponPosicionDGT()

        if siPartidaOriginal:
            # self.ponteAlFinal()
            self.repiteUltimaJugada()

        self.reiniciando = False
        self.rivalPensando = False
        self.siguienteJugada()
コード例 #29
0
    def inicio(self,
               fen,
               lineaPGN,
               okMasOpciones,
               siBlancasAbajo,
               siEngineActivo=False):

        self.pensando(True)

        self.liKibitzersActivas = self.procesador.liKibitzersActivas

        self.okMasOpciones = okMasOpciones

        self.fen = fen
        self.lineaPGN = lineaPGN

        self.siAceptado = False

        uno = PGN.UnPGN()
        uno.leeTexto('[FEN "%s"]\n%s' % (fen, lineaPGN))

        self.partida = uno.partida
        self.pgn.partida = self.partida

        self.tipoJuego = kJugSolo

        self.siJuegaHumano = True
        self.siJuegaPorMi = True
        self.dicRival = {}

        self.siJuegaMotor = False

        self.estado = kJugando

        self.siRevision = False

        self.siVolteoAutomatico = False
        self.pantalla.ponToolBar((k_aceptar, k_cancelar, k_atras, k_reiniciar,
                                  k_configurar, k_utilidades))

        self.siJugamosConBlancas = siBlancasAbajo
        self.pantalla.activaJuego(True, False, siAyudas=False)
        self.quitaAyudas(True, False)
        self.pantalla.ponRotulo1(None)
        self.pantalla.ponRotulo2(None)
        self.mostrarIndicador(True)
        self.ponPiezasAbajo(self.siJugamosConBlancas)
        self.ponMensajero(self.mueveHumano)
        self.pgnRefresh(True)
        self.ponCapInfoPorDefecto()

        self.refresh()

        if self.partida.numJugadas():
            self.mueveJugada(kMoverInicio)
            jg = self.partida.jugada(0)
            self.ponFlechaSC(jg.desde, jg.hasta)
            self.desactivaTodas()
        else:
            self.ponPosicion(self.partida.ultPosicion)

        self.pensando(False)

        siBlancas = self.partida.ultPosicion.siBlancas
        self.siJugamosConBlancas = siBlancas
        self.siJuegaHumano = True

        if siEngineActivo:
            self.activeEngine()

        if not self.partida.numJugadas():
            self.siguienteJugada()
コード例 #30
0
def savePGN(owner, pgn):
    configuracion = VarGen.configuracion
    dicVariables = configuracion.leeVariables("SAVEPGN")

    liGen = [(None, None)]

    liHistorico = dicVariables.get("LIHISTORICO")

    config = FormLayout.Fichero(_("File to save"),
                                "pgn",
                                True,
                                liHistorico=liHistorico,
                                anchoMinimo=300)
    liGen.append((config, ""))

    #Codec
    liCodecs = [k for k in set(v for k, v in aliases.iteritems())]
    liCodecs.sort()
    liCodecs = [(k, k) for k in liCodecs]
    liCodecs.insert(0, (_("Same as file"), "file"))
    liCodecs.insert(0, ("%s: UTF-8" % _("By default"), "default"))
    config = FormLayout.Combobox(_("Write with the codec"), liCodecs)
    codec = dicVariables.get("CODEC", "default")
    liGen.append((config, codec))

    #Overwrite
    liGen.append((_("Overwrite"), dicVariables.get("OVERWRITE", False)))

    #Remove comments
    liGen.append((_("Remove comments and variations"),
                  dicVariables.get("REMCOMMENTSVAR", False)))

    # Editamos
    resultado = FormLayout.fedit(liGen,
                                 title=_("Save PGN"),
                                 parent=owner,
                                 icon=Iconos.PGN())
    if resultado is None:
        return

    accion, liResp = resultado
    fichero, codec, overwrite, remcommentsvar = liResp
    if not fichero:
        return
    if not liHistorico:
        liHistorico = []
    if fichero in liHistorico:
        del liHistorico[liHistorico.index(fichero)]
        chardet
    liHistorico.insert(0, fichero)

    dicVariables["LIHISTORICO"] = liHistorico[:20]
    dicVariables["CODEC"] = codec
    dicVariables["OVERWRITE"] = overwrite
    dicVariables["REMCOMMENTSVAR"] = remcommentsvar

    configuracion.escVariables("SAVEPGN", dicVariables)
    carpeta, name = os.path.split(fichero)
    if carpeta != configuracion.dirSalvados:
        configuracion.dirSalvados = carpeta
        configuracion.graba()

    if remcommentsvar:
        pgn = PGN.rawPGN(pgn)
    pgn = pgn.replace("\n", "\r\n")

    modo = "w" if overwrite else "a"
    if not overwrite:
        if not Util.existeFichero(fichero):
            modo = "w"
    if codec == "default":
        codec = "utf-8"
    elif codec == "file":
        codec = "utf-8"
        if Util.existeFichero(fichero):
            with open(fichero) as f:
                u = chardet.universaldetector.UniversalDetector()
                for n, x in enumerate(f):
                    u.feed(x)
                    if n == 1000:
                        break
                u.close()
                codec = u.result.get("encoding", "utf-8")

    try:
        f = codecs.open(fichero, modo, codec, 'ignore')
        if modo == "a":
            f.write("\r\n\r\n")
        f.write(pgn)
        f.close()
        QTUtil2.mensajeTemporal(owner, _("Saved"), 1.2)
    except:
        QTUtil.ponPortapapeles(pgn)
        QTUtil2.mensError(
            owner, "%s : %s\n\n%s" %
            (_("Unable to save"), fichero,
             _("It is saved in the clipboard to paste it wherever you want.")))