Exemple #1
0
    def terminarBMT(self, bmt_lista, nombre):
        """
        Si se estan creando registros para el entrenamiento BMT (Best move Training), al final hay que grabarlos
        @param bmt_lista: lista a grabar
        @param nombre: nombre del entrenamiento
        """
        if bmt_lista and len(bmt_lista) > 0:
            bmt = BMT.BMT(self.configuracion.ficheroBMT)
            dbf = bmt.leerDBF(False)

            reg = dbf.baseRegistro()
            reg.ESTADO = "0"
            reg.NOMBRE = nombre
            reg.EXTRA = ""
            reg.TOTAL = len(bmt_lista)
            reg.HECHOS = 0
            reg.PUNTOS = 0
            reg.MAXPUNTOS = bmt_lista.maxPuntos()
            reg.FINICIAL = Util.dtos(Util.hoy())
            reg.FFINAL = ""
            reg.SEGUNDOS = 0
            reg.BMT_LISTA = Util.var2blob(bmt_lista)
            reg.HISTORIAL = Util.var2blob([])
            reg.REPE = 0
            reg.ORDEN = 0

            dbf.insertarReg(reg, siReleer=False)

            bmt.cerrar()
Exemple #2
0
def compruebaCambioCarpetas(configuracion):
    usrdata = configuracion.carpeta

    def haz(original, nueva):
        original = os.path.join(usrdata, original)
        nueva = os.path.join(usrdata, nueva)
        if os.path.isfile(original) and not os.path.isfile(nueva):
            shutil.move(original, nueva)

    haz("Mate positions in GM gamesB.tdb", "Checkmates in GM gamesB.tdb")
    haz("From Uwe Auerswald's CollectionB.tdb", "Tactics by Uwe AuerswaldB.tdb")

    if os.path.isfile("dataDB/dataDB.pkd"):
        os.remove("dataDB/dataDB.pkd")

    # cambios de ficheros gm
    gmConvert(configuracion)

    # cambios en dic entmaquina
    dic = Util.recuperaDIC(configuracion.ficheroEntMaquina)
    if dic:
        liAperturasFavoritas = dic.get("APERTURASFAVORITAS", [])
        if liAperturasFavoritas:
            for npos, x in enumerate(liAperturasFavoritas):
                if type(x) == tuple:
                    liAperturasFavoritas[npos] = x[0]
        Util.guardaDIC(dic, configuracion.ficheroEntMaquina)

    # Dic -> DicSQL
    dicDisk(configuracion)

    # Fichero potencia
    ficheroPotencia(configuracion)
Exemple #3
0
 def limpiaTemporal(self):
     try:
         dirTmp = os.path.join(self.carpeta, "tmp")
         for f in Util.listdir(dirTmp):
             Util.borraFichero(os.path.join(dirTmp, f))
     except:
         pass
Exemple #4
0
 def guardaDIC(self):
     dic = {}
     dic["SIBLANCAS"] = self.rbBlancas.isChecked()
     libro = self.cb.valor()
     dic["NOMLIBRO"] = None if libro is None else libro.nombre
     dic["RR"] = self.cbRR.valor()
     dic["RJ"] = self.chRJ.valor()
     Util.guardaVar(self.configuracion.ficheroTrainBooks, dic)
Exemple #5
0
    def aceptar(self):
        if not self.fichero:
            return

        me = QTUtil2.unMomento(self)

        # Creamos el pgn
        fichTemporal = self.wParent.damePGNtemporal()

        # Creamos la linea de ordenes
        if VarGen.isWindows:
            exe = 'EnginesWindows/polyglot/polyglot.exe'
        else:
            exe = 'EnginesLinux/polyglot/polyglot'
        li = [os.path.abspath(exe), 'make-book', "-pgn", fichTemporal, "-bin", self.fichero]
        Util.borraFichero(self.fichero)

        maxPly = self.sbMaxPly.valor()
        minGame = self.sbMinGame.valor()
        minScore = self.sbMinScore.valor()
        onlyWhite = self.chbOnlyWhite.valor()
        onlyBlack = self.chbOnlyBlack.valor()
        uniform = self.chbUniform.valor()
        if maxPly:
            li.append("-max-ply")
            li.append("%d" % maxPly)
        if minGame and minGame != 3:
            li.append("-min-game")
            li.append("%d" % minGame)
        if minScore:
            li.append("-min-score")
            li.append("%d" % minScore)
        if onlyBlack:
            li.append("-only-black")
        if onlyWhite:
            li.append("-only-white")
        if uniform:
            li.append("-uniform")

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

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

        Util.borraFichero(fichTemporal)

        nombre = os.path.basename(self.fichero)[:-4]
        b = Books.Libro("P", nombre, self.fichero, False)
        self.listaLibros.nuevo(b)
        fvar = self.configuracion.ficheroBooks
        self.listaLibros.guardaVar(fvar)

        self.accept()
    def polyglot(self):
        recno = self.grid.recno()
        if recno < 0:
            return
        reg = self.lista[recno]

        # Pedimos el fichero a generar
        fbin = QTUtil2.salvaFichero(self, _("Polyglot book"), reg["NOMBRE"] + ".bin", _("Polyglot book") + " (*.bin)")
        if not fbin:
            return

        me = QTUtil2.unMomento(self)

        # Determinamos el fichero de trabajo
        plTMP = "deleteme_%d.pgn"
        n = 0
        while True:
            fichTMP = plTMP % n
            if Util.existeFichero(fichTMP):
                n += 1
            else:
                break

        # Creamos el fichero de trabajo
        f = open(fichTMP, "wb")
        for pv in reg["LISTA"]:
            f.write('[Result "1/2-1/2"]\n')
            p = Partida.Partida()
            p.leerPV(pv)
            f.write(p.pgnBase() + " 1/2-1/2\n\n")
        f.close()

        # Ejecutamos
        if VarGen.isWindows:
            exe = 'EnginesWindows/polyglot/polyglot.exe'
        else:
            exe = 'EnginesLinux/polyglot/polyglot'
        li = [os.path.abspath(exe),
              'make-book',
              "-pgn", fichTMP,
              "-bin", fbin,
              "-max-ply", "99",
              "-min-game", "1",
              "-uniform"]
        Util.borraFichero(fbin)

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

        me.final()

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

        QTUtil2.mensaje(self, txt)

        Util.borraFichero(fichTMP)
    def temas(self):
        siHay = len(self.liTemas) > 0
        menu = QTVarios.LCMenu(self)

        if siHay:
            mr = menu.submenu(_("Open"), Iconos.Recuperar())
            ponMenuTemas(mr, self.liTemas, "r")
            menu.separador()

        if self.temaActual:
            menu.opcion("grabar", _("Save") + " " + self.temaActual["NOMBRE"], Iconos.Grabar())
            menu.separador()

        menu.opcion("grabarComo", _("Save as"), Iconos.GrabarComo())
        menu.separador()

        if siHay:
            mr = menu.submenu(_("Remove"), Iconos.Borrar())
            ico = Iconos.PuntoNegro()
            for n, uno in enumerate(self.liTemas):
                if uno:
                    mr.opcion("b%d" % n, uno["NOMBRE"], ico)
                    mr.separador()

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

        elif resp == "grabar":
            self.grabarTema(self.temaActual)

        elif resp == "grabarComo":
            tema = self.grabarTema({})
            self.liTemas.append(tema)

        elif resp.startswith("r"):
            num = int(resp[1:])
            tema = self.liTemas[num]
            self.temaActual = tema
            self.confTablero.leeTema(tema.get("TEXTO", ""))
            if "BASE" in tema:
                self.confTablero.leeBase(tema["BASE"])
            self.ponTema(tema)

        elif resp.startswith("b"):
            num = int(resp[1:])
            tema = self.liTemas[num]
            if QTUtil2.pregunta(self, _X(_("Delete %1?"), tema["NOMBRE"])):
                if self.temaActual == tema:
                    self.temaActual = {}
                del self.liTemas[num]

        fichero = self.configuracion.ficheroTemas
        li = []
        for tema in self.liTemas:
            if tema:
                li.append(tema)
        Util.guardaVar(fichero, li)
Exemple #8
0
def changeFolder(nueva):
    if nueva:
        if os.path.abspath(nueva) == os.path.abspath(LCBASEFOLDER):
            return changeFolder(None)
        f = open(LCFILEFOLDER, "wb")
        f.write(nueva)
        f.close()
    else:
        Util.borraFichero(LCFILEFOLDER)
Exemple #9
0
 def wav(self):
     carpeta = Util.recuperaVar(self.confich)
     fichero = QTUtil2.leeFichero(self, carpeta, "wav")
     if fichero:
         carpeta = os.path.dirname(fichero)
         Util.guardaVar(self.confich, carpeta)
         if self.taller.leeWAV(fichero):
             self.mesa.ponCentesimas(self.taller.centesimas)
         else:
             QTUtil2.mensError(self, _("It is impossible to read this file, it is not compatible."))
         self.ponBaseTB()
Exemple #10
0
    def leeSTS(self):
        li = []
        Util.creaCarpeta(self.carpetaSTS)
        for x in Util.listdir(self.carpetaSTS, siUnicode=True):
            if x.lower().endswith(".sts"):
                fich = os.path.join(self.carpetaSTS, x)
                st = os.stat(fich)
                li.append((x, st.st_ctime, st.st_mtime))

        sorted(li, key=lambda x: x[2], reverse=True)  # por ultima modificacin y al reves
        return li
Exemple #11
0
 def grabar(self):
     carpeta = Util.recuperaVar(self.confich)
     filtro = _("File") + " wav (*.wav)"
     fichero = QTUtil2.salvaFichero(self, _("Save wav"), carpeta, filtro, siConfirmarSobreescritura=True)
     if fichero:
         carpeta = os.path.dirname(fichero)
         Util.guardaVar(self.confich, carpeta)
         f = open(fichero, "wb")
         f.write(self.taller.wav)
         f.close()
         self.ponBaseTB()
 def getVideoItem(self, id, url=None, title=None, subtitle=None, summary=None, duration=None, thumb=None):
   """
   Get the VideoItem for a highlight video, either by assembling the data we
   already have, or fetching more from mlb.com
   """
   # (year, month, day, content_id) = (id[:4], id[4:6], id[6:8], id[8:])
   # subtitle = None #"posted %s/%s/%s" % (month, day, year)
   xml = None
   
   if None in [url, title, subtitle, summary, duration, thumb]:
     xurl = C["URL"]["GAME_DETAIL"] % (id[-3], id[-2], id[-1], id)
     xml = XML.ElementFromURL(xurl, headers={"Referer": Util.getURLRoot(xurl)})
   
   if url is None:
     # TODO this seems fragile.  investigate another way.
     for scenario in [
       "FLASH_1000K_640X360",
       "MLB_FLASH_1000K_PROGDNLD",
       "MLB_FLASH_1000K_STREAM_VPP",
       "FLASH_800K_640X360",
       "MLB_FLASH_800K_PROGDNLD",
       "MLB_FLASH_800K_STREAM_VPP",
       "FLASH_400K_600X338"
     ]:
       url = Util.XPathSelectOne(xml, 'url[@playback_scenario="' + scenario + '"]')
       if url is not None:
         break
     else:
       # couldn't find a URL
       return
   
   if duration is None:
     duration_string = Util.XPathSelectOne(xml, 'duration')
     if duration_string is not None:
       duration = int(Util.parseDuration(duration_string)) * 1000
   if title is None:
     title = Util.XPathSelectOne(xml, 'headline')
   if subtitle is None:
     date = isodate.parse_datetime(Util.XPathSelectOne(xml, '//@date'))
     # Log(date.astimezone(datetime.datetime.now().tzinfo))
     # subtitle = date.strftime("%a, %d %b %Y %H:%M:%S %Z")
     subtitle = date.strftime("%A, %B %d")
   
   if summary is None:
     summary = re.sub("^\s*(\d+\.){2}\d+\:", "", str(Util.XPathSelectOne(xml, 'big-blurb')))
   if thumb is None:
     thumb = Util.XPathSelectOne(xml, 'thumbnailScenarios/thumbnailScenario[@type="3"]')
   
   if url[:7] == "rtmp://":
     # pass clip as an empty string to prevent an exception
     return RTMPVideoItem(url, clip="", title=title, subtitle=subtitle, summary=summary, duration=duration, thumb=thumb)
   else:
     return VideoItem(url, title, subtitle=subtitle, summary=summary, duration=duration, thumb=thumb)
