Beispiel #1
0
 def seleccionaLibro(self):
     list_books = Books.ListBooks()
     list_books.restore_pickle(self.configuration.file_books)
     list_books.check()
     menu = QTVarios.LCMenu(self)
     rondo = QTVarios.rondoPuntos()
     for book in list_books.lista:
         menu.opcion(("x", book), book.name, rondo.otro())
         menu.separador()
     menu.opcion(("n", None), _("Install new book"), Iconos.Nuevo())
     resp = menu.lanza()
     if resp:
         orden, book = resp
         if orden == "x":
             pass
         elif orden == "n":
             fbin = QTUtil2.leeFichero(self,
                                       list_books.path,
                                       "bin",
                                       titulo=_("Polyglot book"))
             if fbin:
                 list_books.path = os.path.dirname(fbin)
                 name = os.path.basename(fbin)[:-4]
                 book = Books.Book("P", name, fbin, True)
                 list_books.nuevo(book)
                 list_books.save_pickle(self.configuration.file_books)
     else:
         book = None
     return book
 def polyglot_install(self):
     list_books = Books.ListBooks()
     list_books.restore_pickle(self.configuration.file_books)
     list_books.check()
     menu = QTVarios.LCMenu(self.main_window)
     for book in list_books.lista:
         if not Util.same_path(book.path, Code.tbook):
             menu.opcion(("x", book), book.name, Iconos.Delete())
             menu.separador()
     menu.opcion(("n", None), _("Install new book"), Iconos.Nuevo())
     resp = menu.lanza()
     if resp:
         orden, book = resp
         if orden == "x":
             if QTUtil2.pregunta(self.main_window,
                                 _("Do you want to delete %s?") %
                                 book.name):
                 list_books.borra(book)
                 list_books.save_pickle(self.configuration.file_books)
         elif orden == "n":
             fbin = QTUtil2.leeFichero(self.main_window,
                                       list_books.path,
                                       "bin",
                                       titulo=_("Polyglot book"))
             if fbin:
                 list_books.path = os.path.dirname(fbin)
                 name = os.path.basename(fbin)[:-4]
                 book = Books.Book("P", name, fbin, True)
                 list_books.nuevo(book)
                 list_books.save_pickle(self.configuration.file_books)
Beispiel #3
0
    def importarPolyglot(self, game):
        list_books = Books.ListBooks()
        list_books.restore_pickle(self.configuration.file_books)
        list_books.check()

        dicData = self.dbop.getconfig("IMPORT_POLYGLOT")
        bookW = list_books.lista[0]
        bookB = list_books.lista[0]
        if dicData:
            book = list_books.buscaLibro(dicData["BOOKW"])
            if book:
                bookW = book
            book = list_books.buscaLibro(dicData["BOOKB"])
            if book:
                bookB = book

        liGen = [FormLayout.separador]

        li = [(bookx.name, bookx) for bookx in list_books.lista]
        config = FormLayout.Combobox(_("Book that plays white side"), li)
        liGen.append((config, bookW))
        liGen.append(FormLayout.separador)
        config = FormLayout.Combobox(_("Book that plays black side"), li)
        liGen.append((config, bookB))
        liGen.append(FormLayout.separador)

        resultado = FormLayout.fedit(liGen,
                                     title=_("Polyglot book"),
                                     parent=self,
                                     anchoMinimo=360,
                                     icon=Iconos.Libros())
        if resultado:
            accion, liResp = resultado
            bookW, bookB = liResp
            dicData = {"BOOKW": bookW.name, "BOOKB": bookB.name}
            self.dbop.setconfig("IMPORT_POLYGLOT", dicData)
        else:
            return

        bookW.polyglot()
        bookB.polyglot()

        titulo = bookW.name if bookW == bookB else "%s/%s" % (bookW.name,
                                                              bookB.name)
        dicData = self.importarLeeParam(titulo)
        if dicData:
            depth, siWhite, onlyone, minMoves = (dicData["DEPTH"],
                                                 dicData["SIWHITE"],
                                                 dicData["ONLYONE"],
                                                 dicData["MINMOVES"])
            self.dbop.importarPolyglot(self, game, bookW, bookB, titulo, depth,
                                       siWhite, onlyone, minMoves)
            self.glines.refresh()
            self.glines.gotop()
Beispiel #4
0
    def import_polyglot(self, game):
        list_books = Books.ListBooks()
        list_books.restore_pickle(self.configuration.file_books)
        list_books.check()

        dicData = self.dbop.getconfig("IMPORT_POLYGLOT")
        bookW = list_books.lista[0]
        bookB = list_books.lista[0]
        if dicData:
            book = list_books.buscaLibro(dicData["BOOKW"])
            if book:
                bookW = book
            book = list_books.buscaLibro(dicData["BOOKB"])
            if book:
                bookB = book

        form = FormLayout.FormLayout(self,
                                     _("Polyglot book"),
                                     Iconos.Libros(),
                                     anchoMinimo=360)
        form.separador()

        li = [(bookx.name, bookx) for bookx in list_books.lista]
        form.combobox(_("Book that plays white side"), li, bookW)
        form.separador()

        form.combobox(_("Book that plays black side"), li, bookB)
        form.separador()

        resultado = form.run()
        if resultado:
            accion, liResp = resultado
            bookW, bookB = liResp
            dicData = {"BOOKW": bookW.name, "BOOKB": bookB.name}
            self.dbop.setconfig("IMPORT_POLYGLOT", dicData)
        else:
            return

        bookW.polyglot()
        bookB.polyglot()

        titulo = bookW.name if bookW == bookB else "%s/%s" % (bookW.name,
                                                              bookB.name)
        dicData = self.import_param_books(titulo, True)
        if dicData:
            depth, siWhite, onlyone, minMoves, excl_transpositions = (
                dicData["DEPTH"], dicData["SIWHITE"], dicData["ONLYONE"],
                dicData["MINMOVES"], dicData["EXCLTRANSPOSITIONS"])
            self.dbop.import_polyglot(self, game, bookW, bookB, titulo, depth,
                                      siWhite, onlyone, minMoves,
                                      excl_transpositions)
            self.glines.refresh()
            self.glines.gotop()
Beispiel #5
0
    def nuevo(self):
        menu = QTVarios.LCMenu(self)
        menu.opcion(("engine", None), _("Engine"), Iconos.Motor())
        menu.separador()

        submenu = menu.submenu(_("Polyglot book"), Iconos.Book())
        list_books = Books.ListBooks()
        list_books.restore_pickle(self.configuration.file_books)
        list_books.check()
        rondo = QTVarios.rondoPuntos()
        for book in list_books.lista:
            submenu.opcion(("book", book), book.name, rondo.otro())
            submenu.separador()
        submenu.opcion(("installbook", None), _("Install new book"),
                       Iconos.Nuevo())
        menu.separador()

        si_gaviota = True
        si_index = True
        for kib in self.kibitzers.lista:
            if kib.tipo == Kibitzers.KIB_GAVIOTA:
                si_gaviota = False
            elif kib.tipo == Kibitzers.KIB_INDEXES:
                si_index = False
        if si_index:
            menu.opcion(("index", None),
                        _("Indexes") + " - RodentII", Iconos.Camara())
            menu.separador()
        if si_gaviota:
            menu.opcion(("gaviota", None), _("Gaviota Tablebases"),
                        Iconos.Finales())

        resp = menu.lanza()
        if resp:
            orden, extra = resp

            if orden == "engine":
                self.nuevo_engine()
            elif orden in "book":
                num = self.kibitzers.nuevo_polyglot(extra)
                self.goto(num)
            elif orden == "gaviota":
                num = self.kibitzers.nuevo_gaviota()
                self.goto(num)
            elif orden == "index":
                num = self.kibitzers.nuevo_index()
                self.goto(num)
            elif orden in "installbook":
                self.polyglot_install(list_books)
