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
def __init__(self, wParent, titulo, hasta, etiqueta=None, pos=None, mensAdicional=None): super(WNumEntrenamiento, self).__init__(wParent) self.setWindowTitle(titulo) self.setWindowIcon(Iconos.Datos()) tb = QTUtil2.tbAcceptCancel(self) if pos is None: pos = 1 # random.randint( 1, hasta ) if etiqueta is None: etiqueta = _("Training unit") self.ed, lb = QTUtil2.spinBoxLB(self, pos, 1, hasta, etiqueta=etiqueta, maxTam=60) lb1 = Controles.LB(self, "/ %d" % hasta) if mensAdicional: lb2 = Controles.LB(self, mensAdicional) lb2.ponWrap().anchoMinimo(250) lyH = Colocacion.H().relleno().control(lb).control(self.ed).control(lb1).relleno().margen(15) lyV = Colocacion.V().control(tb).otro(lyH) if mensAdicional: lyV.control(lb2) lyV.margen(3) self.setLayout(lyV) self.resultado = None
def finLinea(self): self.compruebaComentarios() QTUtil2.mensajeTemporal(self.pantalla, _("This line training is completed."), 0.7) self.estado = kFinJuego self.desactivaTodas() liOpciones = [k_mainmenu, k_reiniciar, k_cambiar] if not ( self.siTerminada() and len(self.liVariantes) == 0 ): liOpciones.append(k_variantes) if not self.siShowText: liOpciones.append(k_showtext) # Si no se ha mostrado ahora es el momento if self.dicEtiquetasPGN: liOpciones.append(k_pgnInformacion) liOpciones.extend([k_configurar, k_utilidades, k_siguiente]) self.pantalla.ponToolBar(liOpciones) self.tactica.ponPosActual(self.posSiguiente) if self.tactica.terminada(): self.finalEntrenamiento() self.siPenalizable = False return
def texto2partida(owner, texto): pgn = PGN.UnPGN() pgn.leeTexto(texto) if pgn.siError: QTUtil2.mensError(owner, _("This is not a valid PGN file")) return None return pgn.partida
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 ponResultado(self): self.estado = kFinJuego self.tablero.desactivaTodas() mensaje = _("Game ended") txt, porc, txtResumen = self.motorGM.resultado(self.partida) mensaje += "<br><br>" + txt if self.siJuez: mensaje += "<br><br><b>%s</b> = %+d<br>" % ( _("Points accumulated"), self.puntos ) QTUtil2.mensaje(self.pantalla, mensaje, siResalta=False) dbHisto = Util.DicSQL(self.configuracion.ficheroGMhisto) gmK = "P_%s" % self.gm if self.modo == "personal" else self.gm dic = {} dic["FECHA"] = Util.hoy() dic["PUNTOS"] = self.puntos dic["PACIERTOS"] = porc dic["JUEZ"] = self.motor dic["TIEMPO"] = self.tiempo dic["RESUMEN"] = txtResumen liHisto = dbHisto[gmK] if liHisto is None: liHisto = [] liHisto.insert(0, dic) dbHisto[gmK] = liHisto dbHisto.pack() dbHisto.close()
def __init__(self, parent): QtGui.QDialog.__init__(self, parent) self.setWindowFlags(QtCore.Qt.Dialog | QtCore.Qt.WindowTitleHint) icoP = VarGen.todasPiezas.iconoDefecto("P") icop = VarGen.todasPiezas.iconoDefecto("p") self.setWindowTitle(_("Choose Color")) self.setWindowIcon(icoP) btBlancas = Controles.PB(self, "", rutina=self.blancas, plano=False).ponIcono(icoP, tamIcon=64) btNegras = Controles.PB(self, "", rutina=self.negras, plano=False).ponIcono(icop, tamIcon=64) # Tiempo self.edMinutos, self.lbMinutos = QTUtil2.spinBoxLB(self, 5, 0, 999, maxTam=50, etiqueta=_("Total minutes")) self.edSegundos, self.lbSegundos = QTUtil2.spinBoxLB(self, 10, 0, 999, maxTam=50, etiqueta=_("Seconds added per move")) ly = Colocacion.G() ly.controld(self.lbMinutos, 0, 0).control(self.edMinutos, 0, 1) ly.controld(self.lbSegundos, 0, 2).control(self.edSegundos, 0, 3) self.gbT = Controles.GB(self, _("Time"), ly).conectar(self.cambiaTiempo) self.cambiaTiempo() self.color = None ly = Colocacion.H().control(btBlancas).control(btNegras) ly.margen(10) layout = Colocacion.V().otro(ly).espacio(10).control(self.gbT).margen(5) self.setLayout(layout)
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()
def grabar(self): nombreInicial = self.torneo.nombre() fichInicial = self.torneo.fichero() nombre = self.edNombre.texto() if not nombre: QTUtil2.mensaje(self, _("Missing name")) self.tab.activa(0) self.edNombre.setFocus() return False self.torneo.resign(self.sbResign.valor()) self.torneo.drawMinPly(self.sbDrawMinPly.valor()) self.torneo.drawRange(self.sbDrawRange.valor()) self.torneo.fen(self.fen) self.torneo.norman(self.chbNorman.valor()) try: self.torneo.nombre(nombre) self.torneo.grabar() if fichInicial and self.torneo.fichero().lower() != fichInicial.lower(): os.remove(fichInicial) return True except: self.torneo.nombre(nombreInicial) QTUtil2.mensaje(self, _("Unable to save") + "\n" + _("The tournament name contains incorrect characters")) return False
def mueveMas(self): mrm = self.gestor.analizaEstado() rmUsuN, pos = mrm.buscaRM(self.rmUsu.movimiento()) if rmUsuN is None: um = QTUtil2.analizando(self) self.gestor.analizaFinal() rmUsuN = self.xmotor.valora(self.posicion, self.rmUsu.desde, self.rmUsu.hasta, self.rmUsu.coronacion) mrm.agregaRM(rmUsuN) self.gestor.analizaInicio() um.final() self.rmUsu = rmUsuN rmOPN, pos = mrm.buscaRM(self.rmOP.movimiento()) if rmOPN is None: um = QTUtil2.analizando(self) self.gestor.analizaFinal() rmOPN = self.xmotor.valora(self.posicion, self.rmOP.desde, self.rmOP.hasta, self.rmOP.coronacion) pos = mrm.agregaRM(rmOPN) self.gestor.analizaInicio() um.final() self.rmOP = rmOPN self.analisis = self.mrm, pos self.mrm = mrm self.ponPuntos() self.listaRM, self.posOP = self.hazListaRM() self.grid.refresh()
def grabarComo(self): extension = "pks" siConfirmar = True if self.ultimoFichero: fichero = self.ultimoFichero else: fichero = self.configuracion.dirJS while True: resp = QTUtil2.salvaFichero(self.pantalla, _("File to save"), fichero, _("File") + " %s (*.%s)" % (extension, extension), siConfirmarSobreescritura=siConfirmar) if resp: resp = str(resp) if not siConfirmar: if os.path.abspath(resp) != os.path.abspath(self.ultimoFichero) and os.path.isfile(resp): yn = QTUtil2.preguntaCancelar(self.pantalla, _X(_("The file %1 already exists, what do you want to do?"), resp), si=_("Overwrite"), no=_("Choose another")) if yn is None: break if not yn: continue if self.grabarFichero(resp): self.ultimoFichero = resp self.ponToolBar(True, True) return resp break return None
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 appendFrom(self, wowner, otraGuide): self.grabar() otroFichero = self.pathGuide(otraGuide) otraConexion = sqlite3.connect(otroFichero) otraConexion.text_factory = lambda x: unicode(x, "utf-8", "ignore") cursor = otraConexion.cursor() cursor.execute("pragma table_info(%s)" % self.tablaDatos) liCamposOtra = cursor.fetchall() cursor.close() if not liCamposOtra: return False st = set() for x in liCamposOtra: st.add(x[1]) # nombre liselect = ("XPV", "PV", "NAG", "ADV", "COMMENT", "FEN", "MARK", "GRAPHICS", "XDATA") libasic = ("XPV", "PV", "FEN") li = [] for x in liselect: if x not in st: if x in libasic: otraConexion.close() QTUtil2.mensError(wowner, _("This guide file is not valid")) return False else: li.append(x) select = ",".join(li) dbfOtra = SQLDBF.DBF(otraConexion, self.tablaDatos, select) dbfOtra.leer() reccount = dbfOtra.reccount() bp = QTUtil2.BarraProgreso(wowner, otraGuide, "", reccount).mostrar() liReg = [] for recno in range(reccount): bp.pon(recno) if bp.siCancelado(): break dbfOtra.goto(recno) reg = dbfOtra.registroActual() liReg.append(reg) dbfOtra.cerrar() otraConexion.close() def dispatch(recno): bp.pon(recno) if liReg: dbf = SQLDBF.DBF(self.conexion, self.tablaDatos, select) dbf.insertarLista(liReg, dispatch) dbf.cerrar() bp.cerrar() return len(liReg) > 0
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 ponResultado(self, quien): self.resultado = quien self.desactivaTodas() self.siJuegaHumano = False self.beepResultado(quien) nombreContrario = "%s (%s %d)" % (self.xrival.nombre, _("Level"), self.nivelJugado) mensaje = _("Game ended") if quien == kGanamos: mensaje = _X(_("Congratulations you have won against %1."), nombreContrario) hecho = "B" if self.siJugamosConBlancas else "N" if self.configuracion.rival.categorias.ponResultado(self.categoria, self.nivelJugado, hecho): mensaje += "<br><br>%s: %d (%s)" % ( _("Move to the next level"), self.categoria.nivelHecho + 1, self.categoria.nombre(), ) self.configuracion.graba() if self.puntos: puntuacion = self.configuracion.puntuacion() mensaje += "<br><br>%s: %d+%d = %d %s" % ( _("Total score"), puntuacion - self.puntos, self.puntos, puntuacion, _("pts"), ) self.xrotulo2() elif quien == kGanaRival: mensaje = _X(_("Unfortunately you have lost against %1"), nombreContrario) elif quien == kTablas: mensaje = _X(_("Draw against %1."), nombreContrario) elif quien == kTablasRepeticion: mensaje = _X( _("Draw due to three times repetition (n. %1) against %2."), self.rotuloTablasRepeticion, nombreContrario, ) self.resultado = kTablas elif quien == kTablas50: mensaje = _X(_("Draw according to the 50 move rule against %1."), nombreContrario) self.resultado = kTablas elif quien == kTablasFaltaMaterial: mensaje = _X(_("Draw, not enough material to mate %1"), nombreContrario) self.resultado = kTablas self.guardarGanados(quien == kGanamos) QTUtil2.mensaje(self.pantalla, mensaje) self.ponFinJuego()
def ponResultado(self): tiempo = int((time.time() - self.iniTiempo) * 100.0) self.finJuego() self.ponPosicion(self.cp) self.refresh() mensaje, siRecord = self.pgn.mensResultado(self.numero, tiempo, self.errores) QTUtil2.mensajeTemporal(self.pantalla, mensaje, 3, background="#F22D52" if siRecord else None)
def ponResultado(self): self.estado = kFinJuego self.tablero.desactivaTodas() txt = self.txtAciertos() mensaje = "%s\n%s\n" % (_("Line completed"), txt ) QTUtil2.mensaje(self.pantalla, mensaje)
def final(self): seconds = int(time.time() - self.timer) self.historico.append(Util.hoy(), self.moves, seconds, self.hints) QTUtil2.mensaje(self, "<b>%s<b><ul><li>%s: <b>%d</b></li><li>%s: <b>%d</b></li><li>%s: <b>%d</b></li></ul>" % ( _("Congratulations goal achieved"), _("Moves"), self.moves, _("Second(s)"), seconds, _("Hints"), self.hints)) self.guardarVideo() self.accept()
def cambiaFichero(self): titulo = _("File to save") if self.siSave else _("File to read") fbusca = self.fichero if self.fichero else self.ficheroDefecto filtro = self.extension if "(" in self.extension else ( _("File") + " %s (*.%s)" % (self.extension, self.extension)) if self.siSave: resp = QTUtil2.salvaFichero(self, titulo, fbusca, filtro) else: resp = QTUtil2.leeFichero(self, fbusca, self.extension, titulo=titulo) if resp: self.ponFichero(resp)
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()
def grabarFichero(self): dirSalvados = VarGen.configuracion.dirSalvados resp = QTUtil2.salvaFichero(self, _("File to save"), dirSalvados, _("File") + " PNG (*.png)", False) if resp: self.tablero.salvaEnImagen(resp, "png") txt = resp QTUtil2.mensajeTemporal(self, _X(_("Saved to %1"), txt), 0.8) direc = os.path.dirname(resp) if direc != dirSalvados: VarGen.configuracion.dirSalvados = direc VarGen.configuracion.graba()
def repiteMate(self, siMensaje, siError): if siError: self.errores += 1 fen, pv = self.controlMate.repiteFenPV() fen += " w - - 0 1" if siMensaje: QTUtil2.mensErrorSobreControl(self.pantalla, _("Incorrect. Try again."), self.lbNivel) self.iniciaPosicion(fen)
def aceptar(self): self.nombre = self.edNombre.texto().strip() if not self.nombre: QTUtil2.mensError(self, _("Not indicated the name of training")) return if not self.liBloques: QTUtil2.mensError(self, _("you have not indicated any opening")) return self.accept()
def tw_nuevo(self): # Se genera un PGN pgn = self.dbGames.blankPGN() nuevoPGN, pv, dicPGN = self.procesador.gestorUnPGN(self, pgn) if nuevoPGN: if not self.dbGames.cambiarUno(None, nuevoPGN, pv, dicPGN): QTUtil2.mensError(self, _("This game already exists.")) else: self.wsummary.reset() self.actualiza() self.grid.gobottom()
def borrar(self): li = self.ghistorico.recnosSeleccionados() if len(li) > 0: if QTUtil2.pregunta(self, _("Do you want to delete all selected records?")): um = QTUtil2.unMomento(self) for fila in li: key = self.liHistorico[fila] del self.historico[key] self.historico.pack() self.calcListaHistorico() um.final() self.ghistorico.refresh()
def selectRandom(self): li = [] for mt in self.liMotoresActivos: if mt.siJugable: li.append(mt) if li: n = random.randint(0, len(li) - 1) self.resultado = li[n] self.guardarVideo() self.accept() else: QTUtil2.mensError(self, _("There is not a playable engine between these values"))
def guardar(self): nrecs = self.dbf.reccount() if nrecs == 0: return elif nrecs > 1: menu = QTVarios.LCMenu(self) menu.opcion("all", _("All games"), Iconos.PuntoNaranja()) menu.separador() menu.opcion("selected", _("Selected games"), Iconos.PuntoAzul()) resp = menu.lanza() if resp is None: return elif resp == "all": liSelected = range(nrecs) else: liSelected = self.grid.recnosSeleccionados() else: liSelected = [0] extension = "pgn" resp = QTUtil2.salvaFichero(self, _("File to save"), self.gestor.configuracion.dirSalvados, _("File") + " %s (*.%s)" % (extension, extension), False) if resp: antSelect = self.dbf.select nueSelect = antSelect + ",PGN" self.dbf.ponSelect(nueSelect) self.dbf.leer() self.dbf.gotop() li = [] for i in liSelected: self.dbf.goto(i) dic = self.dbf.dicValores() li.append(dic["PGN"]) dato = "\n\n".join(li) try: modo = "w" if Util.existeFichero(resp): modo = "a" dato = "\n" * 2 + dato f = codecs.open(resp, modo, 'utf-8', 'ignore') f.write(dato.replace("\n", "\r\n")) f.close() QTUtil2.mensaje(self, _X(_("Saved to %1"), resp)) direc = os.path.dirname(resp) if direc != self.gestor.configuracion.dirSalvados: self.gestor.configuracion.dirSalvados = direc self.gestor.configuracion.graba() except: QTUtil.ponPortapapeles(dato) QTUtil2.mensError(self, "%s : %s\n\n%s" % ( _("Unable to save"), resp, _("It is saved in the clipboard to paste it wherever you want.") )) self.dbf.ponSelect(antSelect)
def lineaTerminadaOpciones(self): self.estado = kFinJuego if self.jump: self.ent_siguiente(k_siguiente) return False else: QTUtil2.mensajeTemporal(self.pantalla, _("This line training is completed."), 0.7) if not self.siTerminada(): if k_peliculaSeguir not in self.liOpcionesToolBar: self.liOpcionesToolBar.append(k_peliculaSeguir) self.pantalla.ponToolBar(self.liOpcionesToolBar) return False
def ponResultado(self, quien): self.estado = kFinJuego self.resultado = quien self.desactivaTodas() self.siJuegaHumano = False self.beepResultado(quien) self.saveSummary() nombreContrario = self.xrival.nombre mensaje = _("Game ended") if quien == kGanamos: mensaje = _X(_("Congratulations you have won against %1."), nombreContrario) elif quien == kGanaRival: mensaje = _X(_("Unfortunately you have lost against %1"), nombreContrario) elif quien == kTablas: mensaje = _X(_("Draw against %1."), nombreContrario) elif quien == kTablasRepeticion: mensaje = _X(_("Draw due to three times repetition (n. %1) against %2."), self.rotuloTablasRepeticion, nombreContrario) self.resultado = kTablas elif quien == kTablas50: mensaje = _X(_("Draw according to the 50 move rule against %1."), nombreContrario) self.resultado = kTablas elif quien == kTablasFaltaMaterial: mensaje = _X(_("Draw, not enough material to mate %1"), nombreContrario) self.resultado = kTablas elif quien == kGanamosTiempo: mensaje = _X(_("Congratulations, you win %1 on time."), nombreContrario) self.resultado = kGanamos self.partida.liJugadas[-1].comentario = _X(_("%1 has won on time."), self.configuracion.jugador) elif quien == kGanaRivalTiempo: mensaje = _X(_("%1 has won on time."), nombreContrario) self.resultado = kGanaRival self.partida.liJugadas[-1].comentario = _X(_("%1 has won on time."), nombreContrario) self.guardarGanados(quien == kGanamos) if quien != kGanaRivalTiempo: # Ya que el mensaje ya se ha usado, para a_adir minutos QTUtil2.mensaje(self.pantalla, mensaje) if QTUtil2.pregunta(self.pantalla, _("Do you want to play again?")): self.reiniciar(False) else: self.ponFinJuego()
def tw_borrar(self): li = self.grid.recnosSeleccionados() if li: if not QTUtil2.pregunta(self, _("Do you want to delete all selected records?")): return um = QTUtil2.unMomento(self) self.dbGames.borrarLista(li) self.grid.refresh() self.updateStatus() um.final()
def data_remove(self): raw = self.workmap.db.listaRaws[self.gridData.recno()] if raw["ACTIVE"] != "X": if QTUtil2.pregunta(self, _X(_("Delete %1?"), _("this work"))): self.workmap.db.borra(raw["ROWID"]) self.gridData.refresh()
def portapapeles(self): self.tablero.salvaEnImagen() txt = _("Clipboard") QTUtil2.mensajeTemporal(self, _X(_("Saved to %1"), txt), 0.8)
def importarGM(ownerGM, siWoman): # Primero nos tenemos que traer la lista de la web fichz = "_listaGM.zip" ficht = "_listaGM.txt" fichtg = "GM/listaGM.txt" if siWoman: fichtg = "w" + fichtg try: os.remove(ficht) except: pass if siWoman: web = "http://lucaschess.pythonanywhere.com/static/wgm" message = _("Reading the list of Women Grandmaster from the web") else: web = "http://lucaschess.pythonanywhere.com/static/gm" message = _("Reading the list of Grandmasters from the web") me = QTUtil2.mensEspera.inicio(ownerGM, message) siError = False try: urllib.urlretrieve("%s/%s" % (web, fichz), fichz) zfobj = zipfile.ZipFile(fichz) for name in zfobj.namelist(): outfile = open(name, 'wb') outfile.write(zfobj.read(name)) outfile.close() zfobj.close() os.remove(fichz) except: siError = True me.final() if siError: QTUtil2.mensError(ownerGM, _("List of Grandmasters currently unavailable; please check Internet connectivity")) return False shutil.copy(ficht, fichtg) os.remove(ficht) f = open(fichtg, "rb") liGM = [] for linea in f: linea = linea.strip() if linea: gm, nombre, ctam, cpart = linea.split(VarGen.XSEP) fichero = "GM/%s.xgm" % gm if siWoman: fichero = "w" + fichero if Util.tamFichero(fichero) != int(ctam): # si no existe tam = -1 dic = {"GM": gm, "NOMBRE": nombre, "PARTIDAS": cpart, "ELEGIDO": False} liGM.append(dic) f.close() if len(liGM) == 0: QTUtil2.mensaje(ownerGM, _("You have all Grandmasters installed.")) return False w = WImportar(ownerGM, liGM) if w.exec_(): for dic in liGM: if dic["ELEGIDO"]: gm = dic["GM"] gm = gm[0].upper() + gm[1:].lower() me = QTUtil2.mensEspera.inicio(ownerGM, _X(_("Import %1"), gm), opacity=1.0) # Descargamos fzip = gm + ".zip" urllib.urlretrieve("%s/%s.zip" % (web, gm), fzip) zfobj = zipfile.ZipFile(fzip) for name in zfobj.namelist(): fichero = "GM/%s" % name if siWoman: fichero = "w" + fichero outfile = open(fichero, 'wb') outfile.write(zfobj.read(name)) outfile.close() zfobj.close() os.remove(fzip) me.final() return True return False
def reiniciar(self): if QTUtil2.pregunta(self.main_window, _("Restart the game?")): self.analizaTerminar() self.game.set_position() self.start(self.record)
def reiniciar(self): if len(self.game) and QTUtil2.pregunta(self.main_window, _("Restart the game?")): self.game.set_position() self.start(self.resistance, self.numEngine, self.key)
def grabarPolyglot(self, ventana, ficheroBIN, depth, whiteBest, blackBest): titulo = _("Import a polyglot book") tmpBP2 = QTUtil2.BarraProgreso2(ventana, titulo) tmpBP2.ponTotal(1, 1) tmpBP2.ponRotulo(1, "1. " + _X(_("Reading %1"), os.path.basename(ficheroBIN))) tmpBP2.ponTotal(2, 1) tmpBP2.ponRotulo(2, "") tmpBP2.mostrar() basePos = self.ultPos book = Books.Libro("P", ficheroBIN, ficheroBIN, True) book.polyglot() cp = ControlPosicion.ControlPosicion() lireg = [] stFenM2 = set() # para que no se produzca un circulo vicioso def hazFEN(fen, ply, seq): plyN = ply + 1 siWhite = " w " in fen siMax = False if whiteBest: siMax = siWhite if blackBest: siMax = siMax or not siWhite liPV = book.miraListaPV(fen, siMax) for pv in liPV: cp.leeFen(fen) cp.mover(pv[:2], pv[2:4], pv[4:]) fenN = cp.fen() reg = SQLDBF.Almacen() lireg.append(reg) reg.PV = pv seqN = seq + LCEngine.pv2xpv(pv) reg.XPV = seqN reg.COMMENT = "" reg.NAG = 0 reg.FEN = fenN reg.ADV = 0 self.ultPos += 1 reg.POS = self.ultPos tmpBP2.ponTotal(1, self.ultPos - basePos) tmpBP2.pon(1, self.ultPos - basePos) if plyN < depth: fenM2 = cp.fenM2() if fenM2 not in stFenM2: stFenM2.add(fenM2) hazFEN(fenN, plyN, seqN) hazFEN(ControlPosicion.FEN_INICIAL, 0, "") select = "XPV,PV,COMMENT,NAG,ADV,FEN,POS" dbf = SQLDBF.DBF(self.conexion, self.tablaDatos, select) tmpBP2.ponTotal(2, len(lireg)) tmpBP2.ponRotulo(2, _("Writing...")) def dispatch(num): tmpBP2.pon(2, num) dbf.insertarLista(lireg, dispatch) dbf.cerrar() tmpBP2.cerrar() return len(lireg) > 0
def saveIndexes(self): self.gestor.partida.setFirstComment(self.alm.indexesRAW) QTUtil2.mensajeTemporal(self, _("Saved"), 1.8)
def __init__(self, procesador, titulo, direct_option): QTVarios.WDialogo.__init__(self, procesador.main_window, titulo, Iconos.Libre(), "entMaquina") font = Controles.TipoLetra( puntos=procesador.configuration.x_menu_points) self.direct_option = direct_option self.setFont(font) self.configuration = procesador.configuration self.procesador = procesador self.personalidades = Personalities.Personalities( self, self.configuration) self.motores = SelectEngines.SelectEngines(self.configuration) # Toolbar li_acciones = [ (_("Accept"), Iconos.Aceptar(), self.aceptar), None, (_("Cancel"), Iconos.Cancelar(), self.cancelar), None, (_("Configurations"), Iconos.Configurar(), self.configurationes), None, ] tb = QTVarios.LCTB(self, li_acciones) # Tab tab = Controles.Tab() tab.dispatchChange(self.cambiada_tab) self.tab_advanced = 4 # está en la posición 4 self.tab_advanced_active = ( False ) # Para no tener que leer las options uci to_sq que no sean necesarias, afecta a gridNumDatos def nueva_tab(layout, titulo): ly = Colocacion.V() ly.otro(layout) ly.relleno() w = QtWidgets.QWidget(self) w.setLayout(ly) w.setFont(font) tab.nuevaTab(w, titulo) def nuevoG(): ly_g = Colocacion.G() ly_g.filaActual = 0 ly_g.margen(10) return ly_g gb_style = Common.gb_style() def _label(ly_g, txt, xlayout, rutinaCHB=None, siCheck: object = False): groupbox = Controles.GB(self, txt, xlayout) if rutinaCHB: groupbox.to_connect(rutinaCHB) elif siCheck: groupbox.setCheckable(True) groupbox.setChecked(False) groupbox.setStyleSheet(gb_style) groupbox.setMinimumWidth(640) groupbox.setFont(font) ly_g.controlc(groupbox, ly_g.filaActual, 0) ly_g.filaActual += 1 return groupbox # ################################################################################################################################## # TAB General # ################################################################################################################################## lyG = nuevoG() # # Motores # ## Rival self.rival = self.procesador.XTutor().confMotor self.rivalTipo = SelectEngines.INTERNO self.btRival = Controles.PB(self, "", self.cambiaRival, plano=False).ponFuente(font).altoFijo(48) lbTiempoSegundosR = Controles.LB2P( self, _("Fixed time in seconds")).ponFuente(font) self.edRtiempo = (Controles.ED(self).tipoFloat().anchoMaximo( 50).ponFuente(font).capture_changes(self.cambiadoTiempo)) bt_cancelar_tiempo = Controles.PB( self, "", rutina=self.cancelar_tiempo).ponIcono(Iconos.S_Cancelar()) ly_tiempo = Colocacion.H().control( self.edRtiempo).control(bt_cancelar_tiempo).relleno(1) lb_depth = Controles.LB2P(self, _("Fixed depth")).ponFuente(font) self.edRdepth = Controles.ED(self).tipoInt().anchoMaximo(50).ponFuente( font).capture_changes(self.change_depth) bt_cancelar_depth = Controles.PB( self, "", rutina=self.cancelar_depth).ponIcono(Iconos.S_Cancelar()) ly_depth = Colocacion.H().control( self.edRdepth).control(bt_cancelar_depth).relleno(1) ly = Colocacion.G() ly.controld(lbTiempoSegundosR, 0, 0).otro(ly_tiempo, 0, 1) ly.controld(lb_depth, 1, 0).otro(ly_depth, 1, 1) self.gb_thinks = Controles.GB(self, _("Limits of engine thinking"), ly) self.gb_thinks.setStyleSheet(""" QGroupBox { font: bold %d; 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; padding: 18px; margin-top: 5ex; /* leave space at the top for the title */ } QGroupBox::title { subcontrol-position: top center; /* position at the top center */ padding: 8px; border: 1px solid gray; } """ % procesador.configuration.x_menu_points) lyV = Colocacion.V().espacio(20).control( self.btRival).espacio(20).control(self.gb_thinks) _label(lyG, _("Opponent"), lyV) # # Color self.rb_white = Controles.RB(self, "").activa() self.rb_white.setIcon(Iconos.PeonBlanco()) self.rb_white.setIconSize(QtCore.QSize(32, 32)) self.rb_black = Controles.RB(self, "") self.rb_black.setIcon(Iconos.PeonNegro()) self.rb_black.setIconSize(QtCore.QSize(32, 32)) self.rbRandom = Controles.RB(self, _("Random")) self.rbRandom.setFont(Controles.TipoLetra(puntos=16)) hbox = (Colocacion.H().relleno().control( self.rb_white).espacio(30).control( self.rb_black).espacio(30).control(self.rbRandom).relleno()) _label(lyG, _("Side you play with"), hbox) nueva_tab(lyG, _("Basic configuration")) # ################################################################################################################################## # TAB Ayudas # ################################################################################################################################## self.chbSummary = Controles.CHB( self, _("Save a summary when the game is finished in the main comment"), False).ponFuente(font) self.chbTakeback = Controles.CHB(self, _("Option takeback activated"), True).ponFuente(font) # # Tutor lbAyudas = Controles.LB2P(self, _("Available hints")).ponFuente(font) liAyudas = [(_("Maximum"), 999)] for i in range(1, 21): liAyudas.append((str(i), i)) for i in range(25, 51, 5): liAyudas.append((str(i), i)) self.cbAyudas = Controles.CB(self, liAyudas, 999).ponFuente(font) self.chbChance = Controles.CHB(self, _("Second chance"), True).ponFuente(font) btTutorChange = (Controles.PB(self, _("Tutor change"), self.tutorChange, plano=False).ponIcono( Iconos.Tutor(), icon_size=16).ponFuente(font)) 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)) lbThoughtTt = Controles.LB(self, _("It is showed") + ":").ponFuente(font) self.cbThoughtTt = Controles.CB(self, liThinks, -1).ponFuente(font) self.lbBoxHeight = Controles.LB2P(self, _("Box height")).ponFuente(font) self.sbBoxHeight = Controles.SB(self, 7, 0, 999).tamMaximo(50).ponFuente(font) self.chbContinueTt = Controles.CHB( self, _("The tutor thinks while you think"), True).ponFuente(font) lbArrows = Controles.LB2P( self, _("Arrows with the best moves")).ponFuente(font) self.sbArrowsTt = Controles.SB(self, 3, 0, 999).tamMaximo(50).ponFuente(font) lyT1 = Colocacion.H().control(lbAyudas).control( self.cbAyudas).relleno() lyT1.control(self.chbChance).relleno().control(btTutorChange) lyT2 = Colocacion.H().control(self.chbContinueTt).relleno() lyT2.control(self.lbBoxHeight).control(self.sbBoxHeight).relleno() lyT3 = Colocacion.H().control(lbThoughtTt).control( self.cbThoughtTt).relleno() lyT3.control(lbArrows).control(self.sbArrowsTt) ly = Colocacion.V().otro(lyT1).espacio(16).otro(lyT2).otro( lyT3).relleno() self.gbTutor = Controles.GB(self, _("Activate the tutor's help"), ly) self.gbTutor.setCheckable(True) self.gbTutor.setStyleSheet(gb_style) lb = Controles.LB(self, _("It is showed") + ":").ponFuente(font) self.cbThoughtOp = Controles.CB(self, liThinks, -1).ponFuente(font) lbArrows = Controles.LB2P(self, _("Arrows to show")).ponFuente(font) self.sbArrows = Controles.SB(self, 7, 0, 999).tamMaximo(50).ponFuente(font) ly = Colocacion.H().control(lb).control(self.cbThoughtOp).relleno() ly.control(lbArrows).control(self.sbArrows).relleno() gbThoughtOp = Controles.GB(self, _("Opponent's thought information"), ly) gbThoughtOp.setStyleSheet(gb_style) ly = Colocacion.V().espacio(16).control( self.gbTutor).control(gbThoughtOp) ly.espacio(16).control(self.chbSummary).control( self.chbTakeback).margen(6) nueva_tab(ly, _("Help configuration")) # ################################################################################################################################## # TAB Tiempo # ################################################################################################################################## lyG = nuevoG() self.lbMinutos = Controles.LB(self, _("Total minutes") + ":").ponFuente(font) self.edMinutos = Controles.ED(self).tipoFloat(10.0).ponFuente( font).anchoFijo(50) self.edSegundos, self.lbSegundos = QTUtil2.spinBoxLB( self, 6, -999, 999, maxTam=54, etiqueta=_("Seconds added per move"), fuente=font) self.edMinExtra, self.lbMinExtra = QTUtil2.spinBoxLB( self, 0, -999, 999, maxTam=70, etiqueta=_("Extra minutes for the player"), fuente=font) self.edZeitnot, self.lbZeitnot = QTUtil2.spinBoxLB( self, 0, -999, 999, maxTam=54, etiqueta=_("Zeitnot: alarm sounds when remaining seconds"), fuente=font) lyH = Colocacion.H() lyH.control(self.lbMinutos).control(self.edMinutos).espacio(30) lyH.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(lyH).otro(lyH2).otro(lyH3) self.chbTiempo = _label(lyG, _("Activate the time control"), ly, siCheck=True) nueva_tab(lyG, _("Time")) # ################################################################################################################################## # TAB Initial moves # ################################################################################################################################## lyG = nuevoG() # Posicion self.btPosicion = (Controles.PB( self, " " * 5 + _("Change") + " " * 5, self.posicionEditar).ponPlano(False).ponFuente(font)) self.fen = "" self.btPosicionQuitar = Controles.PB( self, "", self.posicionQuitar).ponIcono(Iconos.Motor_No()).ponFuente(font) self.btPosicionPegar = (Controles.PB( self, "", self.posicionPegar).ponIcono(Iconos.Pegar16()).ponToolTip( _("Paste FEN position"))).ponFuente(font) hbox = (Colocacion.H().relleno().control( self.btPosicionQuitar).control(self.btPosicion).control( self.btPosicionPegar).relleno()) _label(lyG, _("Start position"), hbox) # Openings self.btOpening = (Controles.PB( self, " " * 5 + _("Undetermined") + " " * 5, self.editOpening).ponPlano(False).ponFuente(font)) self.opening_block = None self.btOpeningsFavoritas = Controles.PB( self, "", self.preferred_openings).ponIcono(Iconos.Favoritos()) self.btOpeningsQuitar = Controles.PB( self, "", self.aperturasQuitar).ponIcono(Iconos.Motor_No()) hbox = (Colocacion.H().relleno().control( self.btOpeningsQuitar).control(self.btOpening).control( self.btOpeningsFavoritas).relleno()) _label(lyG, _("Opening"), hbox) # Libros fvar = self.configuration.file_books self.list_books = Books.ListBooks() self.list_books.restore_pickle(fvar) self.list_books.check() li_books = [(x.name, x) for x in self.list_books.lista] libInicial = li_books[0][1] if li_books else None li_resp_book = [ (_("Selected by the player"), "su"), (_("Uniform random"), "au"), (_("Proportional random"), "ap"), (_("Always the highest percentage"), "mp"), ] ## Rival self.cbBooksR = QTUtil2.comboBoxLB(self, li_books, libInicial).ponFuente(font) self.btNuevoBookR = Controles.PB(self, "", self.nuevoBook, plano=True).ponIcono(Iconos.Mas(), icon_size=16) self.cbBooksRR = QTUtil2.comboBoxLB(self, li_resp_book, "mp").ponFuente(font) self.lbDepthBookR = Controles.LB2P(self, _("Max depth")).ponFuente(font) self.edDepthBookR = Controles.ED(self).ponFuente(font).tipoInt( 0).anchoFijo(30) hbox = (Colocacion.H().control(self.cbBooksR).control( self.btNuevoBookR).relleno().control( self.cbBooksRR).relleno().control(self.lbDepthBookR).control( self.edDepthBookR)) self.chbBookR = _label(lyG, "%s: %s" % (_("Activate book"), _("Opponent")), hbox, siCheck=True) ## Player self.cbBooksP = QTUtil2.comboBoxLB(self, li_books, libInicial).ponFuente(font) self.btNuevoBookP = Controles.PB(self, "", self.nuevoBook, plano=True).ponIcono(Iconos.Mas(), icon_size=16) self.lbDepthBookP = Controles.LB2P(self, _("Max depth")).ponFuente(font) self.edDepthBookP = Controles.ED(self).ponFuente(font).tipoInt( 0).anchoFijo(30) hbox = (Colocacion.H().control(self.cbBooksP).control( self.btNuevoBookP).relleno().control(self.lbDepthBookP).control( self.edDepthBookP)) self.chbBookP = _label( lyG, "%s: %s" % (_("Activate book"), self.configuration.nom_player()), hbox, siCheck=True) nueva_tab(lyG, _("Initial moves")) # ################################################################################################################################## # TAB avanzada # ################################################################################################################################## lyG = nuevoG() liAjustes = self.personalidades.listaAjustes(True) self.cbAjustarRival = (Controles.CB( self, liAjustes, ADJUST_BETTER).capture_changes( self.ajustesCambiado).ponFuente(font)) lbAjustarRival = Controles.LB2P(self, _("Set strength")).ponFuente(font) self.btAjustarRival = (Controles.PB(self, _("Personality"), self.cambiaPersonalidades, plano=True).ponIcono( Iconos.Mas(), icon_size=16).ponFuente(font)) # ## Resign lbResign = Controles.LB2P(self, _("Resign/draw by engine")).ponFuente(font) liResign = ( (_("Very early"), -100), (_("Early"), -300), (_("Average"), -500), (_("Late"), -800), (_("Very late"), -1000), (_("Never"), -9999999), ) self.cbResign = Controles.CB(self, liResign, -800).ponFuente(font) self.lb_path_engine = Controles.LB(self, "").set_wrap() o_columns = Columnas.ListaColumnas() o_columns.nueva("OPTION", _("UCI option"), 240, centered=True) o_columns.nueva("VALUE", _("Value"), 200, centered=True, edicion=Delegados.MultiEditor(self)) self.grid_uci = Grid.Grid(self, o_columns, siEditable=True) self.grid_uci.ponFuente(font) self.register_grid(self.grid_uci) lyH2 = (Colocacion.H().control(lbAjustarRival).control( self.cbAjustarRival).control(self.btAjustarRival).relleno()) lyH3 = Colocacion.H().control(lbResign).control( self.cbResign).relleno() ly = Colocacion.V().otro(lyH2).otro(lyH3).espacio(16).control( self.lb_path_engine).control(self.grid_uci) _label(lyG, _("Opponent"), ly) nueva_tab(lyG, _("Advanced")) layout = Colocacion.V().control(tb).control(tab).relleno().margen(3) self.setLayout(layout) self.li_preferred_openings = [] self.btOpeningsFavoritas.hide() file = self.configuration.ficheroEntMaquina if self.direct_option else self.configuration.ficheroEntMaquinaPlay if not os.path.isfile(file): file = self.configuration.ficheroEntMaquina dic = Util.restore_pickle(file) if not dic: dic = {} self.restore_dic(dic) self.ajustesCambiado() # self.ayudasCambiado() self.ponRival() self.restore_video()
def borrar(self): tam_dbop = len(self.dbop) if tam_dbop == 0: return current = self.glines.recno() // 2 li = [] if 0 <= current < tam_dbop: li.append([ "current", _("Remove line %d") % (current + 1, ), Iconos.Mover() ]) if tam_dbop > 1: li.append( ["lines", _("Remove a list of lines"), Iconos.MoverLibre()]) if len(li) > 0: menu = QTVarios.LCMenu(self) for key, title, ico in li: menu.opcion(key, title, ico) menu.separador() resp = menu.lanza() if resp == "current": del self.dbop[current] self.goto_inilinea() else: liGen = [FormLayout.separador] config = FormLayout.Editbox( "<div align=\"right\">" + _("Lines") + "<br>" + _("By example:") + " -5,8-12,14,19-", rx="[0-9,\-,\,]*") liGen.append((config, "")) resultado = FormLayout.fedit(liGen, title=_("Remove a list of lines"), parent=self, anchoMinimo=460, icon=Iconos.OpeningLines()) if resultado: accion, liResp = resultado clista = liResp[0] if clista: ln = Util.ListaNumerosImpresion(clista) li = ln.selected(range(1, tam_dbop + 1)) sli = [] cad = "" for num in li: if cad: cad += "," + str(num) else: cad = str(num) if len(cad) > 80: sli.append(cad) cad = "" if cad: sli.append(cad) cli = "\n".join(sli) if QTUtil2.pregunta( self, _("Do you want to remove the next lines?") + "\n\n" + cli): li.sort(reverse=True) um = QTUtil2.unMomento(self, _("Working...")) for num in li: del self.dbop[num - 1] self.glines.refresh() self.goto_inilinea() um.final()
def tg_borrar(self): nameGuide = self.selectOther() if nameGuide: if QTUtil2.pregunta(self, _X(_("Delete %1?"), nameGuide)): self.bookGuide.removeOther(nameGuide)
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.ListaAperturasStd(VarGen.configuracion, False, False) 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))
def createTactics(self): nameTactic = os.path.basename(self.entreno)[:-4] nomDir = os.path.join(self.configuracion.dirPersonalTraining, "Tactics", nameTactic) if os.path.isdir(nomDir): nom = nomDir + "-%d" n = 1 while os.path.isdir(nom % n): n += 1 nomDir = nom % n nomIni = os.path.join(nomDir, "Config.ini") nomTactic = "TACTIC1" nomDirTac = os.path.join(VarGen.configuracion.dirPersonalTraining, "Tactics") Util.creaCarpeta(nomDirTac) Util.creaCarpeta(nomDir) nomFNS = os.path.join(nomDir, "Puzzles.fns") # Se leen todos los fens f = open(self.entreno) liBase = [] for linea in f: liBase.append(linea.strip()) f.close() # Se crea el fichero con los puzzles f = codecs.open(nomFNS, "w", "utf-8", 'ignore') nregs = len(liBase) tmpBP = QTUtil2.BarraProgreso(self.pantalla, nameTactic, _("Working..."), nregs) tmpBP.mostrar() for n in range(nregs): if tmpBP.siCancelado(): break tmpBP.pon(n + 1) linea = liBase[n] li = linea.split("|") fen = li[0] if len(li) < 3 or not li[2]: # tutor a trabajar mrm = self.xrival.analiza(fen) if not mrm.liMultiPV: continue rm = mrm.liMultiPV[0] p = Partida.Partida(fen=fen) p.leerPV(rm.pv) pts = rm.puntosABS() jg = p.jugada(0) for pos, rm1 in enumerate(mrm.liMultiPV): if pos: if rm1.puntosABS() == pts: p1 = Partida.Partida(fen=fen) p1.leerPV(rm1.pv) if pos > 1: jg.variantes += "\n" jg.variantes += p1.pgnBaseRAW() else: break jugadas = p.pgnBaseRAW() txt = fen + "||%s\n" % jugadas else: txt = linea f.write(txt) f.close() tmpBP.cerrar() # Se crea el fichero de control dicIni = {} dicIni[nomTactic] = d = {} d["MENU"] = nameTactic d["FILESW"] = "%s:100" % os.path.basename(nomFNS) Util.dic8ini(nomIni, dicIni) QTUtil2.mensaje( self.pantalla, _X(_("Tactic training %1 created."), nomDir) + "<br>" + _X( _("You can access this training from menu Trainings-Learn tactics by repetition-%1" ), nomDir)) self.procesador.entrenamientos.rehaz()
def createGuide(self): name = os.path.basename(self.dbGames.nomFichero)[:-4] maxdepth = self.dbGames.depthStat() depth = maxdepth minGames = min(self.dbGames.all_reccount() * 10 / 100, 5) pointview = 2 inicio = 0 mov = self.movActivo() while True: liGen = [(None, None)] liGen.append((_("Name") + ":", name)) liGen.append((FormLayout.Spinbox(_("Depth"), 2, maxdepth, 50), depth)) liGen.append((None, None)) liGen.append((FormLayout.Spinbox(_("Minimum games"), 1, 99, 50), minGames)) liGen.append((None, None)) liPointV = [ pointview, (0, _("White")), (1, _("Black")), (2, "%s + %s" % (_("White"), _("Draw"))), (3, "%s + %s" % (_("Black"), _("Draw"))), ] liGen.append((_("Point of view") + ":", liPointV)) liGen.append((None, None)) if mov: liInicio = [ inicio, (0, _("The beginning")), (1, _("Current move")), ] liGen.append((_("Start from") + ":", liInicio)) resultado = FormLayout.fedit(liGen, title=_("Create new guide"), parent=self, anchoMinimo=460, icon=Iconos.TutorialesCrear()) if resultado is None: return accion, liResp = resultado name = liResp[0].strip() if not name: return depth = liResp[1] minGames = liResp[2] pointview = liResp[3] if mov: inicio = liResp[4] ok = True for una in self.bookGuide.getTodas(): if una.strip().upper() == name.upper(): QTUtil2.mensError(self, _("The name is repeated")) ok = False continue if ok: break # Grabamos um = QTUtil2.unMomento(self) # Read stats siWhite = pointview % 2 == 0 siDraw = pointview > 1 pv = "" if mov: if inicio > 0: pv = self.pvBase + " " + mov["pvmove"] pv = pv.strip() fichPVs = self.dbGames.flistAllpvs(depth, minGames, siWhite, siDraw, pv) # Write to bookGuide self.bookGuide.grabarFichSTAT(name, fichPVs) # BookGuide self.wmoves.inicializa() um.final()
def player_has_moved(self, from_sq, to_sq, promotion=""): jgUsu = self.check_human_move(from_sq, to_sq, promotion) if not jgUsu: return False movimiento = jgUsu.movimiento() position = self.game.last_position isValid = self.motorGM.is_valid_move(movimiento) analysis = None if not isValid: self.board.set_position(position) self.board.activate_side(self.human_side) li_moves = self.motorGM.get_moves_txt(position, True) desdeGM, hastaGM, promotionGM = WindowGM.select_move( self, li_moves, True) siAnalizaJuez = self.with_adjudicator if siAnalizaJuez: if self.book: fen = self.last_fen() siH = self.book.check_human(fen, from_sq, to_sq) is_gm = self.book.check_human(fen, desdeGM, hastaGM) if is_gm and siH: siAnalizaJuez = False else: self.book = False else: siAnalizaJuez = ( self.with_adjudicator and self.mostrar is None ) # None es ver siempre False no ver nunca True ver si diferentes if len(movimiento) == 5: promotion = movimiento[4].lower() desdeGM, hastaGM, promotionGM = from_sq, to_sq, promotion ok, mens, jgGM = Move.get_game_move(self.game, position, desdeGM, hastaGM, promotionGM) movGM = jgGM.pgn_translated() movUsu = jgUsu.pgn_translated() if siAnalizaJuez: um = QTUtil2.analizando(self.main_window) mrm = self.analizaMinimo(self.vtime * 100) import time t = time.time() rmUsu, nada = mrm.buscaRM(jgUsu.movimiento()) if rmUsu is None: um = QTUtil2.analizando(self.main_window) self.analizaFinal() rmUsu = self.xtutor.valora(position, from_sq, to_sq, promotion) mrm.agregaRM(rmUsu) self.analizaInicio() um.final() rmGM, pos_gm = mrm.buscaRM(jgGM.movimiento()) if rmGM is None: self.analizaFinal() rmGM = self.xtutor.valora(position, desdeGM, hastaGM, promotionGM) pos_gm = mrm.agregaRM(rmGM) self.analizaInicio() um.final() analysis = mrm, pos_gm dpts = rmUsu.centipawns_abs() - rmGM.centipawns_abs() if self.mostrar is None or ((self.mostrar is True) and not isValid): w = WindowJuicio.WJuicio( self, self.xtutor, self.nombreGM, position, mrm, rmGM, rmUsu, analysis, is_competitive=not self.show_evals, ) w.exec_() rm, pos_gm = w.analysis[0].buscaRM(jgGM.movimiento()) analysis = w.analysis[0], pos_gm dpts = w.difPuntos() self.puntos += dpts comentario0 = "<b>%s</b> : %s = %s<br>" % ( self.configuration.x_player, movUsu, rmUsu.texto()) comentario0 += "<b>%s</b> : %s = %s<br>" % (self.nombreGM, movGM, rmGM.texto()) comentario1 = "<br><b>%s</b> = %+d<br>" % (_("Difference"), dpts) comentario2 = "<b>%s</b> = %+d<br>" % (_("Points accumulated"), self.puntos) self.textoPuntuacion = comentario2 self.ponRotuloSecundario() if not isValid: jgGM.comment = ((comentario0 + comentario1 + comentario2).replace("<b>", "").replace( "</b>", "").replace("<br>", "\n")) self.analizaFinal() self.move_the_pieces(jgGM.liMovs) jgGM.analysis = analysis self.add_move(jgGM, True) self.error = "" self.play_next_move() return True
def __init__(self, oBase, ventana, segundosPensando, siBlancas, cPuntos, maxRecursion): super(WAnalisisVariantes, self).__init__(ventana) self.oBase = oBase # Creamos los controles self.setWindowTitle(_("Variants")) self.setWindowFlags(QtCore.Qt.Dialog | QtCore.Qt.WindowMinimizeButtonHint) self.setWindowIcon(Iconos.Tutor()) f = Controles.TipoLetra(puntos=12, peso=75) flb = Controles.TipoLetra(puntos=10) lbPuntuacionAnterior = Controles.LB( self, cPuntos).alinCentrado().ponFuente(flb) self.lbPuntuacionNueva = Controles.LB(self).alinCentrado().ponFuente( flb) confTablero = VarGen.configuracion.confTablero("ANALISISVARIANTES", 32) self.tablero = Tablero.Tablero(self, confTablero) self.tablero.crea() self.tablero.ponerPiezasAbajo(siBlancas) self.tableroT = Tablero.Tablero(self, confTablero) self.tableroT.crea() self.tableroT.ponerPiezasAbajo(siBlancas) btTerminar = Controles.PB(self, _("Close"), self.close).ponPlano(False) btReset = Controles.PB(self, _("Another change"), oBase.reset).ponIcono( Iconos.MoverLibre()).ponPlano(False) liMasAcciones = (("FEN:%s" % _("Copy to clipboard"), "MoverFEN", Iconos.Clip()), ) lytbTutor, self.tb = QTVarios.lyBotonesMovimiento( self, "", siLibre=maxRecursion > 0, liMasAcciones=liMasAcciones) self.maxRecursion = maxRecursion - 1 self.segundos, lbSegundos = QTUtil2.spinBoxLB(self, segundosPensando, 1, 999, maxTam=40, etiqueta=_("Second(s)")) # Creamos los layouts lyVariacion = Colocacion.V().control(lbPuntuacionAnterior).control( self.tablero) gbVariacion = Controles.GB(self, _("Proposed change"), lyVariacion).ponFuente(f).alinCentrado() lyTutor = Colocacion.V().control(self.lbPuntuacionNueva).control( self.tableroT) gbTutor = Controles.GB(self, _("Tutor's prediction"), lyTutor).ponFuente(f).alinCentrado() lyBT = Colocacion.H().control(btTerminar).control( btReset).relleno().control(lbSegundos).control(self.segundos) layout = Colocacion.G().control(gbVariacion, 0, 0).control(gbTutor, 0, 1) layout.otro(lyBT, 1, 0).otro(lytbTutor, 1, 1) self.setLayout(layout) self.move(ventana.x() + 20, ventana.y() + 20)
def trainUpdate(self): self.dbop.updateTraining() QTUtil2.mensaje(self, _("The trainings have been updated"))
def __init__(self, procesador, siWoman): self.configuracion = procesador.configuracion self.procesador = procesador self.siWoman = siWoman self.dbHisto = Util.DicSQL(self.configuracion.ficheroGMhisto) self.bloqueApertura = None self.liAperturasFavoritas = [] wParent = procesador.pantalla if siWoman: titulo = _("Play like a Woman Grandmaster") icono = Iconos.WGranMaestro() else: titulo = _("Play like a Grandmaster") icono = Iconos.GranMaestro() extparam = "gm" QTVarios.WDialogo.__init__(self, wParent, titulo, icono, extparam) flb = Controles.TipoLetra(puntos=10) # Toolbar liAcciones = [(_("Accept"), Iconos.Aceptar(), self.aceptar), None, (_("Cancel"), Iconos.Cancelar(), self.cancelar), None, (_("One game"), Iconos.Uno(), self.unJuego), None, (_("Import"), Iconos.ImportarGM(), self.importar) ] tb = Controles.TBrutina(self, liAcciones) # Grandes maestros self.liGM = GM.listaGM(siWoman) li = [(x[0], x[1]) for x in self.liGM] li.insert(0, ("-", None)) self.cbGM = QTUtil2.comboBoxLB(self, li, li[0][1] if len(self.liGM) == 0 else li[1][1]) self.cbGM.capturaCambiado(self.compruebaGM) hbox = Colocacion.H().relleno().control(self.cbGM).relleno() gbGM = Controles.GB(self, _("Choose a Grandmaster"), hbox).ponFuente(flb) # Personales self.liPersonal = GM.listaGMpersonal(self.procesador.configuracion.dirPersonalTraining) if self.liPersonal: li = [(x[0], x[1]) for x in self.liPersonal] li.insert(0, ("-", None)) self.cbPersonal = QTUtil2.comboBoxLB(self, li, li[0][1]) self.cbPersonal.capturaCambiado(self.compruebaP) btBorrar = Controles.PB(self, "", self.borrarPersonal, plano=False).ponIcono(Iconos.Borrar(), tamIcon=16) hbox = Colocacion.H().relleno().control(self.cbPersonal).control(btBorrar).relleno() gbPersonal = Controles.GB(self, _("Personal games"), hbox).ponFuente(flb) # Color self.rbBlancas = Controles.RB(self, _("White"), rutina=self.compruebaColor) self.rbBlancas.activa(True) self.rbNegras = Controles.RB(self, _("Black"), rutina=self.compruebaColor) self.rbNegras.activa(False) # Contrario self.chContrario = Controles.CHB(self, _("Choose the opponent's move, when there are multiple possible answers"), False) # Juez liDepths = [("--", 0)] for x in range(1, 31): liDepths.append((str(x), x)) self.liMotores = self.configuracion.comboMotoresMultiPV10() self.cbJmotor, self.lbJmotor = QTUtil2.comboBoxLB(self, self.liMotores, self.configuracion.tutorInicial, _("Engine")) self.edJtiempo = Controles.ED(self).tipoFloat().ponFloat(1.0).anchoFijo(50) self.lbJtiempo = Controles.LB2P(self, _("Time in seconds")) self.cbJdepth = Controles.CB(self, liDepths, 0).capturaCambiado(self.cambiadoDepth) self.lbJdepth = Controles.LB2P(self, _("Depth")) self.lbJshow = Controles.LB2P(self, _("Show rating")) self.chbEvals = Controles.CHB(self, _("Show all evaluations"), False) liOptions = [(_("All moves"), None), (_("Moves are different"), True), (_("Never"), False)] self.cbJshow = Controles.CB(self, liOptions, True) self.lbJmultiPV = Controles.LB2P(self, _("Number of moves evaluated by engine(MultiPV)")) li = [(_("Default"), "PD"), (_("Maximum"), "MX")] for x in (1, 3, 5, 10, 15, 20, 30, 40, 50, 75, 100, 150, 200): li.append((str(x), str(x))) self.cbJmultiPV = Controles.CB(self, li, "PD") # Inicial self.edJugInicial, lbInicial = QTUtil2.spinBoxLB(self, 1, 1, 99, etiqueta=_("Initial move"), maxTam=40) # 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] li.insert(0, ("--", None)) self.cbBooks, lbBooks = QTUtil2.comboBoxLB(self, li, None, _("Bypass moves in the book")) # Aperturas self.btApertura = Controles.PB(self, " " * 5 + _("Undetermined") + " " * 5, self.aperturasEditar).ponPlano( False) self.btAperturasFavoritas = Controles.PB(self, "", self.aperturasFavoritas).ponIcono(Iconos.Favoritos()) self.btAperturasQuitar = Controles.PB(self, "", self.aperturasQuitar).ponIcono(Iconos.Motor_No()) hbox = Colocacion.H().control(self.btAperturasQuitar).control(self.btApertura).control( self.btAperturasFavoritas).relleno() gbOpening = Controles.GB(self, _("Opening"), hbox) # gbBasic # # Color hbox = Colocacion.H().relleno().control(self.rbBlancas).espacio(10).control(self.rbNegras).relleno() gbColor = Controles.GB(self, _("Play with"), hbox).ponFuente(flb) # Tiempo ly1 = Colocacion.H().control(self.lbJmotor).control(self.cbJmotor).control(self.lbJshow).control( self.cbJshow).relleno() ly2 = Colocacion.H().control(self.lbJtiempo).control(self.edJtiempo) ly2.control(self.lbJdepth).control(self.cbJdepth).espacio(15).control(self.chbEvals).relleno() ly3 = Colocacion.H().control(self.lbJmultiPV).control(self.cbJmultiPV).relleno() ly = Colocacion.V().otro(ly1).otro(ly2).otro(ly3) self.gbJ = Controles.GB(self, _("Adjudicator"), ly).conectar(self.cambiaJuez) # Opciones vlayout = Colocacion.V().control(gbColor) vlayout.espacio(5).control(self.gbJ) vlayout.margen(20) gbBasic = Controles.GB(self, "", vlayout) gbBasic.setFlat(True) # Opciones avanzadas lyInicial = Colocacion.H().control(lbInicial).control(self.edJugInicial).relleno().control(lbBooks).control( self.cbBooks).relleno() vlayout = Colocacion.V().relleno().otro(lyInicial).control(gbOpening) vlayout.espacio(5).control(self.chContrario).margen(20).relleno() gbAdvanced = Controles.GB(self, "", vlayout) gbAdvanced.setFlat(True) # Historico self.liHisto = [] oColumnas = Columnas.ListaColumnas() oColumnas.nueva("FECHA", _("Date"), 80, siCentrado=True) oColumnas.nueva("PACIERTOS", _("Hints"), 90, siCentrado=True) oColumnas.nueva("PUNTOS", _("Points accumulated"), 120, siCentrado=True) oColumnas.nueva("ENGINE", _("Adjudicator"), 100, siCentrado=True) oColumnas.nueva("RESUMEN", _("Game played"), 150) self.grid = grid = Grid.Grid(self, oColumnas, siSelecFilas=True, background=None) self.grid.coloresAlternados() self.registrarGrid(grid) # Tabs self.tab = Controles.Tab().ponPosicion("S") self.tab.nuevaTab(gbBasic, _("Basic")) self.tab.nuevaTab(gbAdvanced, _("Advanced")) self.tab.nuevaTab(self.grid, _("Track record")) # Cabecera lyCab = Colocacion.H().control(gbGM) if self.liPersonal: lyCab.control(gbPersonal) layout = Colocacion.V().control(tb).otro(lyCab).control(self.tab).margen(3) self.setLayout(layout) self.recuperaDic() self.cambiaJuez() self.compruebaGM() self.compruebaP() self.compruebaHisto() self.aperturaMuestra() self.btAperturasFavoritas.hide() self.recuperarVideo(anchoDefecto=450)
def generarStandard(self, ventana, siBasic): oLista = AperturasStd.apTrain dic = oLista.dic titulo = _("Openings") tmpBP2 = QTUtil2.BarraProgreso2(ventana, titulo) tf = len(dic) tmpBP2.ponTotal(1, tf) tmpBP2.ponRotulo(1, "1. " + _X(_("Reading %1"), titulo)) tmpBP2.ponTotal(2, tf) tmpBP2.ponRotulo(2, "") tmpBP2.mostrar() liRegs = [] dRegs = {} # se guarda una lista con los pv, para determinar el padre for nR, k in enumerate(oLista.dic): tmpBP2.pon(1, nR) tmpBP2.siCancelado() ae = oLista.dic[k] if siBasic and not ae.siBasic: continue liPV = ae.a1h8.split(" ") ult = len(liPV) - 1 seqFather = "" cp = ControlPosicion.ControlPosicion() cp.posInicial() for pos, pv in enumerate(liPV): desde, hasta, coronacion = pv[:2], pv[2:4], pv[4:] seq = seqFather + LCEngine.pv2xpv(pv) cp.mover(desde, hasta, coronacion) if seq not in dRegs: reg = SQLDBF.Almacen() reg.XPV = seq reg.PV = pv reg.FEN = cp.fen() reg.COMMENT = ae.trNombre if pos == ult else "" self.ultPos += 1 reg.POS = self.ultPos liRegs.append(reg) dRegs[seq] = reg seqFather = seq tmpBP2.ponRotulo(2, "2. " + _X(_("Converting %1"), titulo)) tmpBP2.ponTotal(2, len(liRegs)) select = "XPV,PV,COMMENT,FEN,POS" dbf = SQLDBF.DBF(self.conexion, self.tablaDatos, select) def dispatch(num): tmpBP2.pon(2, num) tmpBP2.siCancelado() dbf.insertarLista(liRegs, dispatch) dbf.cerrar() tmpBP2.cerrar()
def mueveHumano(self, desde, hasta, coronacion=""): jgUsu = self.checkMueveHumano(desde, hasta, coronacion) if not jgUsu: return False self.tiempo += time.time() - self.iniTiempo jgObj = self.partidaObj.jugada(self.posJugadaObj) siAnalizaJuez = True if self.book: fen = self.fenUltimo() siBookUsu = self.book.compruebaHumano(fen, desde, hasta) siBookObj = self.book.compruebaHumano(fen, jgObj.desde, jgObj.hasta) if siBookUsu and siBookObj: if jgObj.movimiento() != jgUsu.movimiento(): bmove = _("book move") comentario = "%s: %s %s<br>%s: %s %s" % ( self.nombreObj, jgObj.pgnSP(), bmove, self.configuracion.jugador, jgUsu.pgnSP(), bmove) w = PantallaJuicio.MensajeF(self.pantalla, comentario) w.mostrar() siAnalizaJuez = False else: siAnalizaJuez = True if not siBookObj: self.book = None analisis = None comentario = None if siAnalizaJuez: um = QTUtil2.analizando(self.pantalla) pvUsu = jgUsu.movimiento() pvObj = jgObj.movimiento() mrm = self.analizaMinimo(pvUsu, pvObj) posicion = self.partida.ultPosicion rmUsu, nada = mrm.buscaRM(pvUsu) rmObj, posObj = mrm.buscaRM(pvObj) analisis = mrm, posObj um.final() w = PantallaJuicio.WJuicio(self, self.xanalyzer, self.nombreObj, posicion, mrm, rmObj, rmUsu, analisis) w.exec_() analisis = w.analisis if w.siAnalisisCambiado: self.siSave = True dpts = w.difPuntos() self.puntos += dpts dptsMax = w.difPuntosMax() self.puntosMax += dptsMax comentarioUsu = " %s" % (rmUsu.abrTexto()) comentarioObj = " %s" % (rmObj.abrTexto()) comentarioPuntos = "%s = %d %+d %+d = %d" % ( _("Points"), self.puntos - dpts, rmUsu.puntosABS(), -rmObj.puntosABS(), self.puntos) comentario = "%s: %s %s\n%s: %s %s\n%s" % ( self.nombreObj, jgObj.pgnSP(), comentarioObj, self.configuracion.jugador, jgUsu.pgnSP(), comentarioUsu, comentarioPuntos) self.ponPuntos() self.analizaFinal() self.masJugada(True, analisis, comentario) self.siguienteJugada() return True
def ta_massive(self): dicVar = self.configuracion.leeVariables("MASSIVE_OLINES") liGen = [FormLayout.separador] config = FormLayout.Combobox( _("Engine"), self.configuracion.comboMotoresMultiPV10(4)) liGen.append((config, dicVar.get("ENGINE", self.configuracion.tutor))) liGen.append( (_("Duration of engine analysis (secs)") + ":", dicVar.get("SEGUNDOS", float(self.configuracion.tiempoTutor / 1000.0)))) liDepths = [("--", 0)] for x in range(1, 51): liDepths.append((str(x), x)) config = FormLayout.Combobox(_("Depth"), liDepths) liGen.append((config, dicVar.get("DEPTH", self.configuracion.depthTutor))) li = [(_("Maximum"), 0)] for x in (1, 3, 5, 10, 15, 20, 30, 40, 50, 75, 100, 150, 200): li.append((str(x), x)) config = FormLayout.Combobox( _("Number of moves evaluated by engine(MultiPV)"), li) liGen.append( (config, dicVar.get("MULTIPV", self.configuracion.tutorMultiPV))) liGen.append(FormLayout.separador) liGen.append( (_("Redo any existing prior analyses (if they exist)") + ":", dicVar.get("REDO", False))) resultado = FormLayout.fedit(liGen, title=_("Mass analysis"), parent=self, anchoMinimo=460, icon=Iconos.Analizar()) if resultado is None: return claveMotor, tiempo, depth, multiPV, redo = resultado[1] ms = int(tiempo * 1000) if ms == 0 and depth == 0: return dicVar["ENGINE"] = claveMotor dicVar["SEGUNDOS"] = tiempo dicVar["DEPTH"] = depth dicVar["MULTIPV"] = multiPV dicVar["REDO"] = redo self.configuracion.escVariables("MASSIVE_OLINES", dicVar) um = QTUtil2.unMomento(self) stFensM2 = self.dbop.getAllFen() if redo == False: liBorrar = [] for fenM2 in stFensM2: dic = self.dbop.getfenvalue(fenM2) if "ANALISIS" in dic: liBorrar.append(fenM2) for fenM2 in liBorrar: stFensM2.remove(fenM2) conf_engine = copy.deepcopy(self.configuracion.buscaMotor(claveMotor)) conf_engine.actMultiPV(multiPV) xgestor = self.procesador.creaGestorMotor(conf_engine, ms, depth, True) um.final() mensaje = _("Move") + " %d/" + str(len(stFensM2)) tmpBP = QTUtil2.BarraProgreso(self, _("Mass analysis"), "", len(stFensM2)) done = 0 for n, fenM2 in enumerate(stFensM2, 1): if tmpBP.siCancelado(): break tmpBP.inc() tmpBP.mensaje(mensaje % n) mrm = xgestor.analiza(fenM2 + " 0 1") dic = self.dbop.getfenvalue(fenM2) dic["ANALISIS"] = mrm self.dbop.setfenvalue(fenM2, dic) done += 1 tmpBP.cerrar()
def export(self): resp = QTUtil2.salvaFichero(self, _("CSV file"), Code.configuracion.x_save_folder, _("File") + " csv (*.csv)", True) if resp: self.sts.writeCSV(resp)
def polyglotUnir(owner): lista = [(None, None)] dict1 = {"FICHERO": "", "EXTENSION": "bin", "SISAVE": False} lista.append((_("File") + " 1 :", dict1)) dict2 = {"FICHERO": "", "EXTENSION": "bin", "SISAVE": False} lista.append((_("File") + " 2 :", dict2)) dictr = {"FICHERO": "", "EXTENSION": "bin", "SISAVE": True} lista.append((_("Book to create") + ":", dictr)) while True: resultado = FormLayout.fedit(lista, title=_("Merge two books in one"), parent=owner, anchoMinimo=460, icon=Iconos.Libros()) if resultado: resultado = resultado[1] error = None f1 = resultado[0] f2 = resultado[1] fr = resultado[2] if (not f1) or (not f2) or (not fr): error = _("Not indicated all files") elif f1 == f2: error = _("File") + " 1 = " + _("File") + " 2" elif f1 == fr: error = _("File") + " 1 = " + _("Book to create") elif f2 == fr: error = _("File") + " 2 = " + _("Book to create") if error: dict1["FICHERO"] = f1 dict2["FICHERO"] = f2 dictr["FICHERO"] = fr QTUtil2.mensError(owner, error) continue else: return if VarGen.isWindows: exe = 'Engines/Windows/_tools/polyglot/polyglot.exe' else: exe = 'Engines/Linux/_tools/polyglot/polyglot' li = [ os.path.abspath(exe), 'merge-book', "-in1", f1, "-in2", f2, "-out", fr ] try: os.remove(fr) except: pass # Ejecutamos me = QTUtil2.unMomento(owner) process = subprocess.Popen(li, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # Mostramos el resultado txt = process.stdout.read() if os.path.isfile(fr): txt += "\n" + _X(_("Book created : %1"), fr) me.final() QTUtil2.mensaje(owner, txt) return
def __init__(self, wParent, sts, work): super(WWork, self).__init__(wParent) self.work = work self.setWindowTitle(work.pathToExe()) self.setWindowIcon(Iconos.Motor()) self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.Dialog | QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowMaximizeButtonHint) tb = QTUtil2.tbAcceptCancel(self) # Tabs tab = Controles.Tab() # Tab-basic -------------------------------------------------- lbRef = Controles.LB(self, _("Reference") + ": ") self.edRef = Controles.ED(self, work.ref).anchoMinimo(360) lbInfo = Controles.LB(self, _("Information") + ": ") self.emInfo = Controles.EM(self, work.info, siHTML=False).anchoMinimo(360).altoFijo(60) lbDepth = Controles.LB(self, _("Maximum depth") + ": ") self.sbDepth = Controles.ED(self).tipoInt(work.depth).anchoFijo(30) lbSeconds = Controles.LB(self, _("Maximum seconds to think") + ": ") self.sbSeconds = Controles.ED(self).tipoFloat( float(work.seconds), decimales=3).anchoFijo(60) lbSample = Controles.LB(self, _("Sample") + ": ") self.sbIni = Controles.SB(self, work.ini + 1, 1, 100).capturaCambiado(self.changeSample) self.sbIni.isIni = True lbGuion = Controles.LB(self, _("to")) self.sbEnd = Controles.SB(self, work.end + 1, 1, 100).capturaCambiado(self.changeSample) self.sbEnd.isIni = False # self.lbError = Controles.LB(self).ponTipoLetra(peso=75).ponColorN("red") # self.lbError.hide() lySample = Colocacion.H().control(self.sbIni).control(lbGuion).control( self.sbEnd) ly = Colocacion.G() ly.controld(lbRef, 0, 0).control(self.edRef, 0, 1) ly.controld(lbInfo, 1, 0).control(self.emInfo, 1, 1) ly.controld(lbDepth, 2, 0).control(self.sbDepth, 2, 1) ly.controld(lbSeconds, 3, 0).control(self.sbSeconds, 3, 1) ly.controld(lbSample, 4, 0).otro(lySample, 4, 1) w = QtWidgets.QWidget() w.setLayout(ly) tab.nuevaTab(w, _("Basic data")) # Tab-Engine scrollArea = WEngines.wgen_options_engine(self, work.me) tab.nuevaTab(scrollArea, _("Engine options")) # Tab-Groups btAll = Controles.PB(self, _("All"), self.setAll, plano=False) btNone = Controles.PB(self, _("None"), self.setNone, plano=False) lyAN = Colocacion.H().control(btAll).espacio(10).control(btNone) self.liGroups = [] ly = Colocacion.G() ly.columnaVacia(1, 10) num = len(sts.groups) mitad = num / 2 + num % 2 for x in range(num): group = sts.groups.group(x) chb = Controles.CHB(self, _F(group.name), work.liGroupActive[x]) self.liGroups.append(chb) col = 0 if x < mitad else 2 fil = x % mitad ly.control(chb, fil, col) ly.otroc(lyAN, mitad, 0, numColumnas=3) w = QtWidgets.QWidget() w.setLayout(ly) tab.nuevaTab(w, _("Groups")) layout = Colocacion.V().control(tb).control(tab).margen(8) self.setLayout(layout) self.edRef.setFocus()
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 = '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()
def reiniciar(self): if self.partida.numJugadas() and QTUtil2.pregunta(self.pantalla, _("Restart the game?")): self.partida.reset() self.inicio(self.resistance, self.numEngine, self.clave)
def importarSummary(self, ventana, partidabase, ficheroSummary, depth, siWhite, onlyone, minMoves): titulo = _("Importing the summary of a database") bp = QTUtil2.BarraProgreso1(ventana, titulo) bp.ponTotal(0) bp.ponRotulo(_X(_("Reading %1"), os.path.basename(ficheroSummary))) bp.mostrar() dbSTAT = DBgames.TreeSTAT(ficheroSummary) if depth == 0: depth = 99999 pvBase = partidabase.pv() len_partidabase = len(partidabase) liPartidas = [] def hazPV(lipv_ant): if bp.siCancelado(): return n_ant = len(lipv_ant) siWhite1 = n_ant % 2 == 0 pv_ant = " ".join(lipv_ant) if n_ant else "" liChildren = dbSTAT.children(pv_ant, False) if len(liChildren) == 0 or len(lipv_ant) > depth: p = Partida.Partida() p.leerLIPV(lipv_ant) if len(p) > len_partidabase: liPartidas.append(p) bp.ponTotal(len(liPartidas)) bp.pon(len(liPartidas)) return if siWhite1 == siWhite: tt_max = 0 limax = [] for alm in liChildren: tt = alm.W + alm.B + alm.O + alm.D if tt > tt_max: tt_max = tt limax = [alm] elif tt == tt_max and not onlyone: limax.append(alm) liChildren = limax for alm in liChildren: li = lipv_ant[:] li.append(alm.move) hazPV(li) hazPV(pvBase.split(" ") if pvBase else []) bp.ponRotulo(_("Writing...")) self.guardaPartidas( "%s,%s" % (_("Database summary"), os.path.basename(ficheroSummary)), liPartidas) bp.cerrar() return True
def comprobar(self): self.stop_clock() self.pon_toolbar([self.cancelar]) for wm in self.liwm: wm.deshabilita() um = QTUtil2.analizando(self) self.liAnalisis = [] cp = Position.Position() cp.read_fen(self.fen) siError = False totalPuntos = 0 factor = 1 previo = 100 for wm in self.liwm: from_sq, to_sq, promotion = wm.resultado() if from_sq: cpNue = cp.copia() siBien, mensaje = cpNue.mover(from_sq, to_sq, promotion) wm.siCorrecto(siBien) if not siBien: wm.ponError(_("Invalid move")) siError = True break move = Move.Move(None) move.ponDatos(cp, cpNue, from_sq, to_sq, promotion) mrm, pos = self.xtutor.analyse_move(move, self.xtutor.motorTiempoJugada) move.analysis = mrm, pos self.liAnalisis.append(move) rm = mrm.li_rm[pos] rj = mrm.li_rm[0] dif = rj.centipawns_abs() - rm.centipawns_abs() if dif >= 100: puntos = 0 else: puntos = 100 - dif wm.ponPuntos(puntos) cp = cpNue totalPuntos += int(puntos * factor * previo / 100) previo = puntos * previo / 100 factor *= 2 else: break um.final() self.btConsultar.show() if not siError: self.lbTiempo.ponTexto("<h2>%s: %d %s</h2>" % (_("Result"), totalPuntos, _("pts"))) self.historico.append( Util.today(), totalPuntos, self.xtutor.clave, int(self.xtutor.motorTiempoJugada / 1000), self.min_min, self.min_max, self.linea, self.ref, ) self.pon_toolbar([self.terminar])
def importarPolyglot(self, ventana, partida, bookW, bookB, titulo, depth, siWhite, onlyone, minMoves): bp = QTUtil2.BarraProgreso1(ventana, titulo, formato1="%m") bp.ponTotal(0) bp.ponRotulo(_X(_("Reading %1"), "...")) bp.mostrar() cp = partida.ultPosicion setFen = LCEngine.setFen makeMove = LCEngine.makeMove getFen = LCEngine.getFen def hazFEN(fen, lipv_ant, control): if bp.siCancelado(): return siWhite1 = " w " in fen book = bookW if siWhite1 else bookB liPV = book.miraListaPV(fen, siWhite1 == siWhite, onlyone=onlyone) if liPV and len(lipv_ant) < depth: for pv in liPV: setFen(fen) makeMove(pv) fenN = getFen() lipv_nue = lipv_ant[:] lipv_nue.append(pv) hazFEN(fenN, lipv_nue, control) else: p = Partida.Partida() p.leerLIPV(lipv_ant) control.liPartidas.append(p) control.num_partidas += 1 bp.ponTotal(control.num_partidas) bp.pon(control.num_partidas) if control.num_partidas and control.num_partidas % 1000 == 0: self.guardaPartidas(control.rotulo, control.liPartidas, minMoves, with_history=control.with_history) control.liPartidas = [] control.with_history = False control = Util.Almacen() control.liPartidas = [] control.num_partidas = 0 control.with_history = True control.rotulo = "%s,%s,%s" % (_("Polyglot book"), bookW.nombre, bookB.nombre) hazFEN(cp.fen(), partida.lipv(), control) bp.ponRotulo(_("Writing...")) if control.liPartidas: self.guardaPartidas(control.rotulo, control.liPartidas, minMoves, with_history=control.with_history) bp.cerrar() return True
def activar(): is_linux = Code.is_linux dgt = None if is_linux: functype = ctypes.CFUNCTYPE path = os.path.join(Code.folder_OS, "DigitalBoards") if Code.configuration.x_digital_board == "DGT-gon": path_so = os.path.join(path, "libdgt.so") elif Code.configuration.x_digital_board == "Certabo": path_so = os.path.join(path, "libcer.so") elif Code.configuration.x_digital_board == "CertaboBT": path_so = os.path.join(path, "libcerBT.so") elif Code.configuration.x_digital_board == "Millennium": path_so = os.path.join(path, "libmcl.so") elif Code.configuration.x_digital_board == "Citrine": path_so = os.path.join(path, "libcit.so") else: path_so = os.path.join(path, "libucb.so") if os.path.isfile(path_so): try: dgt = ctypes.CDLL(path_so) except: dgt = None from Code.QT import QTUtil2 QTUtil2.message(None, """It is not possible to install the driver for the board, one way to solve the problem is to install the libraries: sudo apt install libqt5pas1 or sudo dnf install qt5pas-devel""") else: functype = ctypes.WINFUNCTYPE for path in ( os.path.join(Code.folder_OS, "DigitalBoards"), "", "C:/Program Files (x86)/DGT Projects/", "C:/Program Files (x86)/Common Files/DGT Projects/", "C:/Program Files/DGT Projects/", "C:/Program Files/Common Files/DGT Projects/", ): try: if Code.configuration.x_digital_board == "DGT": path_dll = os.path.join(path, "DGTEBDLL.dll") elif Code.configuration.x_digital_board == "DGT-gon": path_dll = os.path.join(path, "DGT_DLL.dll") elif Code.configuration.x_digital_board == "Certabo": path_dll = os.path.join(path, "CER_DLL.dll") elif Code.configuration.x_digital_board == "Millennium": path_dll = os.path.join(path, "MCL_DLL.dll") elif Code.configuration.x_digital_board == "Citrine": path_dll = os.path.join(path, "CIT_DLL.dll") else: path_dll = os.path.join(path, "UCB_DLL.dll") if os.path.isfile(path_dll): dgt = ctypes.WinDLL(path_dll) break except: pass if dgt is None: return False # log( "activar" ) Code.dgt = dgt cmpfunc = functype(ctypes.c_int, ctypes.c_char_p) st = cmpfunc(registerStatusFunc) dgt._DGTDLL_RegisterStatusFunc.argtype = [st] dgt._DGTDLL_RegisterStatusFunc.restype = ctypes.c_int dgt._DGTDLL_RegisterStatusFunc(st) cmpfunc = functype(ctypes.c_int, ctypes.c_char_p) st = cmpfunc(registerScanFunc) dgt._DGTDLL_RegisterScanFunc.argtype = [st] dgt._DGTDLL_RegisterScanFunc.restype = ctypes.c_int dgt._DGTDLL_RegisterScanFunc(st) cmpfunc = functype(ctypes.c_int, ctypes.c_char_p) st = cmpfunc(registerWhiteMoveInputFunc) dgt._DGTDLL_RegisterWhiteMoveInputFunc.argtype = [st] dgt._DGTDLL_RegisterWhiteMoveInputFunc.restype = ctypes.c_int dgt._DGTDLL_RegisterWhiteMoveInputFunc(st) cmpfunc = functype(ctypes.c_int, ctypes.c_char_p) st = cmpfunc(registerBlackMoveInputFunc) dgt._DGTDLL_RegisterBlackMoveInputFunc.argtype = [st] dgt._DGTDLL_RegisterBlackMoveInputFunc.restype = ctypes.c_int dgt._DGTDLL_RegisterBlackMoveInputFunc(st) dgt._DGTDLL_WritePosition.argtype = [ctypes.c_char_p] dgt._DGTDLL_WritePosition.restype = ctypes.c_int dgt._DGTDLL_ShowDialog.argtype = [ctypes.c_int] dgt._DGTDLL_ShowDialog.restype = ctypes.c_int dgt._DGTDLL_HideDialog.argtype = [ctypes.c_int] dgt._DGTDLL_HideDialog.restype = ctypes.c_int dgt._DGTDLL_WriteDebug.argtype = [ctypes.c_bool] dgt._DGTDLL_WriteDebug.restype = ctypes.c_int dgt._DGTDLL_SetNRun.argtype = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int] dgt._DGTDLL_SetNRun.restype = ctypes.c_int # Added by GON if Code.configuration.x_digital_board != "DGT": dgt._DGTDLL_GetVersion.argtype = [] dgt._DGTDLL_GetVersion.restype = ctypes.c_int Code.configuration.x_digital_board_version = dgt._DGTDLL_GetVersion() try: dgt._DGTDLL_AllowTakebacks.argtype = [ctypes.c_bool] dgt._DGTDLL_AllowTakebacks.restype = ctypes.c_int dgt._DGTDLL_AllowTakebacks(ctypes.c_bool(True)) cmpfunc = functype(ctypes.c_int) st = cmpfunc(registerWhiteTakeBackFunc) dgt._DGTDLL_RegisterWhiteTakebackFunc.argtype = [st] dgt._DGTDLL_RegisterWhiteTakebackFunc.restype = ctypes.c_int dgt._DGTDLL_RegisterWhiteTakebackFunc(st) cmpfunc = functype(ctypes.c_int) st = cmpfunc(registerBlackTakeBackFunc) dgt._DGTDLL_RegisterBlackTakebackFunc.argtype = [st] dgt._DGTDLL_RegisterBlackTakebackFunc.restype = ctypes.c_int dgt._DGTDLL_RegisterBlackTakebackFunc(st) except: pass # ------------ return True
def __init__(self, procesador): wParent = procesador.pantalla self.configuracion = procesador.configuracion self.procesador = procesador self.siCambios = False QtGui.QDialog.__init__(self, wParent) self.setWindowTitle(_("Training with a book")) self.setWindowIcon(Iconos.Libros()) self.setWindowFlags(QtCore.Qt.Dialog | QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowMinimizeButtonHint) self.setMinimumWidth(450) flb = Controles.TipoLetra(puntos=10) # Variables antiguas dic = self.recuperaDIC() if dic is None: dic = {} dic_siBlancas = dic.get("SIBLANCAS", True) dic_nomLibro = dic.get("NOMLIBRO", "") dic_RR = dic.get("RR", "au") dic_RJ = dic.get("RJ", False) # Toolbar liAcciones = [ (_("Accept"), Iconos.Aceptar(), "aceptar"), None, (_("Cancel"), Iconos.Cancelar(), "cancelar"), None, ] tb = Controles.TB(self, liAcciones) # Color self.rbBlancas = QtGui.QRadioButton(_("White")) self.rbBlancas.setChecked(dic_siBlancas) self.rbNegras = QtGui.QRadioButton(_("Black")) self.rbNegras.setChecked(not dic_siBlancas) hbox = Colocacion.H().relleno().control( self.rbBlancas).espacio(10).control(self.rbNegras).relleno() gbColor = Controles.GB(self, _("Play with"), hbox).ponFuente(flb) # 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 = None if dic_nomLibro: for nom, libro in li: if nom == dic_nomLibro: libInicial = libro break if libInicial is None: libInicial = li[0][1] if li else None self.cb = QTUtil2.comboBoxLB(self, li, libInicial) btNuevo = Controles.PB(self, "", self.nuevo, plano=False).ponIcono(Iconos.Nuevo(), tamIcon=16) btBorrar = Controles.PB(self, "", self.borrar, plano=False).ponIcono(Iconos.Borrar(), tamIcon=16) hbox = Colocacion.H().relleno().control( self.cb).control(btNuevo).control(btBorrar).relleno() gbLibro = Controles.GB(self, _("Book"), hbox).ponFuente(flb) # Respuesta rival li = ( (_("Selected by the player"), "su"), (_("Uniform random"), "au"), (_("Proportional random"), "ap"), (_("Always the highest percentage"), "mp"), ) self.cbRR = QTUtil2.comboBoxLB(self, li, dic_RR) hbox = Colocacion.H().relleno().control(self.cbRR).relleno() gbRR = Controles.GB(self, _("Opponent's move"), hbox).ponFuente(flb) # Respuesta jugador self.chRJ = Controles.CHB(self, _("Always the highest percentage"), dic_RJ) hbox = Colocacion.H().relleno().control(self.chRJ).relleno() gbRJ = Controles.GB(self, _("Player's move"), hbox).ponFuente(flb) vlayout = Colocacion.V() vlayout.control(gbColor).espacio(5) vlayout.control(gbLibro).espacio(5) vlayout.control(gbRR).espacio(5) vlayout.control(gbRJ) vlayout.margen(20) layout = Colocacion.V().control(tb).otro(vlayout).margen(3) self.setLayout(layout)