Exemple #13
0
    def aceptar(self):
        self.dic = self.creaDic()
        Util.guardaDIC(self.dic, self.configuracion.ficheroEntMaquina)

        # Info para el gestor, sin grabar
        dr = self.dic["RIVAL"]
        dr["CM"] = self.rival
        dr["TIPO"] = self.rivalTipo

        self.guardarVideo()

        self.accept()
Exemple #14
0
 def finPartida(self):
     if self.finExit:
         fichero = sys.argv[1]
         if os.path.dirname(fichero).lower() == "tmp":
             Util.borraFichero(fichero)
         self.procesador.procesarAccion(k_terminar)
         self.procesador.pararMotores()
         self.procesador.quitaKibitzers()
         sys.exit(0)
     else:
         self.quitaCapturas()
         self.procesador.inicio()
Exemple #15
0
    def cambioRival(self):
        dic = PantallaEntMaq.cambioRival(self.pantalla, self.configuracion, self.reinicio)

        if dic:
            Util.guardaDIC(dic, self.configuracion.ficheroEntMaquina)
            for k, v in dic.iteritems():
                self.reinicio[k] = v

            siBlancas = dic["SIBLANCAS"]

            self.siAtras = dic["ATRAS"]
            if self.siAtras:
                self.pantalla.ponToolBar(
                    ( k_mainmenu, k_rendirse, k_atras, k_reiniciar, k_aplazar, k_configurar, k_utilidades ))
            else:
                self.pantalla.ponToolBar(( k_mainmenu, k_rendirse, k_reiniciar, k_aplazar, k_configurar, k_utilidades ))

            self.rmRival = None

            self.nAjustarFuerza = dic["AJUSTAR"]

            dr = dic["RIVAL"]
            rival = dr["CM"]
            r_t = dr["TIEMPO"] * 100  # Se guarda en decimas -> milesimas
            r_p = dr["PROFUNDIDAD"]
            if r_t <= 0:
                r_t = None
            if r_p <= 0:
                r_p = None
            if r_t is None and r_p is None and not dic["SITIEMPO"]:
                r_t = 1000

            dr["RESIGN"] = self.resignPTS
            self.xrival = self.procesador.creaGestorMotor(rival, r_t, r_p, self.nAjustarFuerza != kAjustarMejor)

            self.xrival.siBlancas = not siBlancas

            rival = self.xrival.nombre
            jugador = self.configuracion.jugador
            bl, ng = jugador, rival
            if not siBlancas:
                bl, ng = ng, bl
            self.pantalla.cambiaRotulosReloj(bl, ng)

            # self.ponPiezasAbajo( siBlancas )
            self.ponRotuloBasico()

            self.ponPiezasAbajo(siBlancas)
            if siBlancas != self.siJugamosConBlancas:
                self.siJugamosConBlancas = siBlancas
                self.siRivalConBlancas = not siBlancas

                self.siguienteJugada()
Exemple #16
0
 def exportar(self):
     dr = self.configuracion.leeVariables("PCOLORES")
     dirBase = dr["DIRBASE"] if dr else ""
     fich = QTUtil2.salvaFichero(self, _("Colors"), dirBase, "*.lktheme1", True)
     if fich:
         dr["DIRBASE"] = os.path.dirname(fich)
         self.configuracion.escVariables("PCOLORES", dr)
         if not fich.lower().endswith("lktheme1"):
             fich += ".lktheme1"
         tema = {}
         tema["TEXTO"] = self.confTablero.grabaTema()
         tema["BASE"] = self.confTablero.grabaBase()
         Util.guardaVar(fich, tema)
    def entrenar(self, fil=None, col=None):
        if len(self.lista) == 0:
            return
        if fil is None:
            fil = self.grid.recno()

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

        # Datos
        liGen = [(None, None)]

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

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

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

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

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

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

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

        self.resultado = (self.listaAperturasStd, self.ficheroDatos, self.lista, fil, jugamos, repeticiones)
        self.accept()
Exemple #18
0
    def finalEntrenamiento(self):
        liHisto = self.db["HISTO"]
        if not liHisto:
            liHisto = []
            dicActual = {"FINICIAL": Util.hoy(), "FFINAL": None, "SECONDS": 0.0, "POS": self.numPosiciones(),
                         "ERRORS": 0}
            liHisto.insert(0, dicActual)
        liHisto[0]["FFINAL"] = Util.hoy()
        liHisto[0]["SECONDS"] = self.db["SECONDS"]
        liHisto[0]["ERRORS"] = self.db["ERRORS"]
        liHisto[0]["REFERENCE"] = self.db["REFERENCE"]

        self.db["HISTO"] = liHisto
        self.db["POSACTIVE"] = None
Exemple #19
0
 def listaTraducciones(self):
     li = []
     dlang = "Locale"
     for uno in Util.listdir(dlang):
         fini = os.path.join(dlang, uno, "lang.ini")
         if os.path.isfile(fini):
             try:
                 dic = Util.iniBase8dic(fini)
                 if "NAME" in dic:
                     li.append((uno, dic["NAME"], dic.get( "%", "100")))
             except:
                 pass
     li = sorted(li, key=lambda lng: lng[0])
     return li
Exemple #20
0
    def guardarVideo(self):
        dic = {}

        pos = self.pos()
        dic["_POSICION_"] = "%d,%d" % (pos.x(), pos.y())

        tam = self.size()
        dic["_SIZE_"] = "%d,%d" % (tam.width(), tam.height())

        dic["SHOW_TABLERO"] = self.siShowTablero
        dic["NARROWS"] = self.nArrows

        dic["SITOP"] = self.siTop

        Util.guardaDIC(dic, self.ficheroVideo)
 def gridDato(self, grid, fila, oColumna):
     col = oColumna.clave
     key = self.liHistorico[fila]
     reg = self.historico[key]
     if col == "FECHA":
         fecha = reg[col]
         return Util.localDate(fecha)
     elif col == "MPUNTOS":
         mpuntos = reg["MPUNTOS"]
         return "%0.2f" % mpuntos
     elif col == "MTIEMPOS":
         mtiempos = reg["MTIEMPOS"]
         return "%0.2f" % mtiempos
     elif col == "MOTOR":
         return reg["MOTOR"]
     elif col == "SEGUNDOS":
         tiempo = int(reg["TIEMPOJUGADA"] / 1000)
         return "%d" % tiempo
     elif col == "PRUEBAS":
         nfens = len(reg["LIFENS"])
         return "%d" % nfens
     elif col == "FNS":
         fns = reg.get("FNS", None)
         if fns:
             return os.path.basename(fns)
         else:
             return _("Default")
Exemple #22
0
 def gridDato(self, grid, fila, oColumna):
     col = oColumna.clave
     reg = self.historico[fila]
     if col == "FECHA":
         return Util.localDateT(reg.FECHA)
     elif col == "SEGUNDOS":
         return "%.02f" % reg.SEGUNDOS
    def empezar(self):
        liR = []
        if self.fns and Util.existeFichero(self.fns):
            fns = self.fns.lower()
            li = []
            if fns.endswith(".pgn"):
                f = open(fns, "rb")
                for linea in f:
                    if linea.startswith("[FEN "):
                        li.append(linea[6:].split('"')[0])
                f.close()
            else:  # se supone que es un fichero de fens
                f = open(fns, "rb")
                for linea in f:
                    linea = linea.strip()
                    if linea[0].isalnum() and \
                            linea[-1].isdigit() and \
                            ( (" w " in linea) or (" b " in linea) ) and \
                                    linea.count("/") == 7:
                        li.append(linea)
                f.close()
            if len(li) >= self.pruebas:
                liR = random.sample(li, self.pruebas)
            else:
                self.fns = ""

        if not liR:
            liR = PantallaPotencia.leeVariasLineasMFN(self.pruebas)

        # liR = liFens
        w = WDailyTest(self, liR, self.motor, self.segundos, self.fns)
        w.exec_()
        self.calcListaHistorico()
        self.ghistorico.refresh()
Exemple #24
0
 def grabar(self):
     if len(self.dicPtes) == 0:
         return
     dic = self.dicPtes
     self.dicPtes = {}
     # Creamos una tabla de trabajo
     dbf = SQLDBF.DBF(self.conexion, self.tablaDatos, "")
     for k, uno in dic.items():
         reg = SQLDBF.Almacen()
         reg.XPV = uno.xpv()
         reg.PV = uno.pv()
         reg.NAG = uno.nag()
         reg.ADV = uno.adv()
         reg.COMMENT = uno.comment()
         reg.POS = uno.pos()
         reg.FEN = uno.fen()
         reg.MARK = uno.mark()
         reg.GRAPHICS = uno.graphics()
         reg.XDATA = Util.var2blob(uno.xdata())
         if uno.rowid() is None:
             id = dbf.insertarSoloReg(reg)
             uno.rowid(id)
         else:
             dbf.modificarROWID(uno.rowid(), reg)
     dbf.cerrar()
