def __init__(self, nom_fichero): self.nom_fichero = nom_fichero self._conexion = sqlite3.connect(nom_fichero) self.cache = {} self.max_cache = 1000 self.del_cache = 100 self.grupo = 0 self.history = collections.OrderedDict() self.li_xpv = self.init_database() self.db_config = UtilSQL.DictSQL(nom_fichero, tabla="CONFIG") self.db_fenvalues = UtilSQL.DictSQL(nom_fichero, tabla="FENVALUES") self.db_history = UtilSQL.DictSQL(nom_fichero, tabla="HISTORY") self.db_cache_engines = None self.basePV = self.getconfig("BASEPV", "") self.title = self.getconfig("TITLE", os.path.basename(nom_fichero).split(".")[0]) # Check visual if not UtilSQL.check_table_in_db(nom_fichero, "Flechas"): file_resources = Code.configuration.ficheroRecursos for tabla in ("Config", "Flechas", "Marcos", "SVGs", "Markers"): dbr = UtilSQL.DictSQL(nom_fichero, tabla=tabla) dbv = UtilSQL.DictSQL(file_resources, tabla=tabla) dbr.copy_from(dbv) dbr.close() dbv.close() self.board = None
def __init__(self, nom_fichero): self.nom_fichero = nom_fichero self._conexion = sqlite3.connect(nom_fichero) self.cache = {} self.max_cache = 1000 self.del_cache = 100 self.grupo = 0 self.history = collections.OrderedDict() self.li_xpv = self.init_database() self.db_config = UtilSQL.DictSQL(nom_fichero, tabla="CONFIG") self.db_fenvalues = UtilSQL.DictSQL(nom_fichero, tabla="FENVALUES") self.db_history = UtilSQL.DictSQL(nom_fichero, tabla="HISTORY") self.db_cache_engines = None self.basePV = self.getconfig("BASEPV", "") self.title = self.getconfig( "TITLE", os.path.basename(nom_fichero).split(".")[0]) self.tablero = None
def get_puntos_rival(self, rival_key): with UtilSQL.DictSQL(self.file_path) as db: txt = db[rival_key] categorias = Categorias() if txt is not None: categorias.lee(txt) return categorias.puntuacion()
def put_result(self): self.state = ST_ENDGAME self.tablero.disable_all() mensaje = _("Game ended") txt, porc, txtResumen = self.motorGM.resultado(self.game) mensaje += "<br><br>" + txt if self.siJuez: mensaje += "<br><br><b>%s</b> = %+d<br>" % (_("Points accumulated"), self.puntos) self.mensajeEnPGN(mensaje) dbHisto = UtilSQL.DictSQL(self.configuracion.ficheroGMhisto) gmK = "P_%s" % self.gm if self.modo == "personal" else self.gm dic = {} dic["FECHA"] = Util.today() dic["PUNTOS"] = self.puntos dic["PACIERTOS"] = porc dic["JUEZ"] = self.engine dic["TIEMPO"] = self.vtime dic["RESUMEN"] = txtResumen liHisto = dbHisto[gmK] if liHisto is None: liHisto = [] liHisto.insert(0, dic) dbHisto[gmK] = liHisto dbHisto.pack() dbHisto.close()
def determinaColor(self, nivel): key = "%s-%d" % (self._TIPO, nivel) dd = UtilSQL.DictSQL(self._fichEstad, tabla="color") previo = dd.get(key, random.randint(0, 1) == 0) dd.close() return not previo
def determinaColor(self, engine_rival): key = engine_rival.name dd = UtilSQL.DictSQL(self.configuration.fichEstadMicElo, tabla="color") previo = dd.get(key, random.randint(0, 1) == 0) dd.close() return not previo
def __init__(self, w_parent, game, nj, procesador): main_window = w_parent self.procesador = procesador titulo = _("Moves tree") icono = Iconos.Arbol() extparam = "moves" QTVarios.WDialogo.__init__(self, main_window, titulo, icono, extparam) dicVideo = self.restore_dicvideo() self.dbCache = UtilSQL.DictSQL(Code.configuration.ficheroMoves) if nj >= 0: position = game.move(nj).position else: position = game.last_position self.listaMoves = ListaMoves(None, position.fen(), self.dbCache) tb = QTVarios.LCTB(self) tb.new(_("Save"), Iconos.Grabar(), self.grabar) tb.new(_("Cancel"), Iconos.Cancelar(), self.cancelar) self.infoMove = InfoMove(position.is_white) w = QtWidgets.QWidget(self) ly = Colocacion.V().control(tb).control(self.infoMove) w.setLayout(ly) self.wmoves = WMoves(self, procesador) self.splitter = splitter = QtWidgets.QSplitter(self) splitter.addWidget(w) splitter.addWidget(self.wmoves) ly = Colocacion.H().control(splitter).margen(0) self.setLayout(ly) self.wmoves.tree.setFocus() anchoBoard = self.infoMove.board.width() self.restore_video(anchoDefecto=869 - 242 + anchoBoard) if not dicVideo: dicVideo = { "TREE_3": 27, "SPLITTER": [260 - 242 + anchoBoard, 617], "TREE_1": 49, "TREE_2": 383, "TREE_4": 25, } sz = dicVideo.get("SPLITTER", None) if sz: self.splitter.setSizes(sz) for x in range(1, 6): w = dicVideo.get("TREE_%d" % x, None) if w: self.wmoves.tree.setColumnWidth(x, w)
def determinaColor(self, datosMotor): key = datosMotor.name dd = UtilSQL.DictSQL(self.configuracion.fichEstadMicElo, tabla="color") previo = dd.get(key, random.randint(0, 1) == 0) dd.close() return not previo
def determina_side(self, datosMotor): key = "%s-%d" % (datosMotor.key, datosMotor.depth if datosMotor.depth else 0) dd = UtilSQL.DictSQL(self.configuration.fichEstadElo, tabla="color") previo = dd.get(key, random.randint(0, 1) == 0) dd.close() return not previo
def cambiaConfBoard(self, config_board): xid = config_board._id if xid: db = UtilSQL.DictSQL(self.ficheroConfBoards) self.dic_conf_boards_pk[xid] = db[xid] = config_board.graba() db.close() self.leeConfBoards()
def import_previous(self): old_folder = os.path.join( Code.configuration.folder_polyglots_factory(), "old") mkbin_path = self.path[:-5] + "mkbin" if os.path.isfile(mkbin_path): pol_mkbin = FasterCode.Polyglot(mkbin_path) for entry in pol_mkbin: self.insert_entry(entry) self.conexion.commit() pol_mkbin.close() Util.create_folder(old_folder) shutil.move(mkbin_path, old_folder) dbbin_path = self.path[:-5] + "dbbin" if os.path.isfile(dbbin_path): db_ant = UtilSQL.DictSQL(dbbin_path) dic = db_ant.as_dictionary() db_ant.close() for key_str, dic_moves in dic.items(): for move, entry in dic_moves.items(): sql = "SELECT ROWID FROM BOOK WHERE CKEY=? AND MOVE=?" cursor = self.conexion.execute(sql, (key_str, move)) row = cursor.fetchone() if row: rowid = row[0] self.update_entry(rowid, entry) else: self.insert_entry(entry) self.conexion.commit() Util.create_folder(old_folder) shutil.move(dbbin_path, old_folder)
def add_db(self, file, tabla): db = UtilSQL.DictSQL(file, tabla) keys = db.keys() for k in keys: self.add_bin(k, db[k]) db.close()
def save_pos(self, pos_training): db = UtilSQL.DictSQL(self.configuracion.ficheroTrainings) data = db[self.entreno] if data is None: data = {} data["POSULTIMO"] = pos_training db[self.entreno] = data db.close()
def config(self, key, value, default): db_config = UtilSQL.DictSQL(self.file, tabla="config", max_cache=0) if value is None: value = db_config.get(key, default) else: db_config[key] = value db_config.close() return value
def finalizar(self): self.informacion_activable = True self.board.showCoordenadas(True) self.main_window.activaJuego(True, False, siAyudas=False) self.remove_hints() self.main_window.pon_toolbar( (TB_CLOSE, TB_REINIT, TB_CONFIG, TB_UTILITIES)) if self.cancelado: self.game = self.game_objetivo self.goto_end() blancas, negras, fecha, event, result = "", "", "", "", "" for key, value in self.game_objetivo.li_tags: key = key.upper() if key == "WHITE": blancas = value elif key == "BLACK": negras = value elif key == "DATE": fecha = value elif key == "EVENT": event = value elif key == "RESULT": result = value self.set_label1( "%s - %s<br> %s: <b>%s</b><br>%s: <b>%s</b><br>%s: <b>%s</b>" % (fecha, event, _("White"), blancas, _("Black"), negras, _("Result"), result)) numjug = self.jugada_actual if numjug > 0: self.set_label2( '%s: <b>%d</b><br>%s: %0.2f"<br>%s: <b>%d</b><br>%s: <b>%d</b>' % ( _("Moves"), numjug, _("Average time"), self.vtime / numjug, _("Errors"), self.errores, _("Hints"), self.ayudas_recibidas, )) if numjug > 2: db = UtilSQL.DictSQL(self.configuration.ficheroAnotar) f = Util.today() key = "%04d-%02d-%02d %02d:%02d:%02d" % ( f.year, f.month, f.day, f.hour, f.minute, f.second) db[key] = { "PC": self.game_objetivo.save(), "MOVES": numjug, "TIME": self.vtime / numjug, "HINTS": self.ayudas_recibidas, "ERRORS": self.errores, "COLOR": self.si_blancas_abajo, "TOTAL_MOVES": len(self.game_objetivo) } db.close()
def __init__(self, fichdb): SQLBase.DBBase.__init__(self, fichdb) self.dicDB = UtilSQL.DictSQL(fichdb, tabla="CONFIG") self.tabla = "WORK" self.testTabla() self.releer()
def leeParametros(self): param = UtilSQL.DictSQL(self.configuracion.ficheroDailyTest, tabla="parametros") engine = param.get("MOTOR", self.configuracion.tutor_inicial) segundos = param.get("SEGUNDOS", 7) pruebas = param.get("PRUEBAS", 5) fns = param.get("FNS", "") param.close() return engine, segundos, pruebas, fns
def leeParametros(self): param = UtilSQL.DictSQL(self.configuration.ficheroPotencia, tabla="parametros") engine = param.get("ENGINE", "stockfish") segundos = param.get("SEGUNDOS", 5) min_min = param.get("MIN_MIN", 1) min_max = param.get("MIN_MAX", 5) param.close() return engine, segundos, min_min, min_max
def leeConfTableros(self): db = UtilSQL.DictSQL(self.ficheroConfTableros) self.dic_conf_boards_pk = db.as_dictionary() if not ("BASE" in self.dic_conf_boards_pk): with open(Code.path_resource("IntFiles", "basepk.board"), "rb") as f: var = pickle.loads(f.read()) db["BASE"] = self.dic_conf_boards_pk["BASE"] = var # with open("../resources/IntFiles/basepk.board", "wb") as f: # f.write(pickle.dumps(db["BASE"])) db.close()
def get_current_rival_key(self): with UtilSQL.DictSQL(self.file_path, tabla="config") as db: current_rival_key = db["CURRENT_RIVAL_KEY"] if current_rival_key is None: elo = 9999 for key, cm in self.configuration.dic_engines.items(): if 0 < cm.elo < elo: current_rival_key = key elo = cm.elo return current_rival_key
def __init__(self, fichero_db): fichero_tactic = Code.path_resource("IntFiles", "tactic0.bm") self.dic = self.lee(fichero_tactic) self.li_bloque = None self.li_bloque_sol = [] self.registro = None self.current_key = None self.db = UtilSQL.DictSQL(fichero_db) self.db_keys = self.db.keys(si_ordenados=True, si_reverse=True)
def playBeep(self): if self.replayBeep is None: db = UtilSQL.DictSQL(Code.configuration.file_sounds(), "general") keys = db.keys() self.replayBeep = "MC" in keys if self.replayBeep: self.playClave("MC", False) else: QTUtil.beep()
def __init__(self, procesador, path_bloque): QTVarios.WDialogo.__init__(self, procesador.main_window, _("The board at a glance"), Iconos.Gafas(), "visualizaBase") self.procesador = procesador self.configuration = procesador.configuration self.path_bloque = path_bloque file = os.path.join(self.configuration.carpeta_results, os.path.basename(path_bloque) + "db") self.historico = UtilSQL.DictSQL(file) self.li_histo = self.calcListaHistorico() # Historico o_columns = Columnas.ListaColumnas() o_columns.nueva("SITE", _("Site"), 100, centered=True) o_columns.nueva("DATE", _("Date"), 100, centered=True) o_columns.nueva("LEVEL", _("Level"), 80, centered=True) o_columns.nueva("TIME", _("Time used"), 80, centered=True) o_columns.nueva("ERRORS", _("Errors"), 80, centered=True) o_columns.nueva("INTERVAL", _("Interval"), 100, centered=True) o_columns.nueva("POSITION", _("Position"), 80, centered=True) o_columns.nueva("COLOR", _("Square color"), 80, centered=True) o_columns.nueva("ISATTACKED", _("Is attacked?"), 80, centered=True) o_columns.nueva("ISATTACKING", _("Is attacking?"), 80, centered=True) self.ghistorico = Grid.Grid(self, o_columns, siSelecFilas=True, siSeleccionMultiple=True) self.ghistorico.setMinimumWidth(self.ghistorico.anchoColumnas() + 20) # Tool bar li_acciones = ( (_("Close"), Iconos.MainMenu(), self.terminar), None, (_("Play"), Iconos.Empezar(), self.play), None, (_("New"), Iconos.Nuevo(), self.new), None, (_("Remove"), Iconos.Borrar(), self.remove), None, ) self.tb = Controles.TBrutina(self, li_acciones) # Colocamos ly = Colocacion.V().control(self.tb).control(self.ghistorico).margen(3) self.setLayout(ly) self.register_grid(self.ghistorico) self.restore_video() self.ghistorico.gotop()
def grabar(self): if not self.lee_filtro_actual(): return with UtilSQL.DictSQL(self.dbSaveNom, tabla="Filters") as dbc: liConf = dbc.keys(si_ordenados=True) if len(liConf) == 0 and len(self.liFiltro) == 0: return menu = Controles.Menu(self) SELECCIONA, BORRA, GRABA = range(3) for x in liConf: menu.opcion((SELECCIONA, x), x, Iconos.PuntoAzul()) menu.separador() if len(self.liFiltro) > 0: submenu = menu.submenu(_("Save current"), Iconos.Mas()) if liConf: for x in liConf: submenu.opcion((GRABA, x), x, Iconos.PuntoAmarillo()) submenu.separador() submenu.opcion((GRABA, None), _("New"), Iconos.NuevoMas()) if liConf: menu.separador() submenu = menu.submenu(_("Remove"), Iconos.Delete()) for x in liConf: submenu.opcion((BORRA, x), x, Iconos.PuntoRojo()) resp = menu.lanza() if resp: op, name = resp if op == SELECCIONA: liFiltro = dbc[name] self.lee_filtro(liFiltro) elif op == BORRA: if QTUtil2.pregunta(self, _X(_("Delete %1 ?"), name)): del dbc[name] elif op == GRABA: if self.lee_filtro_actual(): if name is None: liGen = [FormLayout.separador] liGen.append((_("Name") + ":", "")) resultado = FormLayout.fedit(liGen, title=_("Filter"), parent=self, icon=Iconos.Libre()) if resultado: accion, liGen = resultado name = liGen[0].strip() if name: dbc[name] = self.liFiltro else: dbc[name] = self.liFiltro
def puntuacion(self): with UtilSQL.DictSQL(self.file_path) as db: p = 0 for grupo in self.grupos.liGrupos: for rival in grupo.li_rivales: txt = db[rival.key] if txt: categorias = Categorias() categorias.lee(txt) p += categorias.puntuacion() return p
def leeConfBoards(self): db = UtilSQL.DictSQL(self.ficheroConfBoards) self.dic_conf_boards_pk = db.as_dictionary() if not ("BASE" in self.dic_conf_boards_pk): with open(Code.path_resource("IntFiles", "basepk.board"), "rb") as f: var = pickle.loads(f.read()) var['x_anchoPieza'] = int(QTUtil.altoEscritorio() * 8 / 100) db["BASE"] = self.dic_conf_boards_pk["BASE"] = var # with open("../resources/IntFiles/basepk.board", "wb") as f: # f.write(pickle.dumps(db["BASE"])) db.close()
def __init__(self, procesador): QTVarios.WDialogo.__init__(self, procesador.main_window, _("Your daily test"), Iconos.DailyTest(), "nivelBase") self.procesador = procesador self.configuration = procesador.configuration self.historico = UtilSQL.DictSQL(self.configuration.ficheroDailyTest) self.calcListaHistorico() self.engine, self.segundos, self.pruebas, self.fns = self.leeParametros( ) # Historico o_columns = Columnas.ListaColumnas() o_columns.nueva("FECHA", _("Date"), 120, centered=True) o_columns.nueva("MPUNTOS", _("Points lost"), 100, centered=True) o_columns.nueva("MTIEMPOS", _("Time"), 80, centered=True) o_columns.nueva("ENGINE", _("Engine"), 120, centered=True) o_columns.nueva("SEGUNDOS", _("Second(s)"), 80, centered=True) o_columns.nueva("PRUEBAS", _("N. of tests"), 80, centered=True) o_columns.nueva("FNS", _("File"), 150, centered=True) self.ghistorico = Grid.Grid(self, o_columns, siSelecFilas=True, siSeleccionMultiple=True) self.ghistorico.setMinimumWidth(self.ghistorico.anchoColumnas() + 20) # Tool bar li_acciones = ( (_("Close"), Iconos.MainMenu(), self.terminar), None, (_("Start"), Iconos.Empezar(), self.empezar), None, (_("Configuration"), Iconos.Opciones(), self.configurar), None, (_("Remove"), Iconos.Borrar(), self.borrar), None, ) tb = QTVarios.LCTB(self, li_acciones) # Colocamos ly = Colocacion.V().control(tb).control(self.ghistorico).margen(3) self.setLayout(ly) self.register_grid(self.ghistorico) self.restore_video()
def __init__(self, procesador, tipo): # Variables self.configuration = procesador.configuration self.tipo = tipo self.fichDB = self.configuration.ficheroBoxing + tipo self.db = UtilSQL.DictSQL(self.fichDB) self.conf = self.db["CONFIG"] if self.conf is None: self.conf = {"SEGUNDOS": 5, "PUNTOS": 100, "NIVELHECHO": 0, "MAXERROR": 0} self.liMotores = self.configuration.comboMotores() # name, key self.claveActual = self.calcClaveActual() self.dicActual = self.dameDicActual()
def configurar(self): # Datos li_gen = [(None, None)] # # Motor mt = self.configuration.tutor_inicial if self.engine is None else self.engine li_combo = [mt] for name, key in self.configuration.comboMotoresMultiPV10(): li_combo.append((key, name)) li_gen.append((_("Engine") + ":", li_combo)) # # Segundos a pensar el tutor config = FormLayout.Spinbox(_("Duration of engine analysis (secs)"), 1, 99, 50) li_gen.append((config, self.segundos)) # Pruebas config = FormLayout.Spinbox(_("N. of tests"), 1, 40, 40) li_gen.append((config, self.pruebas)) # Fichero config = FormLayout.Fichero(_("File"), "%s (*.fns);;%s PGN (*.pgn)" % (_("List of FENs"), _("File")), False, anchoMinimo=280) li_gen.append((config, self.fns)) # Editamos resultado = FormLayout.fedit(li_gen, title=_("Configuration"), parent=self, icon=Iconos.Opciones()) if resultado: accion, li_resp = resultado self.engine = li_resp[0] self.segundos = li_resp[1] self.pruebas = li_resp[2] self.fns = li_resp[3] param = UtilSQL.DictSQL(self.configuration.ficheroDailyTest, tabla="parametros") param["ENGINE"] = self.engine param["SEGUNDOS"] = self.segundos param["PRUEBAS"] = self.pruebas param["FNS"] = self.fns param.close()
def import_openingline(self, base_folder, ori_path: str): ori_path = os.path.abspath(ori_path) ori_folder = os.path.dirname(ori_path) subfolder = os.path.relpath(ori_folder, base_folder) if subfolder == ".": dest_path = os.path.join(Code.configuration.folder_base_openings, os.path.basename(ori_path)) op_idx = os.path.join(Code.configuration.folder_base_openings, "openinglines.pk") else: dest_path = os.path.join(Code.configuration.folder_base_openings, subfolder, os.path.basename(ori_path)) folder_dest = os.path.dirname(dest_path) if not Util.create_folder(folder_dest): try: os.makedirs(folder_dest) except: pass op_idx = os.path.join(Code.configuration.folder_base_openings, subfolder, "openinglines.pk") Util.remove_file(op_idx) dest_path = Util.filename_unique(dest_path) for tabla in ("CONFIG", "FEN", "FENVALUES"): db11 = DicSQLV11(ori_path, tabla=tabla) if len(db11) > 0: db = UtilSQL.DictSQL(dest_path, tabla=tabla) li_keys = db11.keys() for key in li_keys: try: db[key] = db11[key] except: pass db.close() db11.close() conexion_dest = sqlite3.connect(dest_path) conexion_dest.execute( "CREATE TABLE IF NOT EXISTS LINES( XPV TEXT PRIMARY KEY );") conexion_dest.commit() conexion_ori = sqlite3.connect(ori_path) cursor_ori = conexion_ori.execute("SELECT XPV FROM LINES") for raw in cursor_ori.fetchall(): conexion_dest.execute("INSERT INTO LINES( XPV ) VALUES( ? )", raw) conexion_dest.commit() conexion_ori.close() conexion_dest.close()