def leePGNRecno(self, recno, sp): raw = self.leeAllRecno(recno) litags = [] result = "*" for field in self.li_fields: if not (field in ("XPV", "_DATA_", "PLYCOUNT")): v = raw[field] if v: litags.append((drots.get(field, field), v if type(v) == str else str(v))) if field == "RESULT": result = v if type(v) == str else str(v) litags.append(("PlyCount", str(raw["PLYCOUNT"]))) xpgn = raw["_DATA_"] if xpgn: if xpgn.startswith(BODY_SAVE): ok, p = Game.pgn_game(xpgn[len(BODY_SAVE):].strip()) else: p = Game.Game() p.restore(xpgn) p.set_tags(litags) return p.pgn(), p.resultado() pgn = xpv_pgn(raw["XPV"]) if sp == "\r\n": pgn = pgn.replace("\n", "\r\n") tags = [] for t, v in litags: tags.append('[%s "%s"]' % (t, v)) pgn = sp.join(tags) + sp + sp + pgn return pgn, result
def read(self, line): li = line.split("|") self.position.read_fen(li[0]) nli = len(li) if nli > 1: self.label = li[1] if nli > 2: solucion = li[2] ok, game_obj = Game.pgn_game('[FEN "%s"]\n%s' % (self.position.fen(), solucion)) if ok: self.game_obj = game_obj if nli > 3: txt = li[3].replace("]", "]\n").replace(" [", "[") ok, game_original = Game.pgn_game(txt) if ok: ok = False for n in range(len(game_original) - 1, -1, -1): move = game_original.move(n) if move.position == self.position: ok = True if n + 1 != len(game_original): game_original.li_moves = game_original.li_moves[: n + 1] break if ok: self.game_original = game_original self.game_original.set_unknown()
def grid_dato(self, grid, fila, oColumna): rm = self.liData[fila] key = oColumna.clave if key == "EVALUATION": return rm.abrTexto() elif key == "BESTMOVE": p = Game.Game(fen=self.fen) p.read_pv(rm.pv) pgn = p.pgnBaseRAW() if self.siFigurines else p.pgn_translated() li = pgn.split(" ") resp = "" if li: if ".." in li[0]: if len(li) > 1: resp = li[1] else: resp = li[0].lstrip("1234567890.") if self.siFigurines: is_white = " w " in self.fen return resp, is_white, None, None, None, None, False, True else: return resp elif key == "DEPTH": return "%d" % rm.depth else: p = Game.Game(fen=self.fen) p.read_pv(rm.pv) li = p.pgn_translated().split(" ") if ".." in li[0]: li = li[1:] return " ".join(li[1:])
def leePartidaRaw(self, raw): p = Game.Game() xpgn = raw["_DATA_"] ok = False if xpgn: if xpgn.startswith(BODY_SAVE): ok, p = Game.pgn_game(xpgn[len(BODY_SAVE):].strip()) else: try: p.restore(xpgn) ok = True except: ok = False if not ok: fen, pv = self.read_xpv(raw["XPV"]) if fen: p.set_fen(fen) p.read_pv(pv) litags = [] for field in self.li_fields: if not (field in ("XPV", "_DATA_", "PLYCOUNT")): v = raw[field] if v: litags.append((drots.get(field, field), v if type(v) == str else str(v))) litags.append(("PlyCount", str(raw["PLYCOUNT"]))) p.set_tags(litags) p.assign_opening() return p
def graba_tactic(self, game, njg, mrm, pos_act): if not self.tacticblunders: return # Esta creado el folder before = "AvoidBlunders.fns" after = "ExploitBlunders.fns" if not os.path.isdir(self.tacticblunders): dtactics = os.path.join(self.configuracion.dirPersonalTraining, "Tactics") if not os.path.isdir(dtactics): os.mkdir(dtactics) os.mkdir(self.tacticblunders) with open(os.path.join(self.tacticblunders, "Config.ini"), "wt") as f: f.write("""[COMMON] ed_reference=20 REPEAT=0 SHOWTEXT=1 [TACTIC1] MENU=%s FILESW=%s:100 [TACTIC2] MENU=%s FILESW=%s:100 """ % (_("Avoid the blunder"), before, _("Take advantage of blunder"), after)) cab = "" for k, v in game.dicTags().items(): ku = k.upper() if not (ku in ("RESULT", "FEN")): cab += '[%s "%s"]' % (k, v) move = game.move(njg) fen = move.position_before.fen() p = Game.Game(fen=fen) rm = mrm.li_rm[0] p.read_pv(rm.pv) f = open(os.path.join(self.tacticblunders, before), "at") f.write("%s||%s|%s%s\n" % (fen, p.pgnBaseRAW(), cab, game.pgnBaseRAWcopy(None, njg - 1))) f.close() fen = move.position.fen() p = Game.Game(fen=fen) rm = mrm.li_rm[pos_act] li = rm.pv.split(" ") p.read_pv(" ".join(li[1:])) f = open(os.path.join(self.tacticblunders, after), "at") f.write("%s||%s|%s%s\n" % (fen, p.pgnBaseRAW(), cab, game.pgnBaseRAWcopy(None, njg))) f.close() self.siTacticBlunders = True self.procesador.entrenamientos.menu = None
def voyager2(self, game): ptxt = Voyager.voyagerPartida(self, game) if ptxt: game = Game.Game() game.restore(ptxt) self.addPartida(game) self.show_lines()
def mueve_humano(self, from_sq, to_sq, promotion=None): jgSel = self.checkmueve_humano(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.siguiente_jugada() return True
def ponPV(self, pvMirar): if not pvMirar: self.actualizaPV(None) else: self.analisisMRM = None dicAnalisis = {} self.fenm2 = None p = Game.Game() if pvMirar: p.read_pv(pvMirar) self.fenm2 = p.last_position.fenm2() self.analisisMRM = None # TODO analisis # self.dbAnalisis.mrm(self.fenm2) # if self.analisisMRM: # for rm in self.analisisMRM.li_rm: # dicAnalisis[rm.movimiento()] = rm li = pvMirar.split(" ") self.pvBase = " ".join(li[:-1]) busca = li[-1] self.liMoves = self.dbGames.get_summary(pvMirar, dicAnalisis, self.si_figurines_pgn) for fila, move in enumerate(self.liMoves): if move.get("pvmove") == busca: self.grid.goto(fila, 0) break self.cambiaInfoMove()
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 save_pgn(self, fichero, name, dic_cab, fen, move, rm, mj): """ Graba una game en un pgn @param fichero: pgn donde grabar @param name: name del engine que hace el analisis @param dic_cab: etiquetas de cabecera 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 fichero: 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(fichero, "at", encoding="utf-8", errors="ignore") as q: texto = (cab + "\n" + p.pgnBase() + mas + "\n\n").replace( "\n", "\r\n") q.write(texto) return True
def hazPV(lipv_ant): if bp.is_canceled(): return n_ant = len(lipv_ant) siWhite1 = n_ant % 2 == 0 pv_ant = " ".join(lipv_ant) if n_ant else "" liChildren = db_stat.children(pv_ant, False) if len(liChildren) == 0 or len(lipv_ant) > depth: p = Game.Game() p.leerLIPV(lipv_ant) if len(p) > len_partidabase: liPartidas.append(p) bp.ponTotal(len(liPartidas)) bp.pon(len(liPartidas)) return if siWhite1 == siWhite: tt_max = 0 limax = [] for alm in liChildren: tt = alm.W + alm.B + alm.O + alm.D if tt > tt_max: tt_max = tt limax = [alm] elif tt == tt_max and not onlyone: limax.append(alm) liChildren = limax for alm in liChildren: li = lipv_ant[:] li.append(alm.move) hazPV(li)
def setPosicion(self, game, njg, numTab=None): if game is None: return move = game.move(njg) self.game = game self.njg = njg next = self.cb_nextmove.valor() if move: if njg == 0: pv = game.pv_hasta(njg) if next else "" else: pv = game.pv_hasta(njg if next else njg - 1) position = move.position if next else move.position_before else: position = Position.Position().set_pos_initial() pv = "" for ntab, (tipo, tab) in enumerate(self.li_tabs): if ntab == 0: p = Game.Game() p.read_pv(pv) tab.setData(p.pgn_html(siFigurines=self.configuracion.x_pgn_withfigurines), position) else: data = pv if tipo == "dbase" else position if numTab is not None: if ntab != numTab: continue if ntab > 1: tab.setData(data) tab.start()
def show_analisis(self, mrm): self.current_mrm = mrm self.current_posicion = self.position li = [] for rm in mrm.li_rm: game = Game.Game(self.position) game.read_pv(rm.pv) pgn = game.pgnBaseRAW() lit = pgn.split(" ") is_white = self.position.is_white if is_white: pgn0 = lit[0].split(".")[-1] pgn1 = " ".join(lit[1:]) else: pgn0 = lit[1] pgn1 = " ".join(lit[2:]) if self.siFigurines: game.ms_sol = pgn0, is_white, None, None, None, None, False, False else: game.ms_sol = pgn0 game.ms_pgn = pgn1 game.ms_pdt = rm.abrTextoPDT() li.append(game) self.li_analysis = li self.grid_analysis.refresh()
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.ponRotulo3("<br>".join(li) + "</span>") QTUtil.refresh_gui()
def editaAnalisis(self, item, mov): # Hay un analisis -> 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 tablero = wowner.infoMove.tablero import Code.Variantes as Variantes Variantes.editaVarianteMoves( self.procesador, wowner, tablero.is_white_bottom, fen, lineaPGN, titulo=mov.titulo + " - " + mov.etiPuntos(True), )
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.partidaBase = Game.Game(cp) else: self.nivel = self.moveOwner.listaMovesPadre.nivel + 1 self.partidaBase = self.moveOwner.game.copia() self.fenm2 = self.partidaBase.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.liAnalisis = dicCache.get("ANALISIS", []) if dicCache else [] # self.analisisActivo # self.dicAnalisis self.ponAnalisisActivo( dicCache.get("ANALISIS_ACTIVO", None) if dicCache else None)
def __init__(self, a1h8): p = Game.Game() p.read_pv(a1h8) self.dicFEN = {} for move in p.li_moves: self.dicFEN[move.position_before.fen()] = move self.activa = True
def read_id(self, xid): db = Base.DBBase(self._db) dbf = db.dbfT("data", "LEVEL,WHITE,CABS,MOVS", condicion="ROWID=%d" % xid) dbf.leer() dbf.gotop() self.nivel = dbf.LEVEL is_white = dbf.WHITE self.is_human_side_white = is_white self.is_engine_side_white = not is_white pv = FasterCode.xpv_pv(dbf.MOVS) self.partidaObj = Game.Game() self.partidaObj.read_pv(pv) self.posJugadaObj = 0 self.numJugadasObj = self.partidaObj.num_moves() li = dbf.CABS.split("\n") for x in li: if x: key, valor = x.split("=") self.game.add_tag(key, valor) dbf.cerrar() db.cerrar()
def grid_cambiado_registro(self, grid, fila, oCol): if self.grid_num_datos(grid) > fila >= 0: self.setFocus() self.grid.setFocus() fen, pv = self.dbGames.damePV(fila) if fen: p = Game.Game(fen=fen) p.read_pv(pv) p.is_finished() self.infoMove.modoFEN(p, fen, -1) else: p = Game.Game() p.read_pv(pv) p.assign_opening() p.is_finished() self.infoMove.modoPartida(p, 0)
def partidaActual(self): game = Game.Game() numcol = self.glines.posActualN()[1] game.leeOtra(self.game if self.game and numcol > 0 else self.partidabase) if self.num_jg_actual is not None and self.num_jg_inicial <= self.num_jg_actual < len(game): game.li_moves = game.li_moves[: self.num_jg_actual + 1] return game
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 set_key(self, key): self.key = self.db.test_tipo(key) dic = self.configuracion.leeVariables("endingsGTB") order = dic.get("ORDER", "difficulty") dic["KEY"] = self.key self.configuracion.escVariables("endingsGTB", dic) num_positions = self.db.read_key(self.key, order) self.grid.refresh() pos = 0 for c in key: lbl = self.wpzs.li_labels[pos] lbl.ponImagen(self.pzs.pixmap(c, 48)) lbl.show() pos += 1 while pos < 6: self.wpzs.li_labels[pos].hide() pos += 1 self.bt_movs.hide() self.replaying = False self.grid.setFocus() if num_positions: self.act_recno = 0 self.fen = self.db.get_current_fen(0) self.game.set_fen(self.fen) else: self.act_recno = -1 self.game = Game.Game() self.tablero.setposition(self.game.first_position)
def actualizaPV(self, pvBase): self.pvBase = pvBase if not pvBase: pvMirar = "" else: pvMirar = self.pvBase self.analisisMRM = None dicAnalisis = {} self.fenm2 = None if pvMirar: p = Game.Game() if pvMirar: p.read_pv(pvMirar) self.fenm2 = p.last_position.fenm2() # TODO añadir el análisis # self.analisisMRM = self.dbAnalisis.mrm(self.fenm2) # if self.analisisMRM: # for rm in self.analisisMRM.li_rm: # dicAnalisis[rm.movimiento()] = rm self.liMoves = self.dbGames.get_summary(pvMirar, dicAnalisis, self.si_figurines_pgn, self.allmoves) self.grid.refresh() self.grid.gotop()
def grid_cambiado_registro(self, grid, fila, columna): self.game = Game.Game(self.position) self.game.read_pv(self.list_rm[fila].rm.pv) self.maxMoves = len(self.game) self.mueve(siInicio=True) self.grid.setFocus()
def hazFEN(fen, lipv_ant, control): if bp.is_canceled(): return siWhite1 = " w " in fen book = bookW if siWhite1 else bookB liPV = book.miraListaPV(fen, siWhite1 == siWhite, onlyone=onlyone) if liPV and len(lipv_ant) < depth: for pv in liPV: set_fen(fen) make_move(pv) fenN = get_fen() lipv_nue = lipv_ant[:] lipv_nue.append(pv) hazFEN(fenN, lipv_nue, control) else: p = Game.Game() p.leerLIPV(lipv_ant) control.liPartidas.append(p) control.num_partidas += 1 bp.ponTotal(control.num_partidas) bp.pon(control.num_partidas) if control.num_partidas and control.num_partidas % 1000 == 0: self.guardaPartidas(control.rotulo, control.liPartidas, minMoves, with_history=control.with_history) control.liPartidas = [] control.with_history = False
def reiniciar(self): if self.changed and not QTUtil2.pregunta( self.main_window, _("You will loose all changes, are you sure?")): return p = Game.Game() p.restore(self.reinicio) self.inicio(p, self.siCompleta)
def importarApertura(self, game): game.assign_opening() w = PantallaOpenings.WAperturas(self, self.configuracion, game.opening) if w.exec_(): ap = w.resultado() game = Game.Game() game.read_pv(ap.a1h8) self.addPartida(game)
def pgn_lcsb(estado, pgn, jugada_inicial=None): ok, game = Game.pgn_game(pgn) if jugada_inicial: move = game.move(jugada_inicial) si_blancas_abajo = move.position_before.is_white else: si_blancas_abajo = True return dict(ESTADO=estado, GAME=game.save(), WHITEBOTTOM=si_blancas_abajo)
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.liPV = self.game_info["LIPV"] self.numPV = len(self.liPV) self.calc_totalTiempo() self.dicFENm2 = self.training["DICFENM2"] li = self.dbop.getNumLinesPV(self.liPV) 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"), mensLines)) self.siAyuda = False self.tablero.dbVisual_setShowAllways(False) self.game = Game.Game() self.ayudas = 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.mueve_humano) self.setposition(self.game.last_position) self.mostrarIndicador(True) self.quitaAyudas() self.ponPiezasAbajo(self.is_human_side_white) self.pgnRefresh(True) self.ponCapInfoPorDefecto() self.state = ST_PLAYING self.dgt_setposition() self.errores = 0 self.ini_time = time.time() self.muestraInformacion() self.siguiente_jugada()
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