Exemple #25
0
    def importar(self):
        # import os
        # ntema = 0
        # self.liTemas = []
        # for carpeta in ("1","a","b"):
        # sc = 1
        # ps = 0
        # for fich in os.listdir("/tmp/rp/%s"%carpeta):
        # tema = Util.recuperaVar( "/tmp/rp/%s/%s"%(carpeta,fich) )
        # tema["NOMBRE"] = fich[:-9]
        # tema["SECCION"] = "%s-%d"%(carpeta,sc)
        # ps += 1
        # if ps == 12:
        # ps =0
        # sc += 1
        # self.ponTema(tema)
        # self.confTablero.png64Thumb( base64.b64encode(self.tablero.thumbnail(64)) )
        # tema["TEXTO"] = self.confTablero.grabaTema()
        # tema["BASE"] = self.confTablero.grabaBase()
        # self.liTemas.append(tema)
        # fichero = self.configuracion.ficheroTemas
        # Util.guardaVar( fichero, self.liTemas )
        dr = self.configuracion.leeVariables("PCOLORES")
        dirBase = dr["DIRBASE"] if dr else ""

        fich = QTUtil2.leeFichero(self, dirBase, "lktheme1")
        if fich:
            dr["DIRBASE"] = os.path.dirname(fich)
            self.configuracion.escVariables("PCOLORES", dr)
            tema = Util.recuperaVar(fich)
            self.ponTema(tema)
    def terminarTest(self):
        self.paraHumano()
        self.xtutor.terminar()

        t = 0
        for x in self.liPuntos:
            t += x
        mpuntos = t * 1.0 / self.nFens

        t = 0.0
        for x in self.liTiempos:
            t += x
        mtiempos = t * 1.0 / self.nFens

        hoy = Util.hoy()
        fecha = "%d%02d%02d" % ( hoy.year, hoy.month, hoy.day )
        datos = {}
        datos["FECHA"] = hoy
        datos["MOTOR"] = self.xtutor.clave
        datos["TIEMPOJUGADA"] = self.xtutor.motorTiempoJugada
        datos["LIFENS"] = self.liFens
        datos["LIPV"] = self.liPV
        datos["MPUNTOS"] = mpuntos
        datos["MTIEMPOS"] = mtiempos
        datos["FNS"] = self.fns

        self.historico[fecha] = datos

        self.lbColor.ponTexto("")
        self.lbJuego.ponTexto("")

        mens = "<h3>%s : %0.2f</h3><h3>%s : %0.2f</h3>" % (_("Points lost"), mpuntos, _("Time in seconds"), mtiempos )
        QTUtil2.mensaje(self, mens, _("Result"), siResalta=False)

        self.accept()
Exemple #27
0
    def limpia(self, nombre):
        self.elo = 0
        self.eloNC = 1600
        self.michelo = 1600
        self.micheloNC = 1600
        self.fics = 1200
        self.ficsNC = 1200
        self.fide = 1600
        self.fideNC = 1600
        self.grupos.limpia()
        self.id = Util.creaID()
        self.jugador = nombre
        self.dirSalvados = ""
        self.dirPGN = ""
        self.dirJS = ""
        self.liTrasteros = []

        self.salvarGanados = False
        self.salvarPerdidos = False
        self.salvarAbandonados = False
        self.salvarFichero = ""

        self.siActivarCapturas = False
        self.siActivarInformacion = False
        self.siAtajosRaton = False
        self.showCandidates = False

        self.salvarCSV = ""

        self.rival = self.buscaRival(self.rivalInicial)
Exemple #28
0
 def rutinaDatos(recno):
     dic = {}
     dbf.goto(recno)
     for clave in dbf.liCampos:
         dic[clave] = getattr(dbf.reg, clave)
     dic["PGN"] = Util.blob2var(dic["PGN"])
     return dic
Exemple #29
0
    def nuevo(self):
        wav = None
        nombre = ""
        while True:
            w = WEdicionSonido(self, _("New"), wav=wav, maxTime=600000, nombre=nombre)
            resp = w.exec_()
            if resp:
                centesimas = w.centesimas
                if not centesimas:
                    return
                nombre = w.nombre().strip()
                if not nombre:
                    QTUtil2.mensError(self, _("Name missing"))
                    continue

                reg = Util.Almacen()
                reg.nombre = nombre
                reg.centesimas = centesimas
                reg.id = Util.nuevoID()
                reg.wav = w.wav
                reg.ordenVista = (self.liSonidos[-1].ordenVista + 1) if self.liSonidos else 1
                self.db[reg.id] = reg
                self.liSonidos.append(reg)
                self.grid.refresh()
                return
Exemple #30
0
    def getNewName(self, title, previous=""):
        name = previous

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

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

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

            name = Util.validNomFichero(name)

            ok = True
            for k in self.bookGuide.getOtras():
                if k.lower() == name.lower():
                    QTUtil2.mensError(self, _("This name is repeated, please select other"))
                    ok = False
                    break
            if ok:
                return name
 def linea_bloque(self, pos):
     alm = Util.Almacen()
     alm.fen, alm.bm, alm.sol, alm.pgn, alm.dif = self.li_bloque[pos].split(
         "|")
     alm.max_time = (int(alm.dif)**2) * 5 + 120
     return alm
Exemple #32
0
    def genera(self):
        num = self.PUZZLES

        # Determinamos la lista de fens, teniendo en cuenta el peso asociado a cada fichero
        lif = []

        wt = 0
        for f, w, d, h in self.filesw:
            lif0 = []
            for fich in self.listaFicheros(f):
                q = codecs.open(fich, "r", "latin-1", 'ignore')
                for linea in q:
                    linea = linea.strip()
                    if linea and "|" in linea:
                        lif0.append(linea)
                q.close()
            if d and d <= h:
                d -= 1
                lif0 = lif0[d:h]
            lif.append([w, lif0])
            wt += w
        t = 0
        for li in lif:
            li[0] = int(li[0] * num / wt)
            t += li[0]
        t -= self.PUZZLES
        n = 0
        while t:
            lif[0][n] += 1
            t -= 1
            n += 1
            if n == len(lif):
                n = 0

        liFNS = []
        for li in lif:
            n = li[0]
            lif0 = li[1]
            if len(lif0) < n:
                n = len(lif0)
            lir = lif0[:n]
            for x in lir:
                liFNS.append(x)

        self.db["LIFNS"] = liFNS
        self.liFNS = liFNS

        numPuzzles = len(liFNS)

        # Deteminamos la lista indice con el orden de cada fen en liFNS
        liJUMPS = self.JUMPS

        li = [None] * (len(liJUMPS) * 2 * numPuzzles)  # Creamos un list muy grande, mayor del que vamos a usar

        def busca(desde, salto):
            if salto == 0:
                for x in range(desde, len(li)):
                    if li[x] is None:
                        return x
                li.extend([None] * 1000)
                return busca(desde, salto)
            else:
                while salto:
                    desde = busca(desde + 1, 0)
                    salto -= 1
                return desde

        for x in range(numPuzzles):
            n = busca(0, 0)
            li[n] = x
            for m in liJUMPS:
                n = busca(n + 1, int(m))
                li[n] = x

        liBase = []
        for x in li:
            if x is not None:
                liBase.append(x)

        liOrder = []

        liNueva = liBase[:]
        for repeat in self.REPEAT:
            if repeat == 0:  # Original
                liNueva = liBase[:]
            elif repeat == 1:
                liNueva = liBase[:]
                random.shuffle(liNueva)
            else:
                liNueva = liNueva[:]
            liOrder.extend(liNueva)

        self.db["ORDER"] = liOrder
        self.liOrder = liOrder

        self.db["POSACTIVE"] = 0

        self.db["SHOWTEXT"] = self.SHOWTEXT

        self.db["POINTVIEW"] = self.POINTVIEW

        self.db["REFERENCE"] = self.REFERENCE

        # 6.3d---------------+
        liHisto = self.db["HISTO"]
        if not liHisto:
            liHisto = []
        dicActual = {"FINICIAL": Util.hoy(), "FFINAL": None, "SECONDS": 0.0, "POS": self.numPosiciones(), "ERRORS": 0,
                     "PUZZLES": self.PUZZLES, "FILESW": self.filesw, "JUMPS": self.JUMPS, "REPEAT": self.REPEAT,
                     "SHOWTEXT": self.SHOWTEXT, "PENALIZATION": self.PENALIZATION}
        liHisto.insert(0, dicActual)
        self.db["HISTO"] = liHisto
        #6.3d---------------+

        #7.0---------------+
        self.db["SECONDS"] = 0.0
        self.db["ERRORS"] = 0
        #7.0---------------+

        self.db.pack()
 def read(self):
     obj = Util.restore_pickle(self.file)
     return [] if obj is None else obj
    def __init__(self, user):

        self.carpetaBase = active_folder()

        self.carpetaUsers = os.path.join(self.carpetaBase, "users")

        if user:
            Util.create_folder(self.carpetaUsers)
            self.carpeta = os.path.join(self.carpetaUsers, str(user.number))
            Util.create_folder(self.carpeta)
        else:
            Util.create_folder(self.carpetaBase)
            self.carpeta = self.carpetaBase

        self.carpeta_config = os.path.join(self.carpeta, "__Config__")
        Util.create_folder(self.carpeta_config)

        self.carpeta_results = os.path.join(self.carpeta, "Results")
        Util.create_folder(self.carpeta_results)

        self.user = user
        self.set_folders()

        self.is_main = user == "" or user is None

        self.version = ""

        self.x_id = Util.new_id()
        self.x_player = ""
        self.x_save_folder = ""
        self.x_save_pgn_folder = ""
        self.x_save_lcsb = ""
        self.x_translator = ""
        self.x_style = "WindowsVista"
        self.x_tutor_view = POS_TUTOR_HORIZONTAL

        self.x_show_effects = False
        self.x_pieces_speed = 100
        self.x_save_tutor_variations = True

        self.x_mouse_shortcuts = False
        self.x_show_candidates = False

        self.x_captures_activate = True
        self.x_info_activate = False

        self.x_default_tutor_active = True

        self.x_elo = 0
        self.x_michelo = 1600
        self.x_fics = 1200
        self.x_fide = 1600
        self.x_lichess = 1600

        self.x_digital_board = ""

        self.x_menu_play = MENU_PLAY_BOTH

        self.x_opacity_tool_board = 10
        self.x_position_tool_board = "T"

        self.x_director_icon = False
        self.x_direct_graphics = False

        self.colores_nags_defecto()

        self.x_sizefont_infolabels = 10

        self.x_pgn_selbackground = None
        self.x_pgn_headerbackground = None

        self.x_pgn_width = 400
        self.x_pgn_fontpoints = 11
        self.x_pgn_rowheight = 28
        self.x_pgn_withfigurines = True

        self.x_pgn_english = False

        self.x_autopromotion_q = False

        self.x_font_family = ""

        self.x_menu_points = 11
        self.x_menu_bold = False

        self.x_tb_fontpoints = 11
        self.x_tb_bold = False
        self.x_tb_icons = toolbutton_int(Qt.ToolButtonTextUnderIcon)

        self.x_cursor_thinking = True

        self.x_save_won = False
        self.x_save_lost = False
        self.x_save_unfinished = False

        self.x_save_csv = ""
        self.x_save_pgn = ""

        self.x_rival_inicial = "rocinante" if Code.is_linux else "irina"

        self.tutor_inicial = "stockfish"
        self.x_tutor_clave = self.tutor_inicial
        self.x_tutor_multipv = 10  # 0: maximo
        self.x_tutor_difpoints = 10
        self.x_tutor_difporc = 0
        self.x_tutor_mstime = 3000
        self.x_tutor_depth = 0

        self.x_sound_beep = False
        self.x_sound_our = False
        self.x_sound_move = False
        self.x_sound_results = False

        self.x_interval_replay = 1400

        self.x_engine_notbackground = False

        self.x_check_for_update = False

        self.x_carpeta_gaviota = self.carpeta_gaviota_defecto()

        # Editable directamente en su código
        self.x_captures_showall = True
        self.x_counts_showall = True

        self.palette = {}

        self.perfomance = Perfomance()

        self.li_favoritos = None

        self.liPersonalidades = []

        self.relee_engines()

        self.rival = self.buscaRival(self.x_rival_inicial)
        self.tutor = self.buscaTutor(self.tutor_inicial)
        if self.tutor.key != self.x_tutor_clave:
            self.x_tutor_clave = self.tutor.key