Beispiel #6
0
    def __init__(self, w_parent):

        QtWidgets.QDialog.__init__(self, w_parent)

        self.w_parent = w_parent

        self.file = ""

        self.setWindowTitle(_("Create a new book"))
        self.setWindowIcon(Iconos.Libros())
        self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.Dialog | QtCore.Qt.WindowTitleHint)

        f = Controles.TipoLetra(puntos=9, peso=75)

        self.configuration = Code.configuration
        fvar = self.configuration.file_books
        self.list_books = Books.ListBooks()
        self.list_books.restore_pickle(fvar)

        lbFichero = Controles.LB(self, _("Book to create") + ":").ponFuente(f)
        self.btFichero = Controles.PB(self, "", self.buscaFichero, False).anchoMinimo(450).ponFuente(f)
        lbMaxPly = Controles.LB(self, _("Maximum no. half moves (ply)") + ":").ponFuente(f)
        self.sbMaxPly = Controles.SB(self, 0, 0, 999).tamMaximo(50)
        lbMinGame = Controles.LB(self, _("Minimum number of games") + ":").ponFuente(f)
        self.sbMinGame = Controles.SB(self, 3, 1, 999).tamMaximo(50)
        lbMinScore = Controles.LB(self, _("Minimum score") + ":").ponFuente(f)
        self.sbMinScore = Controles.SB(self, 0, 0, 100).tamMaximo(50)
        self.chbOnlyWhite = Controles.CHB(self, _("White only"), False).ponFuente(f)
        self.chbOnlyBlack = Controles.CHB(self, _("Black only"), False).ponFuente(f)
        self.chbUniform = Controles.CHB(self, _("Uniform distribution"), False).ponFuente(f)

        lyf = Colocacion.H().control(lbFichero).control(self.btFichero)
        ly = Colocacion.G().margen(15)
        ly.otroc(lyf, 0, 0, 1, 2)
        ly.controld(lbMaxPly, 1, 0).control(self.sbMaxPly, 1, 1)
        ly.controld(lbMinGame, 2, 0).control(self.sbMinGame, 2, 1)
        ly.controld(lbMinScore, 3, 0).control(self.sbMinScore, 3, 1)
        ly.controlc(self.chbOnlyWhite, 4, 0, 1, 2)
        ly.controlc(self.chbOnlyBlack, 5, 0, 1, 2)
        ly.controlc(self.chbUniform, 6, 0, 1, 2)

        # Toolbar
        li_acciones = [(_("Accept"), Iconos.Aceptar(), "aceptar"), None, (_("Cancel"), Iconos.Cancelar(), "cancelar"), None]
        tb = Controles.TB(self, li_acciones)

        # Layout
        layout = Colocacion.V().control(tb).otro(ly).margen(3)
        self.setLayout(layout)
    def __init__(self, manager, siEnVivo):

        titulo = _("Consult a book")
        icono = Iconos.Libros()
        extparam = "treebook"
        QTVarios.WDialogo.__init__(self, manager.main_window, titulo, icono,
                                   extparam)

        # Se lee la lista de libros1
        self.list_books = Books.ListBooks()
        self.fvar = manager.configuration.file_books
        self.list_books.restore_pickle(self.fvar)

        # Comprobamos que todos esten accesibles
        self.list_books.check()
        self.book = self.list_books.porDefecto()

        # fens
        fenActivo = manager.fenActivoConInicio()  # Posicion en el board
        fenUltimo = manager.last_fen()
        self.siEnviar = siEnVivo and (fenActivo == fenUltimo)

        self.listaMoves = ListaMoves(None, self.book, fenActivo)

        self.infoMove = InfoMove(manager.board.is_white_bottom, fenActivo)

        self.wmoves = WMoves(self, self.siEnviar)

        self.splitter = splitter = QtWidgets.QSplitter(self)
        splitter.addWidget(self.infoMove)
        splitter.addWidget(self.wmoves)

        ly = Colocacion.H().control(splitter).margen(0)

        self.setLayout(ly)

        self.wmoves.tree.setFocus()

        anchoBoard = self.infoMove.board.width()

        self.resize(600 - 278 + anchoBoard, anchoBoard + 30)
        self.splitter.setSizes([296 - 278 + anchoBoard, 290])
        for col, ancho in enumerate((100, 59, 87, 0, 38)):
            self.wmoves.tree.setColumnWidth(col, ancho)

        self.ponTitulo(self.book)
def massive_analysis_parameters(parent,
                                configuration,
                                siVariosSeleccionados,
                                siDatabase=False):
    alm = read_dic_params(configuration)

    # Datos
    liGen = [SEPARADOR]

    # # Tutor
    li = configuration.ayudaCambioTutor()
    li[0] = alm.engine
    liGen.append((_("Engine") + ":", li))

    liGen.append(SEPARADOR)

    # # Time
    config = FormLayout.Editbox(_("Duration of engine analysis (secs)"),
                                40,
                                tipo=float)
    liGen.append((config, alm.vtime / 1000.0))

    # Depth
    liDepths = [("--", 0)]
    for x in range(1, 100):
        liDepths.append((str(x), x))
    config = FormLayout.Combobox(_("Depth"), liDepths)
    liGen.append((config, alm.depth))

    # Time+Depth
    liGen.append(("%s+%s:" % (_("Time"), _("Depth")), alm.timedepth))

    # MultiPV
    liGen.append(SEPARADOR)
    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)))
    config = FormLayout.Combobox(
        _("Number of moves evaluated by engine(MultiPV)"), li)
    liGen.append((config, alm.multiPV))
    liGen.append(SEPARADOR)

    liJ = [(_("White"), "WHITE"), (_("Black"), "BLACK"),
           (_("White & Black"), "BOTH")]
    config = FormLayout.Combobox(_("Analyze only color"), liJ)
    if alm.white and alm.black:
        color = "BOTH"
    elif alm.black:
        color = "BLACK"
    elif alm.white:
        color = "WHITE"
    else:
        color = "BOTH"
    liGen.append((config, color))

    liGen.append(
        ('<div align="right">' + _("Only player moves") + ":<br>%s</div>" %
         _("(You can add multiple aliases separated by ; and wildcard * )"),
         ""))

    fvar = configuration.file_books
    list_books = Books.ListBooks()
    list_books.restore_pickle(fvar)
    # Comprobamos que todos esten accesibles
    list_books.check()
    defecto = list_books.lista[0]
    li = [("--", None)]
    for book in list_books.lista:
        if book.name == alm.book_name:
            defecto = book
        li.append((book.name, book))
    config = FormLayout.Combobox(
        _("Do not scan the opening moves based on book"), li)
    liGen.append((config, defecto))

    liGen.append(
        (_("Start from the end of the game") + ":", alm.from_last_move))

    liGen.append(SEPARADOR)
    liGen.append((_("Redo any existing prior analysis (if they exist)") + ":",
                  alm.delete_previous))

    liGen.append(SEPARADOR)
    liGen.append((_("Only selected games") + ":", siVariosSeleccionados))

    liVar = form_variations(alm)

    liBlunders, liBrilliancies = form_blunders_brilliancies(alm, configuration)

    lista = []
    lista.append((liGen, _("General options"), ""))
    lista.append((liVar, _("Variations"), ""))
    lista.append((liBlunders, _("Wrong moves"), ""))
    lista.append((liBrilliancies, _("Brilliancies"), ""))

    reg = Util.Record()
    reg.form = None

    def dispatchR(valor):
        if reg.form is None:
            if isinstance(valor, FormLayout.FormTabWidget):
                reg.form = valor
                reg.wtime = valor.getWidget(0, 1)
                reg.wdepth = valor.getWidget(0, 2)
                reg.wdt = valor.getWidget(0, 3)
            elif isinstance(valor, FormLayout.FormWidget):
                reg.form = valor
                reg.wtime = valor.getWidget(1)
                reg.wdepth = valor.getWidget(2)
                reg.wdt = valor.getWidget(3)
        else:
            sender = reg.form.sender()
            if not reg.wdt.isChecked():
                if sender == reg.wtime:
                    if reg.wtime.textoFloat() > 0:
                        reg.wdepth.setCurrentIndex(0)
                elif sender == reg.wdepth:
                    if reg.wdepth.currentIndex() > 0:
                        reg.wtime.ponFloat(0.0)
                elif sender == reg.wdt:
                    if reg.wtime.textoFloat() > 0:
                        reg.wdepth.setCurrentIndex(0)
                    elif reg.wdepth.currentIndex() > 0:
                        reg.wtime.ponFloat(0.0)

                QTUtil.refresh_gui()

    resultado = FormLayout.fedit(lista,
                                 title=_("Mass analysis"),
                                 parent=parent,
                                 anchoMinimo=460,
                                 icon=Iconos.Opciones(),
                                 dispatch=dispatchR)

    if resultado:
        accion, liResp = resultado

        liGen, liVar, liBlunders, liBrilliancies = liResp

        alm.engine, vtime, alm.depth, alm.timedepth, alm.multiPV, color, cjug, alm.book, alm.from_last_move, alm.delete_previous, alm.siVariosSeleccionados = liGen

        alm.vtime = int(vtime * 1000)
        alm.white = color != "BLACK"
        alm.black = color != "WHITE"
        cjug = cjug.strip()
        alm.li_players = cjug.upper().split(";") if cjug else None
        alm.book_name = alm.book.name if alm.book else None

        alm.kblunders, alm.tacticblunders, alm.pgnblunders, alm.oriblunders, alm.bmtblunders = liBlunders

        alm.include_variations, alm.limiteinclude_variations, alm.best_variation, alm.info_variation, alm.si_pdt, alm.one_move_variation = liVar

        alm.dpbrilliancies, alm.ptbrilliancies, alm.fnsbrilliancies, alm.pgnbrilliancies, alm.oribrilliancies, alm.bmtbrilliancies = liBrilliancies

        dic = {}
        for x in dir(alm):
            if not x.startswith("__"):
                dic[x.upper()] = getattr(alm, x)
        Util.save_pickle(configuration.file_param_analysis(), dic)

        if not (alm.tacticblunders or alm.pgnblunders or alm.bmtblunders
                or alm.fnsbrilliancies or alm.pgnbrilliancies
                or alm.bmtbrilliancies or siDatabase):
            QTUtil2.message_error(
                parent, _("No file was specified where to save results"))
            return

        return alm
    else:
        return None
