def voyager_position(wowner, position, si_esconde: bool = True, wownerowner=None): pos_ownerowner = None pos = None if si_esconde: pos = QTUtil.escondeWindow(wowner) if wownerowner: pos_ownerowner = QTUtil.escondeWindow(wownerowner) game = Game.Game(ini_posicion=position) dlg = Voyager(wowner, False, game) resp = dlg.resultado if dlg.exec_() else None if si_esconde: if wownerowner: wownerowner.show() wownerowner.move(pos_ownerowner) QTUtil.refresh_gui() time.sleep(0.01) wowner.show() wowner.move(pos) QTUtil.refresh_gui() time.sleep(0.01) return resp
def grid_cambiado_registro(self, grid, row, column): self.game = Game.Game(self.position) self.game.read_pv(self.list_rm[row].rm.pv) self.maxMoves = len(self.game) self.mueve(siInicio=True) self.grid.setFocus()
def __init__(self): self.date = datetime.datetime.now() self.xid = Util.new_id() self.game = Game.Game() self.current_posmove = 0 self.current_depth = 0 self.tries = [] # pos,depth,success,time
def __init__(self, moveOwner, fen, dbCache): self.moveOwner = moveOwner self.dbCache = dbCache if not moveOwner: self.nivel = 0 cp = Position.Position() cp.read_fen(fen) self.gameBase = Game.Game(cp) else: self.nivel = self.moveOwner.listaMovesPadre.nivel + 1 self.gameBase = self.moveOwner.game.copia() self.fenm2 = self.gameBase.last_position.fenm2() dicCache = self.dbCache[self.fenm2] FasterCode.set_fen(self.fenm2 + " 0 1") liMov = [xpv[1:] for xpv in FasterCode.get_moves()] liMov.sort() liMoves = [] for pv in liMov: um = UnMove(self, pv, dicCache) liMoves.append(um) self.liMoves = liMoves self.liMovesInicial = liMoves[:] self.li_analysis = dicCache.get("ANALISIS", []) if dicCache else [] # self.analisisActivo # self.dicAnalisis self.ponAnalisisActivo( dicCache.get("ANALISIS_ACTIVO", None) if dicCache else None)
def player_has_moved(self, from_sq, to_sq, promotion=""): jgSel = self.check_human_move(from_sq, to_sq, promotion) if not jgSel: return False fen = self.game.last_position.fen() pv = jgSel.movimiento().lower() if self.is_opening: op_pv = self.liPVopening[self.posOpening] if pv != op_pv: if self.must_win: QTUtil2.mensajeTemporal(self.main_window, _("Wrong move"), 2) self.run_action(TB_REINIT) else: QTUtil2.message_error( self.main_window, "%s\n%s" % (_("Wrong move"), _("Right move: %s") % Game.pv_san(fen, op_pv))) self.sigueHumano() return False self.posOpening += 1 if self.posOpening == len(self.liPVopening): self.is_opening = False self.move_the_pieces(jgSel.liMovs) self.add_move(jgSel, True) self.error = "" self.play_next_move() return True
def editAnalisis(self, item, mov): # Hay un analysis -> se muestra en variantes # Analisis.show_analysis( self.procesador, self.xtutor, move, is_white, max_recursion, pos ) fen = mov.game.last_position.fen() rm = mov.analysis() if rm is None: return game = Game.Game(mov.game.last_position) game.read_pv(rm.pv) lineaPGN = game.pgnBaseRAW() wowner = self.owner board = wowner.infoMove.board import Code.Variations as Variations Variations.edit_variation_moves( self.procesador, wowner, board.is_white_bottom, fen, lineaPGN, titulo=mov.titulo + " - " + mov.etiPuntos(True), )
def show_dispatch(self, tp, rm): if rm.time or rm.depth: color_engine = "DarkBlue" if self.human_is_playing else "brown" if rm.nodes: nps = "/%d" % rm.nps if rm.nps else "" nodes = " | %d%s" % (rm.nodes, nps) else: nodes = "" seldepth = "/%d" % rm.seldepth if rm.seldepth else "" li = [ '<span style="color:%s">%s' % (color_engine, rm.name), '<b>%s</b> | <b>%d</b>%s | <b>%d"</b>%s' % (rm.abrTextoBase(), rm.depth, seldepth, rm.time // 1000, nodes), ] pv = rm.pv if tp < 999: li1 = pv.split(" ") if len(li1) > tp: pv = " ".join(li1[:tp]) p = Game.Game(self.game.last_position) p.read_pv(pv) li.append(p.pgnBaseRAW()) self.set_label3("<br>".join(li) + "</span>") QTUtil.refresh_gui()
def voyager2(self, game): ptxt = Voyager.voyagerPartida(self, game) if ptxt: game = Game.Game() game.restore(ptxt) self.addPartida(game) self.show_lines()
def new_analysis(self, pv): alm = WindowAnalysisParam.analysis_parameters(self.wowner, Code.configuration, False, siTodosMotores=False) if alm is None: return me = QTUtil2.analizando(self.wowner) conf_motor = Code.configuration.buscaRival(alm.engine) conf_motor.actMultiPV(alm.multiPV) xmotor = Code.procesador.creaManagerMotor(conf_motor, alm.vtime, alm.depth, siMultiPV=True) game = Game.Game() game.read_pv(pv) mrm, pos = xmotor.analizaJugadaPartida(game, 9999, alm.vtime, alm.depth) rotulo = mrm.name if alm.vtime: secs = alm.vtime / 1000.0 rotulo += " %.0f\"" % secs if alm.depth: rotulo += " %d^" % alm.depth mrm.rotulo = rotulo xmotor.terminar() me.final() self.db_analysis().new(pv, mrm)
def set_pos_rm_active(self, pos_rm): self.pos_rm_active = pos_rm self.rm = self.list_rm_name[self.pos_rm_active][0] self.game = Game.Game(self.move.position_before) self.game.read_pv(self.rm.pv) self.game.is_finished() self.pos_mov_active = 0
def procesa(self, orden): key = orden.key if key == KIBRUN_CONFIGURATION: user = orden.dv["USER"] self.configuration = Configuration.Configuration(user) self.configuration.lee() self.configuration.leeConfBoards() Code.configuration = self.configuration OpeningsStd.reset() self.numkibitzer = orden.dv["NUMKIBITZER"] kibitzers = Kibitzers.Kibitzers() self.kibitzer = kibitzers.kibitzer(self.numkibitzer) prioridad = self.kibitzer.prioridad priorities = Priorities.priorities if prioridad != priorities.normal: self.prioridad = priorities.value(prioridad) else: self.prioridad = None self.titulo = self.kibitzer.name self.key_video = "Kibitzers%s" % self.kibitzer.huella self.dic_video = self.configuration.restore_video(self.key_video) self.tipo = self.kibitzer.tipo self.lanzaVentana() elif key == KIBRUN_GAME: game = Game.Game() game.restore(orden.dv["GAME"]) if self.tipo == KIB_THREATS: last_position = game.last_position last_position.is_white = not last_position.is_white game_thread = Game.Game(ini_posicion=last_position) self.ventana.orden_game(game_thread) else: self.ventana.orden_game(game) elif key == KIBRUN_STOP: self.ventana.stop() elif key == KIBRUN_CLOSE: self.ipc.close() self.ventana.finalizar() self.ventana.reject()
def save_pgn(self, file, name, dic_cab, fen, move, rm, mj): """ Graba un game en un pgn @param file: pgn donde grabar @param name: name del engine que hace el analysis @param dic_cab: etiquetas de head del PGN @param fen: fen de la position @param move: move analizada @param rm: respuesta engine @param mj: respuesta engine con la mejor move, usado en caso de blunders, para incluirla """ if not file: return False p = Game.Game() if mj: # blunder p.set_position(move.position_before) p.read_pv(rm.pv) jg0 = p.move(0) jg0.comment = rm.texto() p.set_position(move.position_before) if mj: # blunder rm = mj p.read_pv(rm.pv) if p.is_finished(): result = p.resultado() mas = "" # ya lo anade en la ultima move else: mas = " *" result = "*" jg0 = p.move(0) t = "%0.2f" % (float(self.vtime) / 1000.0, ) t = t.rstrip("0") if t[-1] == ".": t = t[:-1] eti_t = "%s %s" % (t, _("Second(s)")) jg0.comment = "%s %s: %s\n" % (name, eti_t, rm.texto()) if mj: jg0.add_variation(p) cab = "" for k, v in dic_cab.items(): ku = k.upper() if not (ku in ("RESULT", "FEN")): cab += '[%s "%s"]\n' % (k, v) # Nos protegemos de que se hayan escrito en el pgn original de otra forma cab += '[FEN "%s"]\n' % fen cab += '[Result "%s"]\n' % result with open(file, "at", encoding="utf-8", errors="ignore") as q: texto = cab + "\n" + p.pgnBase() + mas + "\n\n" q.write(texto) return True
def reiniciar(self): if self.is_changed() and not QTUtil2.pregunta(self.main_window, _("You will loose all changes, are you sure?")): return p = Game.Game() p.restore(self.reinicio) p.recno = getattr(self.game, "recno", None) self.start(p, self.is_complete, self.only_consult, self.with_previous_next, self.save_routine)
def paste_pgn(self): texto = QTUtil.traePortapapeles() if texto: ok, game = Game.pgn_game(texto) if not ok: QTUtil2.message_error(self.main_window, _("The text from the clipboard does not contain a chess game in PGN format")) return self.replace_game(game)
def importarOpening(self, game): game.assign_opening() w = WindowOpenings.WOpenings(self, self.configuration, game.opening) if w.exec_(): ap = w.resultado() game = Game.Game() game.read_pv(ap.a1h8) self.addPartida(game)
def reinicio(self, dbop, modo, num_linea): self.dbop = dbop self.game_type = GT_OPENING_LINES self.modo = modo self.num_linea = num_linea self.training = self.dbop.training() self.liGames = self.training["LIGAMES_%s" % modo.upper()] self.game_info = self.liGames[num_linea] self.li_pv = self.game_info["LIPV"] self.numPV = len(self.li_pv) self.calc_totalTiempo() self.dicFENm2 = self.training["DICFENM2"] li = self.dbop.getNumLinesPV(self.li_pv) if len(li) > 10: mensLines = ",".join(["%d" % line for line in li[:10]]) + ", ..." else: mensLines = ",".join(["%d" % line for line in li]) self.liMensBasic = [] if self.modo != "sequential": self.liMensBasic.append("%d/%d" % (self.num_linea + 1, len(self.liGames))) self.liMensBasic.append( "%s: %s" % (_("Lines") if len(li) > 1 else _("Line"), mensLines)) self.siAyuda = False self.board.dbvisual_set_show_allways(False) self.game = Game.Game() self.hints = 9999 # Para que analice sin problemas self.is_human_side_white = self.training["COLOR"] == "WHITE" self.is_engine_side_white = not self.is_human_side_white self.main_window.pon_toolbar((TB_CLOSE, TB_HELP, 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()
def jugarPosicion(self): position, from_sq, to_sq = self.um.active_base_position() game = Game.Game(ini_posicion=position) dic_sended = {"ISWHITE": position.is_white, "GAME": game.save()} fichero = Code.configuration.ficheroTemporal("pk") Util.save_pickle(fichero, dic_sended) XRun.run_lucas("-play", fichero)
def __getitem__(self, num): xpv = self.li_xpv[num] if xpv in self.cache: return self.cache[xpv] game = Game.Game() pv = FasterCode.xpv_pv(xpv) game.read_pv(pv) self.add_cache(xpv, game) return game
def __init__(self, owner, numRegistro): QTVarios.WDialogo.__init__(self, owner, _("Learn a game"), Iconos.PGN(), "learn1game") self.owner = owner self.db = owner.db self.procesador = owner.procesador self.configuration = self.procesador.configuration self.numRegistro = numRegistro self.registro = self.db.leeRegistro(numRegistro) self.game = Game.Game() self.game.restore(self.registro["GAME"]) self.lbRotulo = Controles.LB(self, self.label()).ponTipoLetra( puntos=12).set_foreground_backgound("#076C9F", "#EFEFEF") self.liIntentos = self.registro.get("LIINTENTOS", []) o_columns = Columnas.ListaColumnas() o_columns.nueva("DATE", _("Date"), 100, centered=True) o_columns.nueva("LEVEL", _("Level"), 80, centered=True) o_columns.nueva("COLOR", _("Play with"), 80, centered=True) o_columns.nueva("ERRORS", _("Errors"), 80, centered=True) o_columns.nueva("HINTS", _("Hints"), 80, centered=True) o_columns.nueva("TIME", _("Time"), 80, centered=True) self.grid = Grid.Grid(self, o_columns, siSelecFilas=True, siSeleccionMultiple=True) self.grid.setMinimumWidth(self.grid.anchoColumnas() + 20) # Tool bar li_acciones = ( (_("Close"), Iconos.MainMenu(), self.terminar), None, (_("Train"), Iconos.Empezar(), self.empezar), None, (_("Remove"), Iconos.Borrar(), self.borrar), None, ) self.tb = Controles.TBrutina(self, li_acciones) # Colocamos lyTB = Colocacion.H().control(self.tb).margen(0) ly = Colocacion.V().otro(lyTB).control(self.grid).control( self.lbRotulo).margen(3) self.setLayout(ly) self.register_grid(self.grid) self.restore_video(siTam=False) self.grid.gotop()
def hechaJugada(self, move): self.board.disable_all() self.move = move self.pon_toolbar(self.seguir, self.analizar) donePV = move.movimiento().lower() dicResults = self.alm.dicResults mens = "<h2>%s</h2><br>" % self.alm.name mens += "<table><tr><th>%s</th><th>%s</th></tr>" % (_("Move"), _("Score")) mx = 0 ok = False stylePV = ' style="color:red;"' for pv, points in dicResults.items(): if donePV == pv.lower(): ok = True mas = stylePV else: mas = "" san = Game.pv_san(self.alm.fen, pv) mens += '<tr%s><td align="center">%s</td><td align="right">%d</td></tr>' % ( mas, san, points) if points > mx: mx = points if not ok: san = Game.pv_san(self.alm.fen, donePV) mens += '<tr%s><td align="center">%s</td><td align="right">%d</td></tr>' % ( stylePV, san, 0) mens += "</table>" self.alm.donePV = donePV self.alm.puntos = dicResults.get(donePV, 0) self.alm.total = mx mens += "<br><h2>%s: %d/%d</h2>" % (_("Score"), self.alm.puntos, self.alm.total) self.lbJuego.set_text(mens) self.workmap.winAim(donePV)
def cambiaInfoMove(self): row = self.grid.recno() if row >= 0 and self.noFilaTotales(row): pv = self.liMoves[row]["pv"] p = Game.Game() p.read_pv(pv) p.is_finished() p.assign_opening() self.infoMove.modoPartida(p, 9999) self.setFocus() self.grid.setFocus()
def cambiadoRM(self, pos): self.pos_rm = pos rm = self.list_rm[pos][0] self.game_tutor = Game.Game(self.last_position) self.game_tutor.read_pv(rm.getPV()) self.w.ponPuntuacionTutor(rm.texto()) self.pos_tutor = 0 self.max_tutor = len(self.game_tutor) self.moving_tutor(True)
def gui_dispatch(self, rm): if self.is_closed or self.state != ST_PLAYING: return False if not rm.sinInicializar: p = Game.Game(self.game.last_position) p.read_pv(rm.pv) rm.is_white = self.game.last_position.is_white txt = "<b>[%s]</b> (%s) %s" % (rm.name, rm.abrTexto(), p.pgn_translated()) self.lbRotulo3.set_text(txt) self.showPV(rm.pv, 1) return self.pon_reloj()
def paste(self, texto): try: if "." in texto or '"' in texto: ok, game = Game.pgn_game(texto) if not ok: return elif "/" in texto: game = Game.Game(fen=texto) else: return self.opening_block = None self.xfichero = None self.xpgn = None self.xjugadaInicial = None dic = self.creaDic() dic["GAME"] = game.save() dic["WHITEBOTTOM"] = game.last_position.is_white self.reiniciar(dic) except: pass
def get_all_games(self): li_games = [] for xpv in self.li_xpv: if xpv in self.cache: game = self.cache[xpv] else: game = Game.Game() pv = FasterCode.xpv_pv(xpv) game.read_pv(pv) li_games.append(game) return li_games
def label(self, num): r = self.leeRegistro(num) game = Game.Game() game.restore(r["GAME"]) def x(k): return game.get_tag(k) date = x("DATE").replace(".?", "").replace("?", "") return "%s-%s : %s %s %s" % (x("WHITE"), x("BLACK"), date, x("EVENT"), x("SITE"))
def start(self): self.sb_multipv.setDisabled(True) self.cb_engine.setDisabled(True) self.analyzing = True self.sb_multipv.setDisabled(True) self.show_stop() multipv = self.sb_multipv.valor() self.manager_motor.actMultiPV(multipv) game = Game.Game(self.position) self.manager_motor.ac_inicio(game) QtCore.QTimer.singleShot(1000, self.lee_analisis)
def grid_dato(self, grid, row, o_column): col = o_column.key reg = self.db.leeRegistro(row) if "CACHE" in reg: dic_tags = reg["CACHE"] else: game = Game.Game() game.restore(reg["GAME"]) reg["CACHE"] = {k: game.get_tag(k) for k in self.li_keys} self.db.cambiaRegistro(row, reg) return reg["CACHE"].get(col, "")
def lee_varias_lineas_mfn(nlineas): # WindowDailyTest lipos = random.sample(range(0, 9999), nlineas) lifen = [] with open(Code.path_resource("IntFiles", "games.mfn"), "rt", encoding="utf-8") as f: for num, linea in enumerate(f): if num in lipos: cabs, pv, move = linea.strip().split("||") p = Game.Game() p.read_pv(pv) fen = p.move(int(move)).position.fen() lifen.append(fen) return lifen
def start(self, recno, is_white): db = WindowPlayGame.DBPlayGame(self.configuration.file_play_game()) reg = db.leeRegistro(recno) gameObj = Game.Game() gameObj.restore(reg["GAME"]) nombreObj = gameObj.get_tag("WHITE" if is_white else "BLACK") label = db.label(recno) db.close() self.recno = recno self.resultado = None self.human_is_playing = False self.analysis = None self.comment = None self.siAnalizando = False self.human_side = is_white self.is_engine_side_white = not is_white self.numJugadasObj = gameObj.num_moves() self.gameObj = gameObj self.posJugadaObj = 0 self.nombreObj = nombreObj self.siSave = False self.minTiempo = 5000 self.xanalyzer.maximizaMultiPV() self.puntosMax = 0 self.puntos = 0 self.vtime = 0.0 self.book = Opening.OpeningPol(999) self.main_window.pon_toolbar( (TB_CANCEL, TB_REINIT, TB_CONFIG, TB_UTILITIES)) self.main_window.activaJuego(True, False, siAyudas=False) self.remove_hints(True, True) self.set_dispatcher(self.player_has_moved) self.set_position(self.game.last_position) self.put_pieces_bottom(self.human_side) self.show_side_indicator(True) self.set_label1(label) self.set_label2("") self.pgnRefresh(True) self.ponCapInfoPorDefecto() self.check_boards_setposition() self.state = ST_PLAYING self.play_next_move()