Exemple #35
0
    def base_inicio(self, dic_var):
        self.reinicio = dic_var

        self.cache = dic_var.get("cache", {})

        self.game_type = GT_AGAINST_ENGINE

        self.human_is_playing = False
        self.plays_instead_of_me_option = True
        self.state = ST_PLAYING
        self.is_analyzing = False

        self.summary = {
        }  # numJugada : "a"ccepted, "s"ame, "r"ejected, dif points, time used
        self.with_summary = dic_var.get("SUMMARY", False)

        is_white = dic_var["ISWHITE"]
        self.human_side = is_white
        self.is_engine_side_white = not is_white

        self.conf_engine = dic_var["RIVAL"].get("CM", None)

        self.lirm_engine = []
        self.next_test_resign = 0
        self.resign_limit = -99999  # never

        self.aperturaObl = self.aperturaStd = None

        self.fen = dic_var["FEN"]
        if self.fen:
            cp = Position.Position()
            cp.read_fen(self.fen)
            self.game.set_position(cp)
            self.game.pending_opening = False
        else:
            if dic_var["OPENING"]:
                self.aperturaObl = Opening.JuegaOpening(
                    dic_var["OPENING"].a1h8)
                self.primeroBook = False  # la opening es obligatoria

        self.bookR = dic_var.get("BOOKR", None)
        if self.bookR:
            self.bookRdepth = dic_var.get("BOOKRDEPTH", 0)
            self.bookR.polyglot()
            self.bookRR = dic_var.get("BOOKRR", "mp")
        elif dic_var["RIVAL"].get("TYPE", None) in (SelectEngines.MICGM,
                                                    SelectEngines.MICPER):
            if self.conf_engine.book:
                self.bookR = Books.Book("P", self.conf_engine.book,
                                        self.conf_engine.book, True)
                self.bookR.polyglot()
                self.bookRR = "mp"
                self.bookRdepth = 0

        self.bookP = dic_var.get("BOOKP", None)
        if self.bookP:
            self.bookPdepth = dic_var.get("BOOKPDEPTH", 0)
            self.bookP.polyglot()

        self.is_tutor_enabled = (
            Code.dgtDispatch is
            None) and self.configuration.x_default_tutor_active
        self.main_window.set_activate_tutor(self.is_tutor_enabled)

        self.hints = dic_var["HINTS"]
        self.ayudas_iniciales = self.hints  # Se guarda para guardar el PGN
        self.nArrows = dic_var.get("ARROWS", 0)
        n_box_height = dic_var.get("BOXHEIGHT", 24)
        self.thoughtOp = dic_var.get("THOUGHTOP", -1)
        self.thoughtTt = dic_var.get("THOUGHTTT", -1)
        self.continueTt = dic_var.get("CONTINUETT", False)
        self.nArrowsTt = dic_var.get("ARROWSTT", 0)
        self.chance = dic_var.get("2CHANCE", True)

        if self.nArrowsTt != 0 and self.hints == 0:
            self.nArrowsTt = 0

        self.with_takeback = dic_var.get("TAKEBACK", True)

        self.tutor_con_flechas = self.nArrowsTt > 0 and self.hints > 0
        self.tutor_book = Books.BookGame(Code.tbook)

        mx = max(self.thoughtOp, self.thoughtTt)
        if mx > -1:
            self.set_hight_label3(n_box_height)

        dr = dic_var["RIVAL"]
        rival = dr["CM"]

        if dr["TYPE"] == SelectEngines.ELO:
            r_t = 0
            r_p = rival.fixed_depth
            self.nAjustarFuerza = ADJUST_BETTER

        else:
            r_t = dr["ENGINE_TIME"] * 100  # Se guarda en decimas -> milesimas
            r_p = dr["ENGINE_DEPTH"]
            self.nAjustarFuerza = dic_var.get("ADJUST", ADJUST_BETTER)

        if not self.xrival:  # reiniciando is not None
            if r_t <= 0:
                r_t = None
            if r_p <= 0:
                r_p = None
            if r_t is None and r_p is None and not dic_var["WITHTIME"]:
                r_t = 1000
            self.xrival = self.procesador.creaManagerMotor(
                rival, r_t, r_p, self.nAjustarFuerza != ADJUST_BETTER)
            if self.nAjustarFuerza != ADJUST_BETTER:
                self.xrival.maximizaMultiPV()
        self.resign_limit = dic_var["RESIGN"]

        self.game.add_tag("Event", _("Play against an engine"))

        player = self.configuration.nom_player()
        other = self.xrival.name
        w, b = (player, other) if self.human_side else (other, player)
        self.game.add_tag("White", w)
        self.game.add_tag("Black", b)

        self.siBookAjustarFuerza = self.nAjustarFuerza != ADJUST_BETTER

        self.xrival.is_white = self.is_engine_side_white

        self.siTiempo = dic_var["WITHTIME"]
        if self.siTiempo:
            self.maxSegundos = dic_var["MINUTES"] * 60.0
            self.segundosJugada = dic_var["SECONDS"]
            self.segExtra = dic_var.get("MINEXTRA", 0) * 60.0
            self.zeitnot = dic_var.get("ZEITNOT", 0)

            self.vtime = {
                WHITE: Util.Timer(self.maxSegundos),
                BLACK: Util.Timer(self.maxSegundos)
            }
            if self.segExtra:
                self.vtime[self.human_side].ponSegExtra(self.segExtra)

            time_control = "%d" % int(self.maxSegundos)
            if self.segundosJugada:
                time_control += "+%d" % self.segundosJugada
            self.game.add_tag("TimeControl", time_control)
            if self.segExtra:
                self.game.add_tag(
                    "TimeExtra" + "White" if self.human_side else "Black",
                    "%d" % self.segExtra)

        self.pon_toolbar()

        self.main_window.activaJuego(True, self.siTiempo)

        self.set_dispatcher(self.player_has_moved)
        self.set_position(self.game.last_position)
        self.show_side_indicator(True)
        if self.ayudas_iniciales:
            self.ponAyudasEM()
        else:
            self.remove_hints(siQuitarAtras=False)
        self.put_pieces_bottom(is_white)

        self.ponRotuloBasico()
        self.set_label2("")

        if self.nAjustarFuerza != ADJUST_BETTER:
            pers = Personalities.Personalities(None, self.configuration)
            label = pers.label(self.nAjustarFuerza)
            if label:
                self.game.add_tag("Strength", label)

        self.ponCapInfoPorDefecto()

        self.pgnRefresh(True)

        rival = self.xrival.name
        player = self.configuration.x_player
        bl, ng = player, rival
        if self.is_engine_side_white:
            bl, ng = ng, bl

        active_clock = max(self.thoughtOp, self.thoughtTt) > -1

        if self.siTiempo:
            tp_bl = self.vtime[True].etiqueta()
            tp_ng = self.vtime[False].etiqueta()
            self.main_window.ponDatosReloj(bl, tp_bl, ng, tp_ng)
            active_clock = True
            self.refresh()
        else:
            self.main_window.base.change_player_labels(bl, ng)

        if active_clock:
            self.main_window.start_clock(self.set_clock, 400)

        self.main_window.set_notify(self.mueve_rival_base)

        self.is_analyzed_by_tutor = False

        self.game.tag_timestart()

        self.check_boards_setposition()
Exemple #36
0
 def leeRegAllRecno(self, recno):
     raw = self.leeAllRecno(recno)
     alm = Util.Almacen()
     for campo in self.liCamposAll:
         setattr(alm, campo, raw[campo])
     return alm, raw
Exemple #37
0
    def procesa_game(self):
        self.pon_estado(ST_PLAYING)

        # Configuración
        self.fen_inicial = self.torneo.fenNorman()

        # Cerramos los motores anteriores si los hay
        Code.list_engine_managers.close_all()

        if self.torneo.adjudicator_active():
            conf_engine = Code.configuration.buscaRival(
                self.torneo.adjudicator())
            self.xadjudicator = EngineManager.EngineManager(self, conf_engine)
            self.xadjudicator.options(self.torneo.adjudicator_time() * 1000, 0,
                                      False)
            self.xadjudicator.remove_multipv()
        else:
            self.xadjudicator = None
        self.next_control = 0

        self.max_segundos = self.tournament_game.minutos * 60.0
        self.segundos_jugada = self.tournament_game.segundos_jugada

        # abrimos motores
        rival = {
            WHITE: self.torneo.buscaHEngine(self.tournament_game.hwhite),
            BLACK: self.torneo.buscaHEngine(self.tournament_game.hblack)
        }
        for side in (WHITE, BLACK):
            self.lb_player[side].set_text(rival[side].key)

        self.vtime = {}

        self.book = {}
        self.bookRR = {}

        self.xengine = {}

        for side in (WHITE, BLACK):
            rv = rival[side]
            self.xengine[side] = EngineManager.EngineManager(self, rv)
            self.xengine[side].options(rv.time * 1000, rv.depth, False)
            self.xengine[side].set_gui_dispatch(self.gui_dispatch)

            self.vtime[side] = Util.Timer(self.max_segundos)

            bk = rv.book
            if bk == "*":
                bk = self.torneo.book()
            if bk == "-":  # Puede que el torneo tenga "-"
                bk = None
            if bk:
                self.book[side] = Books.Book("P", bk, bk, True)
                self.book[side].polyglot()
            else:
                self.book[side] = None
            self.bookRR[side] = rv.bookRR

        self.game = Game.Game(fen=self.fen_inicial)
        self.pgn.game = self.game

        self.lbRotulo3.altoFijo(32)

        self.board.disable_all()
        self.board.set_position(self.game.last_position)
        self.grid_pgn.refresh()

        for side in (WHITE, BLACK):
            ot = self.vtime[side]
            eti, eti2 = ot.etiquetaDif2()
            self.pon_reloj_side(side, eti, eti2)

        while self.state == ST_PAUSE or self.play_next_move():
            if self.state == ST_PAUSE:
                QTUtil.refresh_gui()
                time.sleep(0.1)
            if self.is_closed:
                break
        for side in (WHITE, BLACK):
            self.xengine[side].terminar()

        if not self.is_closed:
            if self.game_finished():
                self.save_game_done()