Beispiel #9
0
    def reinicio(self, dbop):
        self.dbop = dbop
        self.dbop.open_cache_engines()
        self.game_type = GT_OPENING_LINES

        self.level = self.dbop.getconfig("ENG_LEVEL", 0)
        self.numengine = self.dbop.getconfig("ENG_ENGINE", 0)

        self.trainingEngines = self.dbop.trainingEngines()

        self.auto_analysis = self.trainingEngines.get("AUTO_ANALYSIS", True)
        self.ask_movesdifferent = self.trainingEngines.get(
            "ASK_MOVESDIFFERENT", False)

        liTimes = self.trainingEngines.get("TIMES")
        if not liTimes:
            liTimes = [500, 1000, 2000, 4000, 8000]
        liBooks = self.trainingEngines.get("BOOKS")
        if not liBooks:
            liBooks = ["", "", "", "", ""]
        liBooks_sel = self.trainingEngines.get("BOOKS_SEL")
        if not liBooks_sel:
            liBooks_sel = ["", "", "", "", ""]
        liEngines = self.trainingEngines["ENGINES"]
        num_engines_base = len(liEngines)
        liEnginesExt = [
            key for key in self.trainingEngines.get("EXT_ENGINES", [])
            if not (key in liEngines)
        ]
        num_engines = num_engines_base + len(liEnginesExt)

        if self.numengine >= num_engines:
            self.level += 1
            self.numengine = 0
            self.dbop.setconfig("ENG_LEVEL", self.level)
            self.dbop.setconfig("ENG_ENGINE", 0)
        num_levels = len(liTimes)
        if self.level >= num_levels:
            if QTUtil2.pregunta(
                    self.main_window, "%s.\n%s" %
                (_("Training finished"), _("Do you want to reinit?"))):
                self.dbop.setconfig("ENG_LEVEL", 0)
                self.dbop.setconfig("ENG_ENGINE", 0)
                self.reinicio(dbop)
            return

        self.time = liTimes[self.level]
        nombook = liBooks[self.level]
        if nombook:
            list_books = Books.ListBooks()
            list_books.restore_pickle(self.configuration.file_books)
            self.book = list_books.buscaLibro(nombook)
            if self.book:
                self.book.polyglot()
                self.book.mode = liBooks_sel[self.level]
                if not self.book.mode:
                    self.book.mode = "mp"
        else:
            self.book = None

        if self.numengine < num_engines_base:
            self.keyengine = liEngines[self.numengine]
        else:
            self.keyengine = liEnginesExt[self.numengine - num_engines_base -
                                          1]

        self.plies_mandatory = self.trainingEngines["MANDATORY"]
        self.plies_control = self.trainingEngines["CONTROL"]
        self.plies_pendientes = self.plies_control
        self.lost_points = self.trainingEngines["LOST_POINTS"]

        self.is_human_side_white = self.trainingEngines["COLOR"] == "WHITE"
        self.is_engine_side_white = not self.is_human_side_white

        self.siAprobado = False

        rival = self.configuration.buscaRival(self.keyengine)
        self.xrival = self.procesador.creaManagerMotor(rival, self.time, None)
        self.xrival.is_white = self.is_engine_side_white

        self.xanalyzer.cambiaOpciones(
            max(self.xtutor.motorTiempoJugada, self.time + 5.0), 0)

        juez = self.configuration.buscaRival(
            self.trainingEngines["ENGINE_CONTROL"])
        self.xjuez = self.procesador.creaManagerMotor(
            juez, int(self.trainingEngines["ENGINE_TIME"] * 1000), None)
        self.xjuez.anulaMultiPV()

        self.li_info = [
            "<b>%s</b>: %d/%d - %s" %
            (_("Engine"), self.numengine + 1, num_engines, self.xrival.name),
            '<b>%s</b>: %d/%d - %0.1f"' %
            (_("Level"), self.level + 1, num_levels, self.time / 1000.0),
        ]

        self.dicFENm2 = self.trainingEngines["DICFENM2"]

        self.siAyuda = False
        self.board.dbvisual_set_show_allways(False)
        self.hints = 9999  # Para que analice sin problemas

        self.game = Game.Game()

        self.main_window.pon_toolbar((TB_CLOSE, TB_RESIGN, TB_REINIT))
        self.main_window.activaJuego(True, False, siAyudas=False)
        self.set_dispatcher(self.player_has_moved)
        self.set_position(self.game.last_position)
        self.show_side_indicator(True)
        self.remove_hints()
        self.put_pieces_bottom(self.is_human_side_white)
        self.pgnRefresh(True)

        self.ponCapInfoPorDefecto()

        self.state = ST_PLAYING

        self.check_boards_setposition()

        self.errores = 0
        self.ini_time = time.time()
        self.muestraInformacion()
        self.play_next_move()
Beispiel #10
0
    def __init__(self, procesador):
        w_parent = procesador.main_window
        self.configuration = procesador.configuration
        self.procesador = procesador

        titulo = _("Training with a book")
        icono = Iconos.Libros()

        QTVarios.WDialogo.__init__(self, w_parent, titulo, icono, "bookstrain")

        self.setMinimumWidth(450)

        flb = Controles.TipoLetra(puntos=10)

        # Variables antiguas
        dic_data = self.restore()

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

        # Side
        self.rb_white = Controles.RB(self, _("White"))
        self.rb_white.setChecked(dic_data.get(self.ISWHITE, True))
        self.rb_black = Controles.RB(self, _("Black"))
        self.rb_black.setChecked(not dic_data.get(self.ISWHITE, True))

        hbox = Colocacion.H().relleno().control(
            self.rb_white).espacio(10).control(self.rb_black).relleno()
        gb_side = Controles.GB(self, _("Play with"), hbox).ponFuente(flb)

        # Books
        fvar = self.configuration.file_books
        self.list_books = Books.ListBooks()
        self.list_books.restore_pickle(fvar)
        self.list_books.check()
        li = [(x.name, x) for x in self.list_books.lista]

        # Player
        book_player = li[0][1] if li else None

        nom_book_player = dic_data.get(self.BOOK_PLAYER)
        if nom_book_player:
            for nom, book in li:
                if nom == nom_book_player:
                    book_player = book
                    break
        self.cb_player = Controles.CB(self, li, book_player)

        btNuevo = Controles.PB(self, "", self.nuevo,
                               plano=False).ponIcono(Iconos.Nuevo(),
                                                     icon_size=16)
        btBorrar = Controles.PB(self, "", self.borrar,
                                plano=False).ponIcono(Iconos.Borrar(),
                                                      icon_size=16)

        self.chb_highest = Controles.CHB(
            self, _("Always the highest percentage"),
            dic_data.get(self.ALWAYS_HIGHEST, False))

        lybook = Colocacion.H().relleno().control(
            self.cb_player).control(btNuevo).control(btBorrar).relleno()
        ly_select = Colocacion.H().relleno().control(
            self.chb_highest).relleno()

        ly = Colocacion.V().otro(lybook).espacio(10).otro(ly_select)
        gb_player = Controles.GB(self, _("Player's book"), ly).ponFuente(flb)

        # Rival
        book_rival = book_player

        nom_book_rival = dic_data.get(self.BOOK_RIVAL)
        if nom_book_rival:
            for nom, book in li:
                if nom == nom_book_rival:
                    book_rival = book
                    break
        self.cb_rival = Controles.CB(self, li, book_rival)

        li = (
            (_("Selected by the player"), "su"),
            (_("Uniform random"), "au"),
            (_("Proportional random"), "ap"),
            (_("Always the highest percentage"), "mp"),
        )
        self.cb_resp_rival = Controles.CB(self, li,
                                          dic_data.get(self.RESP_RIVAL, "au"))

        ly = Colocacion.V().controlc(self.cb_rival).espacio(10).controlc(
            self.cb_resp_rival)
        gb_rival = Controles.GB(self, _("Rival book"), ly).ponFuente(flb)

        self.chb_showmenu = Controles.CHB(
            self, _("Display a menu of alternatives if move is invalid"),
            dic_data.get(self.SHOW_MENU, True))

        vlayout = Colocacion.V()
        vlayout.control(gb_side).espacio(5)
        vlayout.control(gb_player).espacio(5)
        vlayout.control(gb_rival).espacio(5)
        vlayout.control(self.chb_showmenu).espacio(5)
        vlayout.margen(20)

        layout = Colocacion.V().control(tb).otro(vlayout).margen(3)

        self.setLayout(layout)

        self.restore_video()
Beispiel #11
0
    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)

        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]

        # Toolbar
        li_acciones = [
            (_("Accept"), Iconos.Aceptar(), self.aceptar),
            None,
            (_("Cancel"), Iconos.Cancelar(), self.cancelar),
            None,
            (_("Configurations"), Iconos.Configurar(), self.configurations),
            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.configuration.x_rival_inicial
        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.change_time)
        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)

        # # Side
        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=14))
        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)

        if self.configuration.x_digital_board:
            self.chb_dgt = Controles.CHB(self, "%s: %s" % (_("Activate board"), self.configuration.x_digital_board), DGT.siON()).ponFuente(
                Controles.TipoLetra(puntos=14)
            )
            lyH = Colocacion.H().control(self.chb_dgt)
            _label(lyG, "", lyH)

        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)

        lbArrows = Controles.LB2P(self, _("Arrows with the best moves")).ponFuente(font)
        self.sbArrowsTt = Controles.SB(self, 0, 0, 999).tamMaximo(50).ponFuente(font)

        lyT1 = Colocacion.H().control(lbAyudas).control(self.cbAyudas).relleno()
        lyT1.control(self.chbChance).relleno().control(btTutorChange)
        lyT3 = Colocacion.H().control(lbThoughtTt).control(self.cbThoughtTt).relleno()
        lyT3.control(lbArrows).control(self.sbArrowsTt)

        ly = Colocacion.V().otro(lyT1).espacio(16).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, 0, 0, 999).tamMaximo(50).ponFuente(font)
        ly = Colocacion.H().control(lb).control(self.cbThoughtOp).relleno()
        ly.control(lbArrows).control(self.sbArrows)
        gbThoughtOp = Controles.GB(self, _("Opponent's thought information"), ly)
        gbThoughtOp.setStyleSheet(gb_style)

        self.lbBoxHeight = Controles.LB2P(self, '%s ("%s")' % (_("Box height"), _("It is showed"))).ponFuente(font)
        self.sbBoxHeight = Controles.SB(self, 0, 0, 999).tamMaximo(50).ponFuente(font)

        lyBox = Colocacion.H().control(self.lbBoxHeight).control(self.sbBoxHeight).relleno()

        ly = Colocacion.V().espacio(16).control(self.gbTutor).control(gbThoughtOp)
        ly.espacio(16).otro(lyBox).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
        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()