Exemple #38
0
    def inicio(self, datosMotor, minutos, segundos, siCompetitivo, aplazamiento=None):

        self.tipoJuego = kJugMicElo

        self.resultado = None
        self.siJuegaHumano = False
        self.estado = kJugando
        self.siCompetitivo = siCompetitivo
        self.puestoResultado = False # Problema doble asignacion de ptos Thomas

        if aplazamiento:
            siBlancas = aplazamiento["SIBLANCAS"]
        else:
            siBlancas = self.determinaColor(datosMotor)

        self.siJugamosConBlancas = siBlancas
        self.siRivalConBlancas = not siBlancas

        self.rmRival = None
        self.liRMrival = []
        self.noMolestar = 0
        self.resignPTS = -1000

        self.siTutorActivado = False
        self.pantalla.ponActivarTutor(False)
        self.ayudasPGN = self.ayudas = 0

        self.tiempo = {}
        self.maxSegundos = minutos * 60
        self.segundosJugada = segundos

        # -Aplazamiento 1/2--------------------------------------------------
        if aplazamiento:
            self.partida.recuperaDeTexto(aplazamiento["JUGADAS"])

            self.datosMotor = self.engineAplazado(aplazamiento["ALIAS"], aplazamiento["BASEELO"])

            self.tiempo[True] = Util.Timer(aplazamiento["TIEMPOBLANCAS"])
            self.tiempo[False] = Util.Timer(aplazamiento["TIEMPONEGRAS"])

            self.maxSegundos = aplazamiento["MAXSEGUNDOS"]
            self.segundosJugada = aplazamiento["SEGUNDOSJUGADA"]

            self.partida.asignaApertura()

        else:
            self.datosMotor = datosMotor
            self.tiempo[True] = Util.Timer(self.maxSegundos)
            self.tiempo[False] = Util.Timer(self.maxSegundos)

        cbook = self.datosMotor.book if self.datosMotor.book else VarGen.tbook
        self.book = Books.Libro("P", cbook, cbook, True)
        self.book.polyglot()

        elo = self.datosMotor.elo
        self.maxMoveBook = elo / 200 if 0 <= elo <= 1700 else 9999

        eloengine = self.datosMotor.elo
        eloplayer = self.configuracion.miceloActivo(siCompetitivo)
        self.whiteElo = eloplayer if siBlancas else eloengine
        self.blackElo = eloplayer if not siBlancas else eloengine

        self.xrival = self.procesador.creaGestorMotor(self.datosMotor, None, None,
                                                      siMultiPV=self.datosMotor.multiPV > 0)

        self.pteToolRendirse = False
        if not self.siCompetitivo:
            self.pteToolRendirse = True
            self.maxPlyRendirse = 6
        elif self.siJugamosConBlancas:
            self.pteToolRendirse = True
            self.maxPlyRendirse = 1
        else:
            self.maxPlyRendirse = 0

        if aplazamiento and self.partida.numJugadas() > self.maxPlyRendirse:
            self.pteToolRendirse = False

        self.ponToolBar()

        self.pantalla.activaJuego(True, True, siAyudas=False)
        self.ponMensajero(self.mueveHumano)
        self.ponPosicion(self.partida.ultPosicion)
        self.ponPiezasAbajo(siBlancas)
        self.quitaAyudas(True, siQuitarAtras=siCompetitivo)
        self.mostrarIndicador(True)

        nbsp = "&nbsp;" * 3

        txt = "%s:%+d%s%s:%+d%s%s:%+d" % (_("Win"), self.datosMotor.pgana, nbsp,
                                          _("Draw"), self.datosMotor.ptablas, nbsp,
                                          _("Loss"), self.datosMotor.ppierde)
        self.ponRotulo1("<center>%s</center>" % txt)
        self.ponRotulo2("")
        self.pgnRefresh(True)
        self.ponCapInfoPorDefecto()

        # -Aplazamiento 2/2--------------------------------------------------
        if aplazamiento:
            self.mueveJugada(kMoverFinal)
            self.siPrimeraJugadaHecha = True
        else:
            self.siPrimeraJugadaHecha = False

        tpBL = self.tiempo[True].etiqueta()
        tpNG = self.tiempo[False].etiqueta()
        self.rival = rival = self.datosMotor.alias + " (%d)" % self.datosMotor.elo
        jugador = self.configuracion.jugador + " (%d)" % self.configuracion.miceloActivo(siCompetitivo)
        bl, ng = jugador, rival
        if self.siRivalConBlancas:
            bl, ng = ng, bl
        self.pantalla.ponDatosReloj(bl, tpBL, ng, tpNG)
        self.refresh()

        self.ponPosicionDGT()

        if not self.siJugamosConBlancas:
            mensaje = _("Press the continue button to start.")
            self.mensajeEnPGN(mensaje)

        self.siguienteJugada()
Exemple #39
0
    def inicio(self, dic, aplazamiento=None, siPrimeraJugadaHecha=False):
        if aplazamiento:
            dic = aplazamiento["EMDIC"]
        self.reinicio = dic

        self.tipoJuego = kJugEntMaq

        self.resultado = None
        self.siJuegaHumano = False
        self.estado = kJugando
        self.timekeeper = Util.Timekeeper()

        self.summary = {}
        self.siSummary = dic.get("SUMMARY", False)

        siBlancas = dic["SIBLANCAS"]
        self.siJugamosConBlancas = siBlancas
        self.siRivalConBlancas = not siBlancas

        self.siAtras = True

        self.rmRival = None
        self.liRMrival = []

        self.aperturaStd = Apertura.AperturaPol(1)

        self.pensando(True)

        self.pantalla.ponActivarTutor(False)

        self.ayudas = 0
        self.ayudasPGN = 0

        cmrival = self.configuracion.buscaRival("irina", None)
        self.xrival = self.procesador.creaGestorMotor(cmrival, None, 2)
        self.rival_name = dic["RIVAL"]
        self.xrival.set_option("Personality", self.rival_name)
        if not dic["FASTMOVES"]:
            self.xrival.set_option("Max Time", "5")
            self.xrival.set_option("Min Time", "1")
        self.xrival.nombre = _F(self.rival_name)

        self.xrival.siBlancas = self.siRivalConBlancas

        self.siPrimeraJugadaHecha = siPrimeraJugadaHecha

        self.siTiempo = dic["SITIEMPO"]
        if self.siTiempo:
            self.maxSegundos = dic["MINUTOS"] * 60.0
            self.segundosJugada = dic["SEGUNDOS"]
            self.segExtra = dic.get("MINEXTRA", 0) * 60.0

            self.tiempo = {}
            self.tiempo[True] = Util.Timer(self.maxSegundos)
            self.tiempo[False] = Util.Timer(self.maxSegundos)

        self.pensando(False)

        # -Aplazamiento 1/2--------------------------------------------------
        if aplazamiento:
            self.partida.recuperaDeTexto(aplazamiento["JUGADAS"])
            self.partida.pendienteApertura = aplazamiento["PENDIENTEAPERTURA"]
            self.partida.apertura = None if aplazamiento["APERTURA"] is None else self.listaAperturasStd.dic[
                aplazamiento["APERTURA"]]

            self.siTiempo = aplazamiento["SITIEMPO"]
            if self.siTiempo:
                self.maxSegundos = aplazamiento["MAXSEGUNDOS"]
                self.segundosJugada = aplazamiento["SEGUNDOSJUGADA"]

                self.tiempo = {}
                self.tiempo[True] = Util.Timer(aplazamiento["TIEMPOBLANCAS"])
                self.tiempo[False] = Util.Timer(aplazamiento["TIEMPONEGRAS"])
                if self.segExtra:
                    self.tiempo[self.siJugamosConBlancas].ponSegExtra(self.segExtra)

                self.siPrimeraJugadaHecha = False

        li = [k_cancelar, k_rendirse, k_atras, k_reiniciar, k_aplazar, k_peliculaPausa, k_configurar, k_utilidades]
        self.pantalla.ponToolBar(li)

        self.pantalla.activaJuego(True, self.siTiempo)

        self.ponMensajero(self.mueveHumano)
        self.ponPosicion(self.partida.ultPosicion)
        self.mostrarIndicador(True)
        self.quitaAyudas(True, siQuitarAtras=False)
        self.ponPiezasAbajo(siBlancas)

        imagen = getattr(Iconos, "pm%s" % self.rival_name)

        self.pantalla.base.lbRotulo1.ponImagen(imagen())
        self.pantalla.base.lbRotulo1.show()

        self.ponCapInfoPorDefecto()

        self.pgnRefresh(True)

        # -Aplazamiento 2/2--------------------------------------------------
        if aplazamiento or "MOVE" in dic:
            self.mueveJugada(kMoverFinal)

        if self.siTiempo:
            self.siPrimeraJugadaHecha = False
            tpBL = self.tiempo[True].etiqueta()
            tpNG = self.tiempo[False].etiqueta()
            jugador = self.configuracion.jugador
            bl, ng = jugador, self.rival_name
            if self.siRivalConBlancas:
                bl, ng = ng, bl
            self.pantalla.ponDatosReloj(bl, tpBL, ng, tpNG)
            self.refresh()

        self.ponPosicionDGT()

        self.siguienteJugada()
 def nuevaCopia(self, ntarea):
     tarea = copy.copy(self.tarea(ntarea))
     tarea._id = Util.str_id()
     return self.nuevaTarea(tarea, ntarea + 1)
 def setFichero(self, file):
     self.close()
     self._fichero = file if file is not None else Code.configuration.ficheroRecursos
     if not Util.exist_file(self._fichero):
         Util.file_copy(Code.path_resource("IntFiles", "recursos.dbl"),
                        self._fichero)
    def inicio(self, dbwashing, washing, engine):
        self.dbwashing = dbwashing
        self.washing = washing

        self.engine = engine

        self.tipoJuego = kJugWashingCreate

        self.resultado = None
        self.siJuegaHumano = False
        self.estado = kJugando
        self.timekeeper = Util.Timekeeper()

        siBlancas = self.engine.color
        self.siJugamosConBlancas = siBlancas
        self.siRivalConBlancas = not siBlancas
        self.siCompetitivo = True

        self.apertura = Apertura.AperturaPol(30, self.engine.elo)

        self.siTutorActivado = True
        self.siAnalizando = False
        # self.pantalla.ponActivarTutor(self.siTutorActivado)

        rival = self.configuracion.buscaRival(self.engine.clave)

        self.xrival = self.procesador.creaGestorMotor(rival, None, None)
        self.xrival.siBlancas = self.siRivalConBlancas
        self.rmRival = None
        self.tmRival = 15.0 * 60.0 * engine.elo / 3000.0

        self.xtutor.maximizaMultiPV()
        self.siAnalizadoTutor = False

        self.pantalla.activaJuego(True, False, False)
        self.quitaAyudas()
        li = [k_mainmenu, k_reiniciar, k_atras]
        self.pantalla.ponToolBar(li)
        self.ponMensajero(self.mueveHumano)
        self.ponPosicion(self.partida.ultPosicion)
        self.mostrarIndicador(True)
        self.ponPiezasAbajo(siBlancas)

        self.ponRotulo1(
            "%s: %s\n%s: %s\n %s: %s" %
            (_("Rival"), self.engine.nombre, _("Task"), self.engine.lbState(),
             _("Tutor"), self.xtutor.nombre))
        self.ponRotuloDatos()

        self.ponCapInfoPorDefecto()

        self.pgnRefresh(True)

        game = dbwashing.restoreGame(engine)
        if game:
            if not game.siTerminada():
                self.partida = game
                self.ponteAlFinal()
                self.pantalla.base.pgnRefresh()

        self.ponPosicionDGT()

        self.siguienteJugada()
Exemple #43
0
    def aceptar(self):
        if not self.fichero:
            return

        # Creamos el pgn
        fichTemporal = self.wParent.damePGNtemporal(self)
        if not fichTemporal:
            return

        me = QTUtil2.unMomento(self)

        # Creamos la linea de ordenes
        if VarGen.isWindows:
            exe = 'Engines/Windows/_tools/polyglot/polyglot.exe'
        else:
            exe = 'Engines/Linux/_tools/polyglot/polyglot'
        li = [
            os.path.abspath(exe), 'make-book', "-pgn", fichTemporal, "-bin",
            self.fichero
        ]
        Util.borraFichero(self.fichero)

        maxPly = self.sbMaxPly.valor()
        minGame = self.sbMinGame.valor()
        minScore = self.sbMinScore.valor()
        onlyWhite = self.chbOnlyWhite.valor()
        onlyBlack = self.chbOnlyBlack.valor()
        uniform = self.chbUniform.valor()
        if maxPly:
            li.append("-max-ply")
            li.append("%d" % maxPly)
        if minGame and minGame != 3:
            li.append("-min-game")
            li.append("%d" % minGame)
        if minScore:
            li.append("-min-score")
            li.append("%d" % minScore)
        if onlyBlack:
            li.append("-only-black")
        if onlyWhite:
            li.append("-only-white")
        if uniform:
            li.append("-uniform")

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

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

        Util.borraFichero(fichTemporal)

        nombre = os.path.basename(self.fichero)[:-4]
        b = Books.Libro("P", nombre, self.fichero, False)
        self.listaLibros.nuevo(b)
        fvar = self.configuracion.ficheroBooks
        self.listaLibros.guardaVar(fvar)

        self.accept()
Exemple #44
0
    def menu_run(self, resp):
        if resp:
            if type(resp) == str:
                if resp == "gm":
                    self.entrenaGM()

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

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

                elif resp.startswith("resistance"):
                    self.resistance(resp[10:])

                elif resp in ["find_all_moves_rival", "find_all_moves_player"]:
                    self.find_all_moves(resp == "find_all_moves_player")

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

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

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

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

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

                elif resp == "endings_gtb":
                    self.gaviota_endings()

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

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

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

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

                elif resp.startswith("ep_"):
                    um = self.procesador.unMomento()
                    entreno = os.path.realpath(resp[3:])
                    titentreno = Util.relative_path(entreno, Code.folder_root)
                    # if "/" in entreno:
                    #     dicTraining = TrListas.dicTraining()
                    #     titentreno = ""
                    #     for x in entreno[:-4].split("/")[1:]:
                    #         titentreno += dicTraining.get(x, x) + "/"
                    #     titentreno = titentreno[:-1]
                    with Util.OpenCodec(entreno) as f:
                        todo = f.read().strip()
                    liEntrenamientos = todo.split("\n")
                    nPosiciones = len(liEntrenamientos)
                    um.final()
                    if nPosiciones == 0:
                        return
                    elif nPosiciones == 1:
                        pos = 1
                        jump = False
                    else:
                        db = UtilSQL.DictSQL(self.configuration.ficheroTrainings)
                        data = db[entreno]
                        jump = False
                        tipo = "s"
                        if data is None:
                            posUltimo = 1
                        elif type(data) == int:
                            posUltimo = data
                        else:
                            posUltimo = data["POSULTIMO"]
                            jump = data["SALTA"]
                            tipo = data["TYPE"]
                        resp = WCompetitionWithTutor.numPosicion(
                            self.procesador.main_window, titentreno, nPosiciones, posUltimo, jump, tipo
                        )
                        if resp is None:
                            db.close()
                            return
                        pos, tipo, jump = resp
                        db[entreno] = {"POSULTIMO": pos, "SALTA": jump, "TYPE": tipo}
                        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 == "playGame":
                    self.procesador.play_game()

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

                elif resp == "transsiberian":
                    self.procesador.showRoute()

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

                elif resp.startswith("tol_"):
                    self.turn_on_lights(resp[4:])

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

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

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

                elif resp == "15mate":
                    self.mate15()

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

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

            else:
                if resp <= -100:
                    self.menu = None  # ya que puede cambiar y la etiqueta es diferente
                    mem = Memory.Memoria(self.procesador)
                    mem.lanza(abs(resp) - 100)
Exemple #45
0
 def recuperaDIC(self):
     return Util.recuperaVar(self.configuracion.ficheroTrainBooks)
 def carpeta_gaviota_defecto(self):
     return Util.relative_path(Code.path_resource("Gaviota"))
Exemple #47
0
 def save(self):
     dicW = {}
     dicW["CURRENT"] = self.current
     dicW["DIC"] = {iso: reg._save() for iso, reg in self.dic.iteritems()}
     return Util.var2blob(dicW)
Exemple #48
0
 def reset(self, depth=None):
     self.close()
     Util.borraFichero(self.nomFichero)
     self._conexion = sqlite3.connect(self.nomFichero)
     self.depth, self.riniFen = self.checkTable(depth)
     self.cursor = self._conexion.cursor()
Exemple #49
0
    def create_menu_tactics(self, menu, xopcion):
        menu.separador()
        menu_tactics = menu.submenu(_("Tactics"), Iconos.Training_Tactics())

        #   Posiciones de entrenamiento --------------------------------------------------------------------------
        self.menuFNS(menu_tactics, _("Training positions"), xopcion)
        menu_tactics.separador()

        # Tacticas ---------------------------------------------------------------------------------------------
        menu_t = menu_tactics.submenu(_("Learn tactics by repetition"), Iconos.Tacticas())
        nico = Util.Rondo(Iconos.Amarillo(), Iconos.Naranja(), Iconos.Verde(), Iconos.Azul(), Iconos.Magenta())
        dicTraining = TrListas.dicTraining()

        def trTraining(txt):
            return dicTraining.get(txt, txt)

        def menu_tacticas(submenu, tipo, carpeta_base, lista):
            if os.path.isdir(carpeta_base):
                for entry in os.scandir(carpeta_base):
                    if entry.is_dir():
                        carpeta = entry.path
                        ini = os.path.join(carpeta, "Config.ini")
                        if os.path.isfile(ini):
                            name = entry.name
                            xopcion(
                                submenu,
                                "tactica|%s|%s|%s|%s" % (tipo, name, carpeta, ini),
                                trTraining(name),
                                nico.otro(),
                            )
                            menu_t.separador()
                            lista.append((carpeta, name))
                        else:
                            submenu1 = submenu.submenu(entry.name, nico.otro())
                            menu_tacticas(submenu1, tipo, carpeta, lista)
            return lista

        menu_tacticas(menu_t, TACTICS_BASIC, Code.path_resource("Tactics"), [])
        lista = []
        carpetaTacticasP = self.configuration.folder_tactics()
        if os.path.isdir(carpetaTacticasP):
            submenu1 = menu_t.submenu(_("Personal tactics"), nico.otro())
            lista = menu_tacticas(submenu1, TACTICS_PERSONAL, carpetaTacticasP, lista)
            if lista:
                ico = Iconos.Delete()
                menub = menu_t.submenu(_("Remove"), ico)
                for carpeta, name in lista:
                    xopcion(menub, "remtactica|%s|%s" % (carpeta, name), trTraining(name), ico)
        menu_tactics.separador()

        xopcion(menu_tactics, "bmt", _("Find best move"), Iconos.BMT())
        menu_tactics.separador()

        xopcion(menu_tactics, "dailytest", _("Your daily test"), Iconos.DailyTest())
        menu_tactics.separador()

        xopcion(menu_tactics, "potencia", _("Determine your calculating power"), Iconos.Potencia())
        menu_tactics.separador()
        # TOL
        menu_tactics.separador()
        menu2 = menu_tactics.submenu(_("Turn on the lights"), Iconos.TOL())
        menu.separador()
        menu3 = menu2.submenu(_("Memory mode"), Iconos.TOL())
        xopcion(menu3, "tol_uned_easy", "%s (%s)" % (_("UNED chess school"), _("Initial")), Iconos.Uned())
        menu3.separador()
        xopcion(menu3, "tol_uned", "%s (%s)" % (_("UNED chess school"), _("Complete")), Iconos.Uned())
        menu3.separador()
        xopcion(menu3, "tol_uwe_easy", "%s (%s)" % (_("Uwe Auerswald"), _("Initial")), Iconos.Uwe())
        menu3.separador()
        xopcion(menu3, "tol_uwe", "%s (%s)" % (_("Uwe Auerswald"), _("Complete")), Iconos.Uwe())
        menu2.separador()
        menu3 = menu2.submenu(_("Calculation mode"), Iconos.Calculo())
        xopcion(menu3, "tol_uned_easy_calc", "%s (%s)" % (_("UNED chess school"), _("Initial")), Iconos.Uned())
        menu3.separador()
        xopcion(menu3, "tol_uned_calc", "%s (%s)" % (_("UNED chess school"), _("Complete")), Iconos.Uned())
        menu3.separador()
        xopcion(menu3, "tol_uwe_easy_calc", "%s (%s)" % (_("Uwe Auerswald"), _("Initial")), Iconos.Uwe())
        menu3.separador()
        xopcion(menu3, "tol_uwe_calc", "%s (%s)" % (_("Uwe Auerswald"), _("Complete")), Iconos.Uwe())
        menu2.separador()
        xopcion(menu2, "tol_oneline", _("Turn on lights in one line"), Iconos.TOLline())
Exemple #50
0
    def tg_training(self):

        w = WBG_Training.WTraining(self, self.tree.dicValoracion, self.tree.dicVentaja)
        w.exec_()
        if not w.siAceptado:
            return
        um = QTUtil2.unMomento(self)
        dic = w.resultado()
        siBlancas = dic["SIWHITE"]
        tactica = Tacticas.BaseTactica()
        menuname = dic["NAME"]
        depth = dic["DEPTH"]
        reValW, reVenW = dic["WHITE"]
        reValB, reVenB = dic["BLACK"]
        dicVal = {True: reValW, False: reValB}
        dicVen = {True: reVenW, False: reVenB}
        siAddOpening = dic["ADDSTD"]
        if siAddOpening:
            listaAperturasStd = AperturasStd.ap
        tactica.SHOWTEXT = [0 if siAddOpening else 1, ]

        # Leemos todas las lineas=listas de movimientos
        liT = self.bookGuide.allLines()

        # Se calcula el nombre de la carpeta
        name = self.bookGuide.name
        restDir = name
        nomDir = os.path.join(VarGen.configuracion.dirPersonalTraining, "Tactics", restDir)
        nomIni = os.path.join(nomDir, "Config.ini")
        if os.path.isfile(nomIni):
            dic = Util.ini8dic(nomIni)
            n = 1
            while True:
                if "TACTIC%d" % n in dic:
                    if "MENU" in dic["TACTIC%d" % n]:
                        if dic["TACTIC%d" % n]["MENU"].upper() == menuname.upper():
                            break
                    else:
                        break
                    n += 1
                else:
                    break
            nomTactic = "TACTIC%d" % n
        else:
            nomDirTac = os.path.join(VarGen.configuracion.dirPersonalTraining, "Tactics")
            Util.creaCarpeta(nomDirTac)
            Util.creaCarpeta(nomDir)
            nomTactic = "TACTIC1"
            dic = {}
        nomFNS = os.path.join(nomDir, nomTactic + ".fns")

        # Se crea el fichero con los puzzles
        f = codecs.open(nomFNS, "w", "utf-8", 'ignore')
        setPr = set()
        set_fathers_removed = set()
        for nline, liMVbase in enumerate(liT):
            if siBlancas:
                liMV = liMVbase[1:]
            else:
                liMV = liMVbase[2:]
            if not liMV:
                continue

            fenBase = liMV[0].fenBase()

            numJG = 1
            pgn = ""
            if not siBlancas:
                pgn += "%d..." % numJG
                numJG += 1
            colorAct = siBlancas
            if len(liMV) > depth:
                liMV = liMV[:depth]

            for mv in liMV:
                mas = ""

                if mv.adv() in dicVen[colorAct] or \
                                mv.nag() in dicVal[colorAct] or \
                                mv.father in set_fathers_removed:
                    set_fathers_removed.add(mv)
                    continue

                if colorAct == siBlancas:
                    liBrothers = mv.brothers()
                    for mv1 in liBrothers:
                        if mv1.adv() in dicVen[colorAct] or \
                                        mv1.nag() in dicVal[colorAct]:
                            continue
                        mas += "(%s)" % mv1.pgnEN()

                if colorAct:
                    pgn += " %d." % numJG
                    numJG += 1
                pgn += " " + mv.pgnEN()
                if mas:
                    pgn += " " + mas
                colorAct = not colorAct

            k = fenBase + pgn

            if k not in setPr:
                txt = ""
                if siAddOpening:
                    opening = listaAperturasStd.asignaAperturaListaMoves(liMVbase[1:])
                    if opening:
                        txt += "%s: %s<br>" % (_("Opening"), opening)
                txt += mv.comment()

                f.write("%s|%s|%s\n" % (fenBase, txt, pgn))
                setPr.add(k)
        f.close()

        # Se crea el fichero de control
        dic[nomTactic] = d = {}
        d["MENU"] = menuname
        d["FILESW"] = "%s.fns:100" % nomTactic

        d["PUZZLES"] = str(tactica.PUZZLES)
        for field in ("JUMPS", "REPEAT", "PENALIZATION", "SHOWTEXT"):
            d[field] = tactica.comas2texto(field)

        Util.dic8ini(nomIni, dic)

        self.procesador.entrenamientos.rehaz()
        um.final()
        QTUtil2.mensaje(self, _X(_("Tactic training %1 created."), menuname) + "<br>" +
                        _X(_("You can access this training from menu Trainings-Learn tactics by repetition-%1"),
                           name))
Exemple #51
0
    def leerPGNs(self, ficheros, dlTmp):
        erroneos = duplicados = importados = n = 0

        t1 = time.time() - 0.7  # para que empiece enseguida

        next_n = random.randint(100, 200)

        self.dbSTAT.massive_append_set(True)

        # fich_erroneos = "UsrData/fich_erroneos.pgn"

        codec = Util.file_encoding(ficheros[0])
        sicodec = codec not in ("utf-8", "ascii")

        liRegs = []
        stRegs = set()
        nRegs = 0

        conexion = self._conexion
        cursor = self._cursor

        sql = "insert into games (XPV,EVENT,SITE,DATE,WHITE,BLACK,RESULT,ECO,WHITEELO,BLACKELO,PGN,PLIES) values (?,?,?,?,?,?,?,?,?,?,?,?);"
        liCabs = self.liCamposBase[:-1]  # all except PLIES PGN, TAGS
        liCabs.append("PLYCOUNT")

        for fichero in ficheros:
            dlTmp.pon_titulo(os.path.basename(fichero))
            with LCEngine.PGNreader(fichero, self.depthStat()) as fpgn:
                for n, (pgn, pv, dCab, raw, liFens) in enumerate(fpgn, 1):
                    if not pv:
                        erroneos += 1
                    else:
                        fen = dCab.get("FEN", None)
                        if fen and fen != ControlPosicion.FEN_INICIAL:
                            erroneos += 1
                        else:
                            xpv = pv2xpv(pv)
                            if xpv in stRegs:
                                dup = True
                            else:
                                cursor.execute(
                                    "SELECT COUNT(*) FROM games WHERE XPV = ?",
                                    (xpv, ))
                                num = cursor.fetchone()[0]
                                dup = num > 0
                            if dup:
                                duplicados += 1
                            else:
                                stRegs.add(xpv)
                                if sicodec:
                                    for k, v in dCab.iteritems():
                                        dCab[k] = unicode(v,
                                                          encoding=codec,
                                                          errors="ignore")
                                    if pgn:
                                        pgn = unicode(pgn,
                                                      encoding=codec,
                                                      errors="ignore")

                                if raw:  # si no tiene variantes ni comentarios, se graba solo las tags que faltan
                                    liRTags = [(k, v)
                                               for k, v in dCab.iteritems()
                                               if k not in liCabs
                                               ]  # k is always upper
                                    if liRTags:
                                        pgn = {}
                                        pgn["RTAGS"] = liRTags
                                    else:
                                        pgn = None

                                event = dCab.get("EVENT", "")
                                site = dCab.get("SITE", "")
                                date = dCab.get("DATE", "")
                                white = dCab.get("WHITE", "")
                                black = dCab.get("BLACK", "")
                                result = dCab.get("RESULT", "")
                                eco = dCab.get("ECO", "")
                                whiteelo = dCab.get("WHITEELO", "")
                                blackelo = dCab.get("BLACKELO", "")
                                plies = (pv.count(" ") + 1) if pv else 0
                                if pgn:
                                    pgn = Util.var2blob(pgn)

                                reg = (xpv, event, site, date, white, black,
                                       result, eco, whiteelo, blackelo, pgn,
                                       plies)
                                self.dbSTAT.append_fen(pv, result, liFens)
                                liRegs.append(reg)
                                nRegs += 1
                                importados += 1
                                if nRegs == 10000:
                                    cursor.executemany(sql, liRegs)
                                    liRegs = []
                                    stRegs = set()
                                    conexion.commit()
                    if n == next_n:
                        if time.time() - t1 > 0.8:
                            if not dlTmp.actualiza(
                                    erroneos + duplicados + importados,
                                    erroneos, duplicados, importados):
                                break
                            t1 = time.time()
                        next_n = n + random.randint(100, 500)

        if liRegs:
            cursor.executemany(sql, liRegs)
            conexion.commit()

        dlTmp.actualiza(erroneos + duplicados + importados, erroneos,
                        duplicados, importados)
        dlTmp.ponSaving()

        self.dbSTAT.massive_append_set(False)
        self.dbSTAT.commit()
        conexion.commit()
        dlTmp.ponContinuar()
 def write(self):
     Util.save_pickle(self.file, self._list)
Exemple #53
0
    def new(self):
        recno = self.ghistorico.recno()
        if recno >= 0:
            key = self.liHistorico[recno]
            reg = self.historico[key]
            sitePre = reg["SITE"]
            intervaloPre = reg["INTERVAL"]
            intervaloPorPiezaPre = reg["INTERVALPIECE"]
            esatacadaPre = reg["ISATTACKED"]
            esatacantePre = reg["ISATTACKING"]
            posicionPre = reg["POSITION"]
            colorPre = reg["COLOR"]
        else:
            recno = 0
            sitePre = None
            intervaloPre = 3
            intervaloPorPiezaPre = True
            esatacadaPre = False
            esatacantePre = False
            posicionPre = False
            colorPre = False

        # Datos
        liGen = [(None, None)]

        # # Site
        f = open(self.path_bloque)
        liData = [x.split("|") for x in f.read().split("\n")]
        f.close()
        liSites = []
        sitePreNum = -1
        for n, uno in enumerate(liData):
            site = uno[0]
            if site:
                if sitePre and site == sitePre:
                    sitePreNum = n
                liSites.append((site, n))
        liSites = sorted(liSites, key=lambda st: st[0])
        config = FormLayout.Combobox(_("Site"), liSites)
        if sitePreNum == -1:
            sitePreNum = liSites[0][0]
        liGen.append((config, sitePreNum))

        liGen.append((None, None))

        # # Intervals
        liGen.append((None, _("Seconds of every glance") + ":"))
        liGen.append((FormLayout.Spinbox(_("Seconds"), 1, 100,
                                         50), intervaloPre))

        liTypes = ((_("By piece"), True), (_("Fixed"), False))
        config = FormLayout.Combobox(_("Type"), liTypes)
        liGen.append((config, intervaloPorPiezaPre))

        liGen.append((None, None))

        liGen.append((None, _("Ask for") + ":"))
        liGen.append((_("Position") + ":", posicionPre))
        liGen.append((_("Square color") + ":", colorPre))
        liGen.append((_("Is attacked?") + ":", esatacadaPre))
        liGen.append((_("Is attacking?") + ":", esatacantePre))

        resultado = FormLayout.fedit(liGen,
                                     title=_("Configuration"),
                                     parent=self,
                                     icon=Iconos.Gafas(),
                                     anchoMinimo=360)
        if resultado:
            accion, liGen = resultado

            siteNum, \
            intervalo, intervaloPorPieza, \
            posicion, color, esatacada, esatacante = liGen

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

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

            self.work(recno)
Exemple #54
0
 def append(self, valor):
     k = str(Util.today())
     self.__setitem__(k, valor)
     self.regKeys = self.keys(True, True)
Exemple #55
0
 def blankPartida(self):
     hoy = Util.hoy()
     liTags = [
         ["Date", "%d.%02d.%02d" % (hoy.year, hoy.month, hoy.day)],
     ]
     return Partida.PartidaCompleta(liTags=liTags)
 def nombre(self):
     self.test_bmi2()
     if self._nombre:
         return self._nombre
     return Util.primeraMayuscula(self.carpeta) + " " + self.version
 def carpeta_gaviota(self):
     if not Util.exist_file(
             os.path.join(self.x_carpeta_gaviota, "kbbk.gtb.cp4")):
         self.x_carpeta_gaviota = self.carpeta_gaviota_defecto()
         self.graba()
     return self.x_carpeta_gaviota