Beispiel #12
0
    def __init__(self, procesador):
        self.configuration = procesador.configuration
        self.procesador = procesador

        self.db_histo = UtilSQL.DictSQL(self.configuration.ficheroGMhisto)
        self.opening_block = None
        self.li_preferred_openings = []

        w_parent = procesador.main_window
        titulo = _("Play like a Grandmaster")
        icono = Iconos.GranMaestro()

        extparam = "gm"
        QTVarios.WDialogo.__init__(self, w_parent, titulo, icono, extparam)

        flb = Controles.TipoLetra(puntos=procesador.configuration.x_menu_points)

        # Toolbar
        li_acciones = [
            (_("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, li_acciones)

        # Grandes maestros
        self.li_gm = GM.lista_gm()
        gb_style = Common.gb_style()
        li = [(x[0], x[1]) for x in self.li_gm]
        li.insert(0, ("-", None))
        self.cb_gm = QTUtil2.comboBoxLB(self, li, li[0][1] if len(self.li_gm) == 0 else li[1][1])
        self.cb_gm.capture_changes(self.check_gm)
        hbox = Colocacion.H().relleno().control(self.cb_gm).relleno()
        gbGM = Controles.GB(self, _("Choose a Grandmaster"), hbox).ponFuente(flb)
        gbGM.setStyleSheet(gb_style)

        # Personales
        self.li_personal = GM.lista_gm_personal(self.procesador.configuration.personal_training_folder)
        if self.li_personal:
            li = [(x[0], x[1]) for x in self.li_personal]
            li.insert(0, ("-", None))
            self.cbPersonal = QTUtil2.comboBoxLB(self, li, li[0][1])
            self.cbPersonal.capture_changes(self.check_personal)
            btBorrar = Controles.PB(self, "", self.borrarPersonal).ponIcono(Iconos.Borrar(), icon_size=24)
            hbox = Colocacion.H().relleno().control(self.cbPersonal).control(btBorrar).relleno()
            gb_personal = Controles.GB(self, _("Personal games"), hbox).ponFuente(flb)
            gb_personal.setStyleSheet(gb_style)

        # Color
        self.rb_white = Controles.RB(self, _("White"), rutina=self.check_color)
        self.rb_white.setFont(flb)
        self.rb_white.activa(True)
        self.rb_black = Controles.RB(self, _("Black"), rutina=self.check_color)
        self.rb_black.setFont(flb)
        self.rb_black.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.configuration.comboMotoresMultiPV10()
        self.cbJmotor, self.lbJmotor = QTUtil2.comboBoxLB(self, self.liMotores, self.configuration.tutor_inicial, _("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).capture_changes(self.change_depth)
        self.lbJdepth = Controles.LB2P(self, _("Depth"))
        self.lbJshow = Controles.LB2P(self, _("Show rating"))
        self.chbEvals = Controles.CHB(self, _("Show all evaluations"), False)
        li_options = [(_("All moves"), None), (_("Moves are different"), True), (_("Never"), False)]
        self.cbJshow = Controles.CB(self, li_options, 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")

        self.li_adjudicator_controls = (
            self.cbJmotor,
            self.lbJmotor,
            self.edJtiempo,
            self.lbJtiempo,
            self.lbJdepth,
            self.cbJdepth,
            self.lbJshow,
            self.cbJshow,
            self.lbJmultiPV,
            self.cbJmultiPV,
            self.chbEvals,
        )

        for control in self.li_adjudicator_controls:
            control.setFont(flb)

        # Inicial
        self.edJugInicial, lbInicial = QTUtil2.spinBoxLB(self, 1, 1, 99, etiqueta=_("Initial move"), maxTam=40)

        # Libros
        fvar = self.configuration.file_books
        self.list_books = Books.ListBooks()
        self.list_books.restore_pickle(fvar)
        # # Comprobamos que todos esten accesibles
        self.list_books.check()
        li = [(x.name, x) for x in self.list_books.lista]
        li.insert(0, ("--", None))
        self.cbBooks, lbBooks = QTUtil2.comboBoxLB(self, li, None, _("Bypass moves in the book"))

        # Openings

        self.btOpening = Controles.PB(self, " " * 5 + _("Undetermined") + " " * 5, self.aperturasEditar).ponPlano(False)
        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().control(self.btOpeningsQuitar).control(self.btOpening).control(self.btOpeningsFavoritas).relleno()
        gbOpening = Controles.GB(self, _("Opening"), hbox)

        # gbBasic
        # # Color
        hbox = Colocacion.H().relleno().control(self.rb_white).espacio(10).control(self.rb_black).relleno()
        gbColor = Controles.GB(self, _("Play with"), hbox).ponFuente(flb)
        gbColor.setStyleSheet(gb_style)

        # Tiempo
        ly1 = Colocacion.H().control(self.lbJmotor).control(self.cbJmotor).relleno().control(self.lbJshow).control(self.cbJshow)
        ly2 = Colocacion.H().control(self.lbJtiempo).control(self.edJtiempo)
        ly2.control(self.lbJdepth).control(self.cbJdepth).relleno().control(self.chbEvals)
        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).to_connect(self.change_adjudicator)
        self.gbJ.setStyleSheet(gb_style)

        # 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().otro(lyInicial).control(gbOpening)
        vlayout.espacio(5).control(self.chContrario).margen(20).relleno()
        gbAdvanced = Controles.GB(self, "", vlayout)
        gbAdvanced.setFlat(True)

        # Historico
        self.liHisto = []
        o_columns = Columnas.ListaColumnas()
        o_columns.nueva("FECHA", _("Date"), 100, centered=True)
        o_columns.nueva("PACIERTOS", _("Hints"), 90, centered=True)
        o_columns.nueva("PUNTOS", _("Points accumulated"), 140, centered=True)
        o_columns.nueva("ENGINE", _("Adjudicator"), 100, centered=True)
        o_columns.nueva("RESUMEN", _("Game played"), 280)

        self.grid = grid = Grid.Grid(self, o_columns, siSelecFilas=True, background=None)
        self.grid.coloresAlternados()
        self.register_grid(grid)

        # Tabs
        self.tab = Controles.Tab().set_position("S")
        self.tab.nuevaTab(gbBasic, _("Basic"))
        self.tab.nuevaTab(gbAdvanced, _("Advanced"))
        self.tab.nuevaTab(self.grid, _("Track record"))
        self.tab.setFont(flb)

        # Cabecera
        lyCab = Colocacion.H().control(gbGM)
        if self.li_personal:
            lyCab.control(gb_personal)

        layout = Colocacion.V().control(tb).otro(lyCab).control(self.tab).margen(6)

        self.setLayout(layout)

        self.restore_dic()
        self.change_adjudicator()
        self.check_gm()
        self.check_personal()
        self.check_histo()
        self.aperturaMuestra()
        self.btOpeningsFavoritas.hide()

        self.restore_video(anchoDefecto=750)
def analysis_parameters(parent,
                        configuration,
                        siModoAmpliado,
                        siTodosMotores=False):
    alm = read_dic_params(configuration)

    # Datos
    li_gen = [SEPARADOR]

    # # Tutor
    if siTodosMotores:
        li = configuration.ayudaCambioCompleto(alm.engine)
    else:
        li = configuration.ayudaCambioTutor()
        li[0] = alm.engine
    li_gen.append((_("Engine") + ":", li))

    # # Time
    li_gen.append(SEPARADOR)
    config = FormLayout.Editbox(_("Duration of engine analysis (secs)"),
                                40,
                                tipo=float)
    li_gen.append((config, alm.vtime / 1000.0))

    # Depth
    liDepths = [("--", 0)]
    for x in range(1, 51):
        liDepths.append((str(x), x))
    config = FormLayout.Combobox(_("Depth"), liDepths)
    li_gen.append((config, alm.depth))

    # Time+Depth
    li_gen.append(("%s+%s:" % (_("Time"), _("Depth")), alm.timedepth))

    # MultiPV
    li_gen.append(SEPARADOR)
    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)))
    config = FormLayout.Combobox(
        _("Number of moves evaluated by engine(MultiPV)"), li)
    li_gen.append((config, alm.multiPV))

    # Priority
    li_gen.append(SEPARADOR)
    config = FormLayout.Combobox(_("Process priority"),
                                 Priorities.priorities.combo())
    li_gen.append((config, alm.priority))

    # Completo
    if siModoAmpliado:
        li_gen.append(SEPARADOR)

        liJ = [(_("White"), "WHITE"), (_("Black"), "BLACK"),
               (_("White & Black"), "BOTH")]
        config = FormLayout.Combobox(_("Analyze only color"), liJ)
        if alm.white and alm.black:
            color = "BOTH"
        elif alm.black:
            color = "BLACK"
        elif alm.white:
            color = "WHITE"
        else:
            color = "BOTH"
        li_gen.append((config, color))

        config = FormLayout.Editbox('<div align="right">' + _("Moves") +
                                    "<br>" + _("By example:") +
                                    " -5,8-12,14,19-",
                                    rx="[0-9,\-,\,]*")
        li_gen.append((config, ""))

        fvar = configuration.file_books
        list_books = Books.ListBooks()
        list_books.restore_pickle(fvar)
        # Comprobamos que todos esten accesibles
        list_books.check()
        li = [("--", None)]
        defecto = list_books.lista[0] if alm.book_name else None
        for book in list_books.lista:
            if alm.book_name == book.name:
                defecto = book
            li.append((book.name, book))
        config = FormLayout.Combobox(
            _("Do not scan the opening moves based on book"), li)
        li_gen.append((config, defecto))
        li_gen.append(SEPARADOR)

        li_gen.append(
            (_("Redo any existing prior analysis (if they exist)") + ":",
             alm.delete_previous))

        li_gen.append(
            (_("Start from the end of the game") + ":", alm.from_last_move))

        li_gen.append(SEPARADOR)

        li_gen.append((_("Show graphics") + ":", alm.show_graphs))

        liVar = form_variations(alm)

        liBlunders, liBrilliancies = form_blunders_brilliancies(
            alm, configuration)

        liST = [SEPARADOR]
        liST.append((_("Activate") + ":", alm.stability))
        liST.append(SEPARADOR)
        liST.append(
            (FormLayout.Spinbox(_("Last depths to control same best move"), 2,
                                10, 40), alm.st_depths))
        liST.append(SEPARADOR)
        liST.append(
            (FormLayout.Spinbox(_("Maximum difference among last evaluations"),
                                0, 99999, 60), alm.st_centipawns))
        liST.append(SEPARADOR)
        liST.append((FormLayout.Spinbox(_("Additional time limit"), 0, 99999,
                                        60), alm.st_timelimit))

        lista = []
        lista.append((li_gen, _("General options"), ""))
        lista.append((liVar, _("Variations"), ""))
        lista.append((liBlunders, _("Wrong moves"), ""))
        lista.append((liBrilliancies, _("Brilliancies"), ""))
        lista.append((liST, _("Stability control"), ""))

    else:
        lista = li_gen

    reg = Util.Record()
    reg.form = None

    def dispatchR(valor):
        if reg.form is None:
            if isinstance(valor, FormLayout.FormTabWidget):
                reg.form = valor
                reg.wtime = valor.getWidget(0, 1)
                reg.wdepth = valor.getWidget(0, 2)
                reg.wdt = valor.getWidget(0, 3)
            elif isinstance(valor, FormLayout.FormWidget):
                reg.form = valor
                reg.wtime = valor.getWidget(1)
                reg.wdepth = valor.getWidget(2)
                reg.wdt = valor.getWidget(3)
        else:
            sender = reg.form.sender()
            if not reg.wdt.isChecked():
                if sender == reg.wtime:
                    if reg.wtime.textoFloat() > 0:
                        reg.wdepth.setCurrentIndex(0)
                elif sender == reg.wdepth:
                    if reg.wdepth.currentIndex() > 0:
                        reg.wtime.ponFloat(0.0)
                elif sender == reg.wdt:
                    if reg.wtime.textoFloat() > 0:
                        reg.wdepth.setCurrentIndex(0)
                    elif reg.wdepth.currentIndex() > 0:
                        reg.wtime.ponFloat(0.0)

                QTUtil.refresh_gui()

    resultado = FormLayout.fedit(lista,
                                 title=_("Analysis Configuration"),
                                 parent=parent,
                                 anchoMinimo=460,
                                 icon=Iconos.Opciones(),
                                 dispatch=dispatchR)

    if resultado:
        accion, liResp = resultado

        if siModoAmpliado:
            li_gen, liVar, liBlunders, liBrilliancies, liST = liResp
        else:
            li_gen = liResp

        alm.engine = li_gen[0]
        alm.vtime = int(li_gen[1] * 1000)
        alm.depth = li_gen[2]
        alm.timedepth = li_gen[3]
        alm.multiPV = li_gen[4]
        alm.priority = li_gen[5]

        if siModoAmpliado:
            color = li_gen[6]
            alm.white = color != "BLACK"
            alm.black = color != "WHITE"
            alm.num_moves = li_gen[7]
            alm.book = li_gen[8]
            alm.book_name = alm.book.name if alm.book else None
            alm.delete_previous = li_gen[9]
            alm.from_last_move = li_gen[10]
            alm.show_graphs = li_gen[11]

            (alm.include_variations, alm.limit_include_variations,
             alm.best_variation, alm.info_variation, alm.si_pdt,
             alm.one_move_variation) = liVar

            (alm.kblunders, alm.tacticblunders, alm.pgnblunders,
             alm.oriblunders, alm.bmtblunders) = liBlunders

            (alm.dpbrilliancies, alm.ptbrilliancies, alm.fnsbrilliancies,
             alm.pgnbrilliancies, alm.oribrilliancies,
             alm.bmtbrilliancies) = liBrilliancies

            (alm.stability, alm.st_depths, alm.st_centipawns,
             alm.st_timelimit) = liST

        dic = {}
        for x in dir(alm):
            if not x.startswith("__"):
                dic[x] = getattr(alm, x)
        Util.save_pickle(configuration.file_param_analysis(), dic)

        return alm
    else:
        return None
Beispiel #14
0
    def trainNewEngines(self):
        training = self.dbop.trainingEngines()
        color = "WHITE"
        basepv = self.dbop.basePV
        mandatory = basepv.count(" ") + 1 if len(basepv) > 0 else 0
        control = 10
        lost_points = 20
        engine_control = self.configuration.tutor.key
        engine_time = 5.0
        num_engines = 20
        key_engine = "alaric"
        ext_engines = []
        auto_analysis = True
        ask_movesdifferent = False
        times = [500, 1000, 2000, 4000, 8000]
        books = ["", "", "", "", ""]
        books_sel = ["", "", "", "", ""]

        if training is not None:
            color = training["COLOR"]
            mandatory = training.get("MANDATORY", mandatory)
            control = training.get("CONTROL", control)
            lost_points = training.get("LOST_POINTS", lost_points)
            engine_control = training.get("ENGINE_CONTROL", engine_control)
            engine_time = training.get("ENGINE_TIME", engine_time)
            num_engines = training.get("NUM_ENGINES", num_engines)
            key_engine = training.get("KEY_ENGINE", key_engine)
            ext_engines = training.get("EXT_ENGINES", ext_engines)
            auto_analysis = training.get("AUTO_ANALYSIS", auto_analysis)
            ask_movesdifferent = training.get("ASK_MOVESDIFFERENT",
                                              ask_movesdifferent)
            times = training.get("TIMES", times)
            books = training.get("BOOKS", books)
            books_sel = training.get("BOOKS_SEL", books_sel)

        separador = FormLayout.separador
        li_gen = [separador]

        liJ = [(_("White"), "WHITE"), (_("Black"), "BLACK")]
        config = FormLayout.Combobox(_("Play with"), liJ)
        li_gen.append((config, color))

        li_gen.append((_("Mandatory moves") + ":", mandatory))
        li_gen.append(separador)
        li_gen.append((_("Moves until the control") + ":", control))
        li_gen.append(separador)
        li_gen.append(
            (_("Maximum number of lost centipawns to pass control") + ":",
             lost_points))
        li_gen.append(separador)

        dic_engines = self.configuration.dic_engines
        li_engines = EnginesBunch.lista(dic_engines)
        config = FormLayout.Spinbox(
            "%s: %s" % (_("Automatic selection"), _("number of engines")), 0,
            len(li_engines), 50)
        li_gen.append((config, num_engines))

        likeys = [(dic_engines[x].name, x) for x in li_engines
                  if x in dic_engines]
        config = FormLayout.Combobox(
            "%s: %s" % (_("Automatic selection"), _("bunch of engines")),
            likeys)
        li_gen.append((config, key_engine))
        li_gen.append(separador)

        config = FormLayout.Combobox(_("Engine that does the control"),
                                     self.configuration.comboMotores())
        li_gen.append((config, engine_control))
        li_gen.append(
            (_("Duration of analysis (secs)") + ":", float(engine_time)))

        li_gen.append(separador)

        li_gen.append((_("Automatic analysis") + ":", auto_analysis))

        li_gen.append(separador)

        li_gen.append(
            (_("Ask when the moves are different from the line") + ":",
             ask_movesdifferent))

        li = [("--", "")]
        for key, cm in self.configuration.dic_engines.items():
            li.append((cm.nombre_ext(), key))
        li = sorted(li, key=operator.itemgetter(1))

        li_ext = []

        for x in range(16):
            config = FormLayout.Combobox("%s %d" % (_("Engine"), x + 1), li)
            key = ext_engines[x] if len(ext_engines) > x else ""
            li_ext.append((config, key))

        liLevels = [separador]
        list_books = Books.ListBooks()
        list_books.restore_pickle(self.configuration.file_books)
        list_books.check()
        libooks = [(bookx.name, bookx) for bookx in list_books.lista]
        libooks.insert(0, ("--", None))
        li_books_sel = (("", ""), (_("Uniform random"),
                                   "au"), (_("Proportional random"), "ap"),
                        (_("Always the highest percentage"), "mp"))
        for level in range(5):
            n = level + 1
            title = "%s %d" % (_("Level"), n)
            # liLevels.append((None, title))
            tm = times[level] / 1000.0 if len(times) > level else 0.0
            liLevels.append(
                ("%s. %s:" % (title, _("Time engines think in seconds")), tm))

            bk = books[level] if len(books) > level else ""
            book = list_books.buscaLibro(bk) if bk else None
            config = FormLayout.Combobox(_("Book"), libooks)
            liLevels.append((config, book))

            config = FormLayout.Combobox(_("Book selection mode"),
                                         li_books_sel)
            liLevels.append((config, books_sel[level]))

        lista = []
        lista.append((li_gen, _("Basic data"), ""))
        lista.append((li_ext, _("Manual engine selection"), ""))
        lista.append((liLevels, _("Levels"), ""))

        resultado = FormLayout.fedit(lista,
                                     title=_("With engines"),
                                     parent=self,
                                     anchoMinimo=360,
                                     icon=Iconos.Study())
        if resultado is None:
            return

        accion, liResp = resultado

        selMotoresExt = []
        li_gen, li_ext, liLevels = liResp

        for key in li_ext:
            if key:
                selMotoresExt.append(key)

        reg = {}

        (
            reg["COLOR"],
            reg["MANDATORY"],
            reg["CONTROL"],
            reg["LOST_POINTS"],
            reg["NUM_ENGINES"],
            reg["KEY_ENGINE"],
            reg["ENGINE_CONTROL"],
            reg["ENGINE_TIME"],
            reg["AUTO_ANALYSIS"],
            reg["ASK_MOVESDIFFERENT"],
        ) = li_gen
        reg["EXT_ENGINES"] = selMotoresExt

        if (len(selMotoresExt) + reg["NUM_ENGINES"]) == 0:
            reg["NUM_ENGINES"] = 1

        times = []
        books = []
        books_sel = []
        for x in range(5):
            tm = int(liLevels[x * 3] * 1000)
            bk = liLevels[x * 3 + 1]
            bk_mode = liLevels[x * 3 + 2]
            if tm:
                times.append(tm)
                books.append(bk.name if bk else "")
                books_sel.append(bk_mode)
        if len(times) == 0:
            times.append(500)
            books.append(None)
        reg["TIMES"] = times
        reg["BOOKS"] = books
        reg["BOOKS_SEL"] = books_sel

        self.dbop.createTrainingEngines(reg, self.procesador)

        QTUtil2.message_bold(self, _("Created"))
Beispiel #15
0
    def remove_worst(self):
        form = FormLayout.FormLayout(self, _("Remove worst lines"),
                                     Iconos.OpeningLines())
        form.separador()
        liJ = [(_("White"), "WHITE"), (_("Black"), "BLACK")]
        form.combobox(_("Side"), liJ, "WHITE")
        form.separador()

        list_books = Books.ListBooks()
        list_books.restore_pickle(self.configuration.file_books)
        list_books.check()
        libooks = [(bookx.name, bookx) for bookx in list_books.lista]
        libooks.insert(0, ("--", None))
        form.combobox(_("Book"), libooks, None)
        form.separador()

        form.float(_("Duration of engine analysis (secs)"),
                   float(self.configuration.x_tutor_mstime / 1000.0))
        form.separador()

        resultado = form.run()
        if resultado:
            color, book, segs = resultado[1]
            ms = int(segs * 1000)
            if ms == 0:
                return
            if book:
                book.polyglot()
            si_white = color == "WHITE"
            dic = self.dbop.dicRepeFen(si_white)
            mensaje = _("Move") + "  %d/" + str(len(dic))
            tmpBP = QTUtil2.BarraProgreso(self, _("Remove worst lines"), "",
                                          len(dic))

            xmanager = self.procesador.creaManagerMotor(
                self.configuration.tutor, ms, 0, siMultiPV=False)

            st_borrar = set()

            ok = True

            for n, fen in enumerate(dic, 1):
                if tmpBP.is_canceled():
                    ok = False
                    break

                tmpBP.inc()
                tmpBP.mensaje(mensaje % n)

                dic_a1h8 = dic[fen]
                st_a1h8 = set(dic_a1h8.keys())
                li = []
                if book:
                    li_moves = book.get_list_moves(fen)
                    if li_moves:
                        # (from_sq, to_sq, promotion, "%-5s -%7.02f%% -%7d" % (pgn, pc, w), 1.0 * w / maxim))
                        li = [(m[0] + m[1] + m[2], m[4]) for m in li_moves
                              if m[0] + m[1] + m[2] in st_a1h8]
                        if li:
                            li.sort(key=lambda x: x[1], reverse=True)
                            st_ya = set(x[0] for x in li)
                            for a1h8 in st_a1h8:
                                if a1h8 not in st_ya:
                                    li.append((a1h8, 0))

                if len(li) == 0:
                    mrm = xmanager.analiza(fen)
                    for a1h8 in dic_a1h8:
                        rm, pos = mrm.buscaRM(a1h8)
                        li.append((a1h8, pos))
                    li.sort(key=lambda x: x[1])

                for a1h8, pos in li[1:]:
                    for num_linea in dic_a1h8[a1h8]:
                        st_borrar.add(num_linea)

            tmpBP.cerrar()

            xmanager.terminar()

            if ok:
                li_borrar = list(st_borrar)
                n = len(li_borrar)
                if n:
                    self.dbop.removeLines(li_borrar, _("Remove worst lines"))
                    QTUtil2.message_bold(self, _("Removed %d lines") % n)
                else:
                    QTUtil2.message_bold(self, _("Done"))
    def __init__(self, w_parent, listaMotores, engine, siTorneo=False):

        super(WEngine, self).__init__(w_parent)

        self.setWindowTitle(engine.version)
        self.setWindowIcon(Iconos.Motor())
        self.setWindowFlags(
            QtCore.Qt.WindowCloseButtonHint
            | QtCore.Qt.Dialog
            | QtCore.Qt.WindowTitleHint
            | QtCore.Qt.WindowMinimizeButtonHint
            | QtCore.Qt.WindowMaximizeButtonHint
        )

        scrollArea = wgen_options_engine(self, engine)

        self.motorExterno = engine
        self.liMotores = listaMotores
        self.siTorneo = siTorneo

        # Toolbar
        tb = QTUtil2.tbAcceptCancel(self)

        lbAlias = Controles.LB2P(self, _("Alias"))
        self.edAlias = Controles.ED(self, engine.key).anchoMinimo(360)

        lbNombre = Controles.LB2P(self, _("Name"))
        self.edNombre = Controles.ED(self, engine.name).anchoMinimo(360)

        lbInfo = Controles.LB(self, _("Information") + ": ")
        self.emInfo = Controles.EM(self, engine.id_info, siHTML=False).anchoMinimo(360).altoFijo(60)

        lbElo = Controles.LB(self, "ELO: ")
        self.sbElo = Controles.SB(self, engine.elo, 0, 4000)

        lbExe = Controles.LB(self, "%s: %s" % (_("File"), Util.relative_path(engine.path_exe)))

        if siTorneo:
            lbDepth = Controles.LB(self, _("Maximum depth") + ": ")
            self.sbDepth = Controles.SB(self, engine.depth, 0, 50)

            lbTime = Controles.LB(self, _("Maximum seconds to think") + ": ")
            self.sbTime = Controles.SB(self, engine.time, 0, 9999)

            lbBook = Controles.LB(self, _("Opening book") + ": ")
            fvar = Code.configuration.file_books
            self.list_books = Books.ListBooks()
            self.list_books.restore_pickle(fvar)
            # # Comprobamos que todos esten accesibles
            self.list_books.check()
            li = [(x.name, x.path) for x in self.list_books.lista]
            li.insert(0, ("* " + _("None"), "-"))
            li.insert(0, ("* " + _("Default"), "*"))
            self.cbBooks = Controles.CB(self, li, engine.book)
            btNuevoBook = Controles.PB(self, "", self.nuevoBook, plano=False).ponIcono(Iconos.Nuevo(), icon_size=16)
            # # Respuesta rival
            li = (
                (_("Uniform random"), "au"),
                (_("Proportional random"), "ap"),
                (_("Always the highest percentage"), "mp"),
            )
            self.cbBooksRR = QTUtil2.comboBoxLB(self, li, engine.bookRR)
            lyBook = (
                Colocacion.H()
                .control(lbBook)
                .control(self.cbBooks)
                .control(self.cbBooksRR)
                .control(btNuevoBook)
                .relleno()
            )
            lyDT = (
                Colocacion.H()
                .control(lbDepth)
                .control(self.sbDepth)
                .espacio(40)
                .control(lbTime)
                .control(self.sbTime)
                .relleno()
            )
            lyTorneo = Colocacion.V().otro(lyDT).otro(lyBook)

        # Layout
        ly = Colocacion.G()
        ly.controld(lbAlias, 0, 0).control(self.edAlias, 0, 1)
        ly.controld(lbNombre, 1, 0).control(self.edNombre, 1, 1)
        ly.controld(lbInfo, 2, 0).control(self.emInfo, 2, 1)
        ly.controld(lbElo, 3, 0).control(self.sbElo, 3, 1)
        ly.control(lbExe, 4, 0, 1, 2)

        if siTorneo:
            ly.otro(lyTorneo, 5, 0, 1, 2)

        layout = Colocacion.V().control(tb).espacio(30).otro(ly).control(scrollArea)
        self.setLayout(layout)

        self.edAlias.setFocus()
Beispiel #17
0
    def __init__(self, w_parent, nombre_torneo):

        torneo = self.torneo = Tournament.Tournament(nombre_torneo)

        titulo = nombre_torneo
        icono = Iconos.Torneos()
        extparam = "untorneo_v1"
        QTVarios.WDialogo.__init__(self, w_parent, titulo, icono, extparam)

        self.configuration = Code.configuration

        # Datos

        self.liEnActual = []
        self.xjugar = None
        self.liResult = None
        self.last_change = Util.today()
        self.li_results = []

        # Toolbar
        tb = Controles.TBrutina(self, icon_size=24)
        tb.new(_("Close"), Iconos.MainMenu(), self.terminar)
        tb.new(_("Launch a worker"), Iconos.Lanzamiento(), self.gm_launch)

        # Tabs
        self.tab = tab = Controles.Tab()

        # Tab-configuration --------------------------------------------------
        w = QtWidgets.QWidget()

        # Adjudicator
        lb_resign = Controles.LB(
            self, "%s (%s): " %
            (_("Minimum centipawns to assign winner"), "0=%s" % _("Disable")))
        self.ed_resign = Controles.ED(self).tipoInt(
            torneo.resign()).anchoFijo(30)
        bt_resign = Controles.PB(self, "", rutina=self.borra_resign).ponIcono(
            Iconos.Reciclar())

        # Draw-plys
        lbDrawMinPly = Controles.LB(
            self, "%s (%s): " %
            (_("Minimum moves to assign draw"), "0=%s" % _("Disable")))
        self.sbDrawMinPly = Controles.SB(self, torneo.drawMinPly(), 20, 1000)
        # Draw-puntos
        lb_draw_range = Controles.LB(
            self,
            _("Maximum centipawns to assign draw") + ": ")
        self.ed_draw_range = Controles.ED(self).tipoInt(
            torneo.drawRange()).anchoFijo(30)
        bt_draw_range = Controles.PB(
            self, "", rutina=self.borra_draw_range).ponIcono(Iconos.Reciclar())

        # adjudicator
        self.liMotores = self.configuration.comboMotoresMultiPV10()
        self.cbJmotor, self.lbJmotor = QTUtil2.comboBoxLB(
            self, self.liMotores, torneo.adjudicator(), _("Engine"))
        self.edJtiempo = Controles.ED(self).tipoFloat(
            torneo.adjudicator_time()).anchoFijo(50)
        self.lbJtiempo = Controles.LB2P(self, _("Time in seconds"))
        layout = Colocacion.G()
        layout.controld(self.lbJmotor, 3, 0).control(self.cbJmotor, 3, 1)
        layout.controld(self.lbJtiempo, 4, 0).control(self.edJtiempo, 4, 1)
        self.gbJ = Controles.GB(self, _("Adjudicator"), layout)
        self.gbJ.setCheckable(True)
        self.gbJ.setChecked(torneo.adjudicator_active())

        lbBook = Controles.LB(self, _("Opening book") + ": ")
        fvar = self.configuration.file_books
        self.list_books = Books.ListBooks()
        self.list_books.restore_pickle(fvar)
        # Comprobamos que todos esten accesibles
        self.list_books.check()
        li = [(x.name, x.path) for x in self.list_books.lista]
        li.insert(0, ("* " + _("None"), "-"))
        self.cbBooks = Controles.CB(self, li, torneo.book())
        btNuevoBook = Controles.PB(self, "", self.nuevoBook,
                                   plano=False).ponIcono(Iconos.Nuevo(),
                                                         icon_size=16)
        lyBook = Colocacion.H().control(
            self.cbBooks).control(btNuevoBook).relleno()

        lbBookDepth = Controles.LB(self,
                                   _("Max depth of book (0=Maximum)") + ": ")
        self.sbBookDepth = Controles.SB(self, torneo.bookDepth(), 0, 200)

        lb_slow = Controles.LB(self,
                               _("Slow down the movement of pieces") + ": ")
        self.chb_slow = Controles.CHB(self, " ", self.torneo.slow_pieces())

        # Posicion inicial
        lbFEN = Controles.LB(self, _("Initial position") + ": ")
        self.fen = torneo.fen()
        self.btPosicion = Controles.PB(self, " " * 5 + _("Change") + " " * 5,
                                       self.posicionEditar).ponPlano(False)
        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"))
        lyFEN = Colocacion.H().control(self.btPosicionQuitar).control(
            self.btPosicion).control(self.btPosicionPegar).relleno()

        # Norman Pollock
        lbNorman = Controles.LB(
            self,
            '%s(<a href="https://komodochess.com/pub/40H-pgn-utilities">?</a>): '
            % _("Initial position from Norman Pollock openings database"),
        )
        self.chbNorman = Controles.CHB(self, " ", self.torneo.norman())

        # Layout
        layout = Colocacion.G()
        ly_res = Colocacion.H().control(
            self.ed_resign).control(bt_resign).relleno()
        ly_dra = Colocacion.H().control(
            self.ed_draw_range).control(bt_draw_range).relleno()
        layout.controld(lb_resign, 0, 0).otro(ly_res, 0, 1)
        layout.controld(lbDrawMinPly, 1, 0).control(self.sbDrawMinPly, 1, 1)
        layout.controld(lb_draw_range, 2, 0).otro(ly_dra, 2, 1)
        layout.controld(lbBook, 3, 0).otro(lyBook, 3, 1)
        layout.controld(lbBookDepth, 4, 0).control(self.sbBookDepth, 4, 1)
        layout.controld(lbFEN, 5, 0).otro(lyFEN, 5, 1)
        layout.controld(lbNorman, 6, 0).control(self.chbNorman, 6, 1)
        layout.controld(lb_slow, 7, 0).control(self.chb_slow, 7, 1)
        layoutV = Colocacion.V().relleno().otro(layout).control(
            self.gbJ).relleno()
        layoutH = Colocacion.H().relleno().otro(layoutV).relleno()

        # Creamos
        w.setLayout(layoutH)
        tab.nuevaTab(w, _("Configuration"))

        # Tab-engines --------------------------------------------------
        self.splitterEngines = QtWidgets.QSplitter(self)
        self.register_splitter(self.splitterEngines, "engines")
        # TB
        li_acciones = [
            (_("New"), Iconos.TutorialesCrear(), self.enNuevo),
            None,
            (_("Modify"), Iconos.Modificar(), self.enModificar),
            None,
            (_("Remove"), Iconos.Borrar(), self.enBorrar),
            None,
            (_("Copy"), Iconos.Copiar(), self.enCopiar),
            None,
            (_("Import"), Iconos.MasDoc(), self.enImportar),
            None,
        ]
        tbEnA = Controles.TBrutina(self,
                                   li_acciones,
                                   icon_size=16,
                                   style=QtCore.Qt.ToolButtonTextBesideIcon)

        # Grid engine
        o_columns = Columnas.ListaColumnas()
        o_columns.nueva("NUM", _("N."), 50, centered=True)
        o_columns.nueva("ALIAS", _("Alias"), 209)
        self.gridEnginesAlias = Grid.Grid(self,
                                          o_columns,
                                          siSelecFilas=True,
                                          siSeleccionMultiple=True,
                                          xid=GRID_ALIAS)
        self.register_grid(self.gridEnginesAlias)

        w = QtWidgets.QWidget()
        ly = Colocacion.V().control(self.gridEnginesAlias).margen(0)
        w.setLayout(ly)
        self.splitterEngines.addWidget(w)

        o_columns = Columnas.ListaColumnas()
        o_columns.nueva("CAMPO", _("Label"), 200, siDerecha=True)
        o_columns.nueva("VALOR", _("Value"), 286)
        self.gridEnginesValores = Grid.Grid(self,
                                            o_columns,
                                            siSelecFilas=False,
                                            xid=GRID_VALUES)
        self.register_grid(self.gridEnginesValores)

        w = QtWidgets.QWidget()
        ly = Colocacion.V().control(self.gridEnginesValores).margen(0)
        w.setLayout(ly)
        self.splitterEngines.addWidget(w)

        self.splitterEngines.setSizes([250, 520])  # por defecto

        w = QtWidgets.QWidget()
        ly = Colocacion.V().control(tbEnA).control(self.splitterEngines)
        w.setLayout(ly)
        tab.nuevaTab(w, _("Engines"))

        # Creamos

        # Tab-games queued--------------------------------------------------
        w = QtWidgets.QWidget()
        # TB
        li_acciones = [
            (_("New"), Iconos.TutorialesCrear(), self.gm_crear_queued),
            None,
            (_("Remove"), Iconos.Borrar(), self.gm_borrar_queued),
            None,
        ]
        tbEnG = Controles.TBrutina(self,
                                   li_acciones,
                                   icon_size=16,
                                   style=QtCore.Qt.ToolButtonTextBesideIcon)

        o_columns = Columnas.ListaColumnas()
        o_columns.nueva("NUM", _("N."), 50, centered=True)
        o_columns.nueva("WHITE", _("White"), 190, centered=True)
        o_columns.nueva("BLACK", _("Black"), 190, centered=True)
        o_columns.nueva("TIME", _("Time"), 170, centered=True)
        # o_columns.nueva("STATE", _("State"), 190, centered=True)
        self.gridGamesQueued = Grid.Grid(self,
                                         o_columns,
                                         siSelecFilas=True,
                                         siSeleccionMultiple=True,
                                         xid=GRID_GAMES_QUEUED)
        self.register_grid(self.gridGamesQueued)
        # Layout
        layout = Colocacion.V().control(tbEnG).control(self.gridGamesQueued)

        # Creamos
        w.setLayout(layout)
        tab.nuevaTab(w, _("Games queued"))

        # Tab-games terminados--------------------------------------------------
        w = QtWidgets.QWidget()
        # TB
        li_acciones = [
            (_("Remove"), Iconos.Borrar(), self.gm_borrar_finished),
            None,
            (_("Show"), Iconos.PGN(), self.gm_show_finished),
            None,
            (_("Save") + "(%s)" % _("PGN"), Iconos.GrabarComo(),
             self.gm_save_pgn),
            None,
            (_("Save") + "(%s)" % _("Database"), Iconos.GrabarComo(),
             self.gm_save_database),
            None,
        ]
        tbEnGt = Controles.TBrutina(self,
                                    li_acciones,
                                    icon_size=16,
                                    style=QtCore.Qt.ToolButtonTextBesideIcon)

        o_columns = Columnas.ListaColumnas()
        o_columns.nueva("NUM", _("N."), 50, centered=True)
        o_columns.nueva("WHITE", _("White"), 190, centered=True)
        o_columns.nueva("BLACK", _("Black"), 190, centered=True)
        o_columns.nueva("TIME", _("Time"), 170, centered=True)
        o_columns.nueva("RESULT", _("Result"), 190, centered=True)
        self.gridGamesFinished = Grid.Grid(self,
                                           o_columns,
                                           siSelecFilas=True,
                                           siSeleccionMultiple=True,
                                           xid=GRID_GAMES_FINISHED)
        self.register_grid(self.gridGamesFinished)
        # Layout
        layout = Colocacion.V().control(tbEnGt).control(self.gridGamesFinished)

        # Creamos
        w.setLayout(layout)
        tab.nuevaTab(w, _("Games finished"))

        # Tab-resultado --------------------------------------------------
        w = QtWidgets.QWidget()

        # Grid
        wh = _("W.")
        bl = _("B.")
        o_columns = Columnas.ListaColumnas()
        o_columns.nueva("NUM", _("N."), 35, centered=True)
        o_columns.nueva("ENGINE", _("Engine"), 120, centered=True)
        o_columns.nueva("SCORE", _("Score") + "%", 50, centered=True)
        o_columns.nueva("WIN", _("Wins"), 50, centered=True)
        o_columns.nueva("DRAW", _("Draws"), 50, centered=True)
        o_columns.nueva("LOST", _("Losses"), 50, centered=True)
        o_columns.nueva("WIN-WHITE",
                        "%s %s" % (wh, _("Wins")),
                        60,
                        centered=True)
        o_columns.nueva("DRAW-WHITE",
                        "%s %s" % (wh, _("Draws")),
                        60,
                        centered=True)
        o_columns.nueva("LOST-WHITE",
                        "%s %s" % (wh, _("Losses")),
                        60,
                        centered=True)
        o_columns.nueva("WIN-BLACK",
                        "%s %s" % (bl, _("Wins")),
                        60,
                        centered=True)
        o_columns.nueva("DRAW-BLACK",
                        "%s %s" % (bl, _("Draws")),
                        60,
                        centered=True)
        o_columns.nueva("LOST-BLACK",
                        "%s %s" % (bl, _("Losses")),
                        60,
                        centered=True)
        o_columns.nueva("GAMES", _("Games"), 50, centered=True)
        self.gridResults = Grid.Grid(self,
                                     o_columns,
                                     siSelecFilas=True,
                                     xid=GRID_RESULTS)
        self.register_grid(self.gridResults)

        self.qtColor = {
            "WHITE": QTUtil.qtColorRGB(255, 250, 227),
            "BLACK": QTUtil.qtColorRGB(221, 255, 221),
            "SCORE": QTUtil.qtColorRGB(170, 170, 170),
        }

        # Layout
        layout = Colocacion.V().control(self.gridResults)

        # Creamos
        w.setLayout(layout)
        tab.nuevaTab(w, _("Results"))

        # Layout
        # tab.set_position("W")
        layout = Colocacion.V().control(tb).espacio(-3).control(tab).margen(2)
        self.setLayout(layout)

        self.restore_video(siTam=True, anchoDefecto=800, altoDefecto=430)

        self.gridEnginesAlias.gotop()

        self.ed_resign.setFocus()

        self.muestraPosicion()

        QtCore.QTimer.singleShot(5000, self.comprueba_cambios)
        self.rotulos_tabs()