Exemple #58
0
    def __init__(self, procesador, titulo):
        super().__init__(parent=procesador.pantalla,
                         titulo=titulo,
                         icono=Iconos.Libre(),
                         extparam="entMaquina")

        self.configuracion = procesador.configuracion
        self.procesador = procesador

        self.personalidades = Personalidades.Personalidades(
            self, self.configuracion)

        self.motores = Motores.Motores(self.configuracion)

        # Toolbar

        liAcciones = [
            (_("Accept"), Iconos.Aceptar(), self.aceptar),
            None,
            (_("Cancel"), Iconos.Cancelar(), self.cancelar),
            None,
            (_("Configurations"), Iconos.Configurar(), self.configuraciones),
            None,
        ]
        tb = Controles.TBrutina(self, liAcciones)

        # Tab

        tab = Controles.Tab()

        def nuevoG():
            lyG = Colocacion.G()
            lyG.filaActual = 0
            return lyG

        gbStyle = """
            QGroupBox {
                font: bold 16px;
                background-color: #F2F2EC;/*qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #E0E0E0, stop: 1 #FFFFFF);*/
                border: 1px solid gray;
                border-radius: 3px;
                margin-top: 5ex; /* leave space at the top for the title */
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center; /* position at the top center */
                padding: 0 3px;
             }
        """

        def _label(lyG, txt, ly, rutinaCHB=None, siCheck=False):
            gb = Controles.GB(self, txt, ly)
            if rutinaCHB:
                gb.conectar(rutinaCHB)
            elif siCheck:
                gb.setCheckable(True)
                gb.setChecked(False)

            gb.setStyleSheet(gbStyle)
            lyG.controlc(gb, lyG.filaActual, 0)
            lyG.filaActual += 1
            return gb

        # TAB General

        lyG = nuevoG()

        # Blancas o negras
        self.rbBlancas = Controles.RB(self, "").activa()
        self.rbBlancas.setIcon(
            QTVarios.fsvg2ico("Pieces/Chessicons/wp.svg", 64))
        self.rbNegras = Controles.RB(self, "")
        self.rbNegras.setIcon(QTVarios.fsvg2ico("Pieces/Chessicons/bp.svg",
                                                64))
        self.rbRandom = Controles.RB(self, _("Random"))
        hbox = Colocacion.H().relleno().control(
            self.rbBlancas).espacio(30).control(
                self.rbNegras).espacio(30).control(self.rbRandom).relleno()
        _label(lyG, _("Select color"), hbox)

        # Motores
        liDepths = [("--", 0)]
        for x in range(1, 31):
            liDepths.append((str(x), x))

        # # Rival
        self.rival = self.configuracion.rivalInicial
        self.rivalTipo = Motores.INTERNO
        self.btRival = Controles.PB(self, "", self.cambiaRival, plano=False)
        self.edRtiempo = Controles.ED(self).tipoFloat().anchoMaximo(50)
        self.cbRdepth = Controles.CB(self, liDepths,
                                     0).capturaCambiado(self.cambiadoDepth)
        lbTiempoSegundosR = Controles.LB2P(self, _("Time"))
        lbNivel = Controles.LB2P(self, _("Depth"))

        # # Ajustar rival
        liAjustes = self.personalidades.listaAjustes(True)
        self.cbAjustarRival = Controles.CB(self, liAjustes,
                                           kAjustarMejor).capturaCambiado(
                                               self.ajustesCambiado)
        lbAjustarRival = Controles.LB2P(self, _("Set strength"))
        btAjustarRival = Controles.PB(self,
                                      _("Personality"),
                                      self.cambiaPersonalidades,
                                      plano=True).ponIcono(Iconos.Mas(),
                                                           tamIcon=16)

        # Resign
        lbResign = Controles.LB2P(self, _("Resign/draw by engine"))
        liResign = ((_("Very early"), -100), (_("Early"), -300),
                    (_("Average"), -500), (_("Late"), -800),
                    (_("Very late"), -1000), (_("Never"), -9999999))
        self.cbResign = Controles.CB(self, liResign, -800)

        lyH1 = Colocacion.H().control(self.btRival).espacio(20)
        lyH1.control(lbTiempoSegundosR).control(self.edRtiempo)
        lyH1.control(lbNivel).control(self.cbRdepth).relleno()
        lyH2 = Colocacion.H().control(lbAjustarRival).control(
            self.cbAjustarRival).control(btAjustarRival).relleno()
        lyH3 = Colocacion.H().control(lbResign).control(
            self.cbResign).relleno()
        ly = Colocacion.V().otro(lyH1).otro(lyH2).otro(lyH3)
        _label(lyG, _("Opponent"), ly)

        gb = Controles.GB(self, "", lyG)
        tab.nuevaTab(gb, _("Basic configuration"))

        # TAB Ayudas
        lbAyudas = Controles.LB2P(self, _("Available hints"))
        self.sbAyudas = Controles.SB(self, 7, 0, 999).tamMaximo(50)
        self.cbAtras = Controles.CHB(self, _("Takeback"), True)
        self.cbChance = Controles.CHB(self, _("Second chance"), True)
        btTutorChange = Controles.PB(self,
                                     _("Tutor change"),
                                     self.tutorChange,
                                     plano=False).ponIcono(Iconos.Tutor(),
                                                           tamIcon=16)

        liThinks = [(_("Nothing"), -1), (_("Score"), 0)]
        for i in range(1, 5):
            liThinks.append(
                ("%d %s" % (i, _("ply") if i == 1 else _("plies")), i))
        liThinks.append((_("All"), 9999))

        lb = Controles.LB(self, _("It is showed") + ":")
        self.cbThoughtTt = Controles.CB(self, liThinks, -1)
        self.cbContinueTt = Controles.CHB(
            self, _("The tutor thinks while you think"), True)
        lbBoxHeight = Controles.LB2P(self, _("Box height"))
        self.sbBoxHeight = Controles.SB(self, 7, 0, 999).tamMaximo(50)
        ly1 = Colocacion.H().control(lb).control(self.cbThoughtTt).relleno()
        ly2 = Colocacion.H().control(lbBoxHeight).control(
            self.sbBoxHeight).relleno()
        ly = Colocacion.V().otro(ly1).control(
            self.cbContinueTt).espacio(16).otro(ly2).relleno()
        gbThoughtTt = Controles.GB(self, _("Thought of the tutor"), ly)
        gbThoughtTt.setStyleSheet(gbStyle)

        lb = Controles.LB(self, _("It is showed") + ":")
        self.cbThoughtOp = Controles.CB(self, liThinks, -1)
        lbArrows = Controles.LB2P(self, _("Arrows to show"))
        self.sbArrows = Controles.SB(self, 7, 0, 999).tamMaximo(50)
        ly1 = Colocacion.H().control(lb).control(self.cbThoughtOp).relleno()
        ly2 = Colocacion.H().control(lbArrows).control(self.sbArrows).relleno()
        ly = Colocacion.V().otro(ly1).otro(ly2).relleno()
        gbThoughtOp = Controles.GB(self, _("Thought of the opponent"), ly)
        gbThoughtOp.setStyleSheet(gbStyle)

        self.chbSummary = Controles.CHB(
            self,
            _("Save a summary when the game is finished in the main comment"),
            False)

        lyH1 = Colocacion.H().relleno()
        lyH1.control(lbAyudas).control(self.sbAyudas).relleno()
        lyH1.control(self.cbAtras).relleno()
        lyH1.control(self.cbChance).relleno()
        lyH1.control(btTutorChange).relleno()

        # lyV1 = Colocacion.V().control(gbThoughtOp)

        lyH3 = Colocacion.H().relleno()
        lyH3.control(gbThoughtOp).relleno()
        lyH3.control(gbThoughtTt).relleno()

        ly = Colocacion.V().otro(lyH1).otro(lyH3).control(
            self.chbSummary).margen(16)
        gb = Controles.GB(self, "", ly)
        tab.nuevaTab(gb, _("Help configuration"))

        # TAB Tiempo

        lyG = nuevoG()
        self.edMinutos, self.lbMinutos = QTUtil2.spinBoxLB(
            self, 15, 0, 999, maxTam=50, etiqueta=_("Total minutes"))
        self.edSegundos, self.lbSegundos = QTUtil2.spinBoxLB(
            self,
            6,
            -999,
            999,
            maxTam=54,
            etiqueta=_("Seconds added per move"))
        self.edMinExtra, self.lbMinExtra = QTUtil2.spinBoxLB(
            self,
            0,
            -999,
            999,
            maxTam=70,
            etiqueta=_("Extra minutes for the player"))
        self.edZeitnot, self.lbZeitnot = QTUtil2.spinBoxLB(
            self,
            0,
            -999,
            999,
            maxTam=54,
            etiqueta=_("Zeitnot: alarm sounds when remaining seconds"))
        lyH1 = Colocacion.H()
        lyH1.control(self.lbMinutos).control(self.edMinutos).espacio(30)
        lyH1.control(self.lbSegundos).control(self.edSegundos).relleno()
        lyH2 = Colocacion.H()
        lyH2.control(self.lbMinExtra).control(self.edMinExtra).relleno()
        lyH3 = Colocacion.H()
        lyH3.control(self.lbZeitnot).control(self.edZeitnot).relleno()
        ly = Colocacion.V().otro(lyH1).otro(lyH2).otro(lyH3)
        self.chbTiempo = _label(lyG, _("Time"), ly, siCheck=True)

        gb = Controles.GB(self, "", lyG)
        tab.nuevaTab(gb, _("Time"))

        # TAB Initial moves

        lyG = nuevoG()

        # Posicion
        self.btPosicion = Controles.PB(self, " " * 5 + _("Change") + " " * 5,
                                       self.posicionEditar).ponPlano(False)
        self.fen = ""
        self.btPosicionQuitar = Controles.PB(
            self, "", self.posicionQuitar).ponIcono(Iconos.Motor_No())
        self.btPosicionPegar = Controles.PB(self, "",
                                            self.posicionPegar).ponIcono(
                                                Iconos.Pegar16()).ponToolTip(
                                                    _("Paste FEN position"))
        hbox = Colocacion.H().relleno().control(self.btPosicionQuitar).control(
            self.btPosicion).control(self.btPosicionPegar).relleno()
        _label(lyG, _("Start position"), hbox)

        # Aperturas
        self.btApertura = Controles.PB(self,
                                       " " * 5 + _("Undetermined") + " " * 5,
                                       self.editarApertura).ponPlano(False)
        self.bloqueApertura = None
        self.btAperturasFavoritas = Controles.PB(
            self, "", self.aperturasFavoritas).ponIcono(Iconos.Favoritos())
        self.btAperturasQuitar = Controles.PB(
            self, "", self.aperturasQuitar).ponIcono(Iconos.Motor_No())
        hbox = Colocacion.H().relleno().control(
            self.btAperturasQuitar).control(self.btApertura).control(
                self.btAperturasFavoritas).relleno()
        _label(lyG, _("Opening"), hbox)

        # Libros
        fvar = self.configuracion.ficheroBooks
        self.listaLibros = Books.ListaLibros()
        self.listaLibros.recuperaVar(fvar)
        # Comprobamos que todos esten accesibles
        self.listaLibros.comprueba()
        li = [(x.nombre, x) for x in self.listaLibros.lista]
        libInicial = li[0][1] if li else None
        self.cbBooks = QTUtil2.comboBoxLB(self, li, libInicial)
        self.btNuevoBook = Controles.PB(self, "", self.nuevoBook,
                                        plano=True).ponIcono(Iconos.Mas(),
                                                             tamIcon=16)
        self.chbBookMandatory = Controles.CHB(self, _("Mandatory"), False)
        # Respuesta rival
        li = (
            (_("Selected by the player"), "su"),
            (_("Uniform random"), "au"),
            (_("Proportional random"), "ap"),
            (_("Always the highest percentage"), "mp"),
        )
        self.cbBooksRR = QTUtil2.comboBoxLB(self, li, "mp")
        self.lbBooksRR = Controles.LB2P(self, _("Opponent's move"))
        hbox = Colocacion.H().relleno().control(self.cbBooks).control(
            self.btNuevoBook).control(self.chbBookMandatory).relleno()
        hboxRR = Colocacion.H().relleno().control(self.lbBooksRR).control(
            self.cbBooksRR).relleno()
        hboxV = Colocacion.V().otro(hbox).otro(hboxRR)
        self.chbBook = _label(lyG, _("Book"), hboxV, siCheck=True)

        ly = Colocacion.V().otro(lyG).relleno()

        gb = Controles.GB(self, "", ly)
        tab.nuevaTab(gb, _("Initial moves"))

        layout = Colocacion.V().control(tb).control(tab).relleno().margen(3)

        self.setLayout(layout)

        self.liAperturasFavoritas = []
        self.btAperturasFavoritas.hide()

        dic = Util.recuperaDIC(self.configuracion.ficheroEntMaquina)
        if not dic:
            dic = {}
        self.muestraDic(dic)

        self.ajustesCambiado()
        # self.ayudasCambiado()
        self.ponRival()

        self.recuperarVideo()
 def piezas_gaviota(self):
     if Util.exist_file(
             os.path.join(self.carpeta_gaviota(), "kbbkb.gtb.cp4")):
         return 5
     return 4
Exemple #60
0
 def dbdatos(self):
     return Util.DicSQL(self.fichero, tabla=self.nombre)