def __init__(self, moveOwner, fen, dbCache): self.moveOwner = moveOwner self.dbCache = dbCache if not moveOwner: self.nivel = 0 cp = ControlPosicion.ControlPosicion() cp.leeFen(fen) self.partidaBase = Partida.Partida(cp) else: self.nivel = self.moveOwner.listaMovesPadre.nivel + 1 self.partidaBase = self.moveOwner.partida.copia() self.fenM2 = self.partidaBase.ultPosicion.fenM2() dicCache = self.dbCache[self.fenM2] LCEngine.setFen(self.fenM2 + " 0 1") liMov = [xpv[1:] for xpv in LCEngine.getMoves()] 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 calculaSolucion(self): fenMB = self.cp.fen() fenOB = fenMB.replace(" w ", " b ") if "w" in fenMB else fenMB.replace( " b ", " w ") stAttacKing = set() stAttacKed = set() for fen in (fenMB, fenOB): LCEngine.setFen(fen) liMV = LCEngine.getExMoves() for mv in liMV: if mv.captura(): stAttacKing.add(mv.desde()) stAttacKed.add(mv.hasta()) liSolucion = [] for posicion, pieza in self.cp.casillas.iteritems(): if pieza: reg = Util.Almacen() reg.pieza = pieza reg.posicion = posicion lt = posicion[0] nm = int(posicion[1]) iswhite = nm % 2 == 0 if lt in "bdfh": iswhite = not iswhite reg.color = iswhite reg.atacante = posicion in stAttacKing reg.atacada = posicion in stAttacKed reg.comprobada = False liSolucion.append(reg) return liSolucion
def lipv_lipgn(lipv): LCEngine.setFenInicial() li_pgn = [] for pv in lipv: info = LCEngine.moveExPV(pv[:2], pv[2:4], pv[4:]) li_pgn.append(info._san) return li_pgn
def __init__(self, procesador): self.pantalla = procesador.pantalla self.tablero = self.pantalla.tablero self.procesador = procesador fmt = "./IntFiles/Mate/mate1.lst" with open(fmt) as f: li = [linea for linea in f.read().split("\n") if linea.strip()] linea = random.choice(li) li = linea.split("|") uno = random.choice(li) fen, mv0 = uno.split(",") fen += " w - - 1 1" LCEngine.setFen(fen) liMv = LCEngine.getExMoves() self.liMovs = [] for mv in liMv: if mv.mate(): self.liMovs.append(mv.movimiento()) self.cp = ControlPosicion.ControlPosicion() self.cp.leeFen(fen) self.iniTime = time.time() self.siBlancas = " w " in fen self.tablero.bloqueaRotacion(False) self.tablero.ponMensajero(self.mueveHumano) self.tablero.ponPosicion(self.cp) self.tablero.ponerPiezasAbajo(self.siBlancas) self.tablero.activaColor(self.siBlancas) self.tablero.ponIndicador(self.siBlancas)
def importarPGO(self, partidabase, ficheroPGO, maxDepth): self.saveHistory(_("Personal Opening Guide"), os.path.basename(ficheroPGO)) base = partidabase.pv() if partidabase else self.getconfig("BASEPV") baseXPV = LCEngine.pv2xpv(base) conexionPGO = sqlite3.connect(ficheroPGO) liRawPGO = conexionPGO.execute("SELECT XPV from GUIDE") stPGO = set() for raw in liRawPGO: xpv = raw[0] if maxDepth: lipv = LCEngine.xpv2pv(xpv).split(" ") if len(lipv) > maxDepth: lipv = lipv[:maxDepth] xpv = LCEngine.pv2xpv(" ".join(lipv)) if not xpv.startswith(baseXPV): continue ok = True lirem = [] for xpv0 in stPGO: if xpv.startswith(xpv0): lirem.append(xpv0) elif xpv0.startswith(xpv): ok = False break for xpv0 in lirem: stPGO.remove(xpv0) if ok: stPGO.add(xpv) conexionPGO.close() cursor = self._conexion.cursor() sql_insert = "INSERT INTO LINES( XPV ) VALUES( ? )" sql_update = "UPDATE LINES SET XPV=? WHERE XPV=?" for xpv in stPGO: add = True for npos, xpv_ant in enumerate(self.li_xpv): if xpv_ant.startswith(xpv): add = False break if xpv.startswith(xpv_ant): cursor.execute(sql_update, (xpv, xpv_ant)) self.li_xpv[npos] = xpv add = False break if add: cursor.execute(sql_insert, (xpv, )) self.li_xpv.append(xpv) cursor.close() self.li_xpv.sort() self._conexion.commit()
def aura(self): lista = [] def add(lipos): for pos in lipos: lista.append(LCEngine.posA1(pos)) def liBR(npos, fi, ci): fil, col = LCEngine.posFC(npos) liM = [] ft = fil + fi ct = col + ci while True: if ft < 0 or ft > 7 or ct < 0 or ct > 7: break t = LCEngine.FCpos(ft, ct) liM.append(t) pz = self.casillas[LCEngine.posA1(t)] if pz: break ft += fi ct += ci add(liM) pzs = "KQRBNP" if self.siBlancas else "kqrbnp" for i in range(8): for j in range(8): a1 = chr(i + 97) + chr(j + 49) pz = self.casillas[a1] if pz and pz in pzs: pz = pz.upper() npos = LCEngine.a1Pos(a1) if pz == "K": add(LCEngine.liK(npos)) elif pz == "Q": for f_i, c_i in ((1, 1), (1, -1), (-1, 1), (-1, -1), (1, 0), (-1, 0), (0, 1), (0, -1)): liBR(npos, f_i, c_i) elif pz == "R": for f_i, c_i in ((1, 0), (-1, 0), (0, 1), (0, -1)): liBR(npos, f_i, c_i) elif pz == "B": for f_i, c_i in ((1, 1), (1, -1), (-1, 1), (-1, -1)): liBR(npos, f_i, c_i) elif pz == "N": add(LCEngine.liN(npos)) elif pz == "P": lim, lix = LCEngine.liP(npos, self.siBlancas) add(lix) return lista
def lee_subnivel(self, fila): alm_base = self.li_moves[fila] if alm_base.nivel >= 17: return LCEngine.setFen(alm_base.fen) if LCEngine.movePV(alm_base.desde, alm_base.hasta, alm_base.coronacion): fen = LCEngine.getFen() for alm in self.book.almListaJugadas(fen): nv = alm.nivel = alm_base.nivel + 1 alm.dato = [""] * 20 alm.dato[nv] = alm.pgn alm.dato[nv+1] = alm.porc alm.dato[nv+2] = "%d" % alm.weight fila += 1 self.li_moves.insert(fila, alm)
def ayuda(self): self.hints += 1 self.tablero.quitaFlechas() self.ponSiguiente() pa = self.camino[0 if self.baseUnica else self.posActual] ps = self.camino[self.posActual + 1] tlist = LCEngine.liNMinimo(pa, ps, self.celdas_ocupadas) if self.nayuda >= len(tlist): self.nayuda = 0 li = tlist[self.nayuda] for x in range(len(li) - 1): d = LCEngine.posA1(li[x]) h = LCEngine.posA1(li[x + 1]) self.tablero.creaFlechaMov(d, h, "2") self.nayuda += 1
def haz_partida(partida, liMoves): njg = len(partida) if len(liMoves) + njg > maxDepth: liMoves = liMoves[:maxDepth - njg] pv = " ".join([move.pv for move in liMoves]) partida.leerPV(pv) pv = partida.pv() if base and not pv.startswith(base) or partida.numJugadas( ) <= njugbase: return xpv = LCEngine.pv2xpv(pv) if xpv in self.li_xpv: return line_blob = partida.save2blob() updated = False for npos, xpv_ant in enumerate(self.li_xpv): if xpv.startswith(xpv_ant): cursor.execute(sql_update, (xpv, line_blob, xpv_ant)) self.li_xpv[npos] = xpv updated = True break if not updated: cursor.execute(sql_insert, (xpv, line_blob)) self.li_xpv.append(xpv) for njug, move in enumerate(liMoves): if move.variantes: for lim in move.variantes: p = partida.copia( njug - 1) if njug > 0 else Partida.Partida() haz_partida(p, lim.liMoves)
def guardaPartidas(self, liPartidas, minMoves=0): partidabase = self.getpartidabase() sql_insert = "INSERT INTO LINES( XPV, LINE ) VALUES( ?, ? )" sql_update = "UPDATE LINES SET XPV=?, LINE=? WHERE XPV=?" cursor = self._conexion.cursor() for partida in liPartidas: if minMoves <= partida.numJugadas() > partidabase.numJugadas(): xpv = LCEngine.pv2xpv(partida.pv()) if xpv not in self.li_xpv: line_blob = partida.save2blob() updated = False for npos, xpv_ant in enumerate(self.li_xpv): if xpv.startswith(xpv_ant): cursor.execute(sql_update, (xpv, line_blob, xpv_ant)) self.li_xpv[npos] = xpv updated = True break if not updated: cursor.execute(sql_insert, (xpv, line_blob)) self.li_xpv.append(xpv) cursor.close() self._conexion.commit() self.li_xpv.sort()
def hazFEN(fen, ply, seq): plyN = ply + 1 siWhite = " w " in fen siMax = False if whiteBest: siMax = siWhite if blackBest: siMax = siMax or not siWhite liPV = book.miraListaPV(fen, siMax) for pv in liPV: cp.leeFen(fen) cp.mover(pv[:2], pv[2:4], pv[4:]) fenN = cp.fen() reg = SQLDBF.Almacen() lireg.append(reg) reg.PV = pv seqN = seq + LCEngine.pv2xpv(pv) reg.XPV = seqN reg.COMMENT = "" reg.NAG = 0 reg.FEN = fenN reg.ADV = 0 self.ultPos += 1 reg.POS = self.ultPos tmpBP2.ponTotal(1, self.ultPos - basePos) tmpBP2.pon(1, self.ultPos - basePos) if plyN < depth: fenM2 = cp.fenM2() if fenM2 not in stFenM2: stFenM2.add(fenM2) hazFEN(fenN, plyN, seqN)
def exePulsadoNumUsuario(self, siActivar, numero): if numero in [1, 8]: if siActivar: # Que jugada esta en el tablero jg = self.partidaUsuario.jugada( self.posUsuario if self.posUsuario > -1 else 0) if self.posUsuario == -1: fen = jg.posicionBase.fen() else: fen = jg.posicion.fen() siBlancas = " w " in fen if siBlancas: siMB = numero == 1 else: siMB = numero == 8 self.tableroUsuario.quitaFlechas() if self.tableroUsuario.flechaSC: self.tableroUsuario.flechaSC.hide() li = LCEngine.getCaptures(fen, siMB) for m in li: d = m.desde() h = m.hasta() self.tableroUsuario.creaFlechaMov(d, h, "c") else: self.tableroUsuario.quitaFlechas() if self.tableroUsuario.flechaSC: self.tableroUsuario.flechaSC.show()
def guardaPartidas(self, label, liPartidas, minMoves=0, with_history=True): if with_history: self.saveHistory(_("Import"), label) partidabase = self.getpartidabase() sql_insert = "INSERT INTO LINES( XPV) VALUES( ? )" sql_update = "UPDATE LINES SET XPV=? WHERE XPV=?" cursor = self._conexion.cursor() for partida in liPartidas: if minMoves <= partida.numJugadas() > partidabase.numJugadas(): xpv = LCEngine.pv2xpv(partida.pv()) if xpv not in self.li_xpv: updated = False for npos, xpv_ant in enumerate(self.li_xpv): if xpv.startswith(xpv_ant): cursor.execute(sql_update, (xpv, xpv_ant)) self.li_xpv[npos] = xpv updated = True break if not updated: cursor.execute(sql_insert, (xpv, )) self.li_xpv.append(xpv) cursor.close() self._conexion.commit() self.li_xpv.sort()
def haz_partida(liMoves): njg = len(liMoves) if njg > maxDepth: liMoves = liMoves[:maxDepth] pv = " ".join([move.pv for move in liMoves]) partida = Partida.Partida() partida.leerPV(pv) pv = partida.pv() if base and not pv.startswith(base): return xpv = LCEngine.pv2xpv(pv) updated = False for npos, xpv_ant in enumerate(self.li_xpv): if xpv_ant.startswith(xpv): return if xpv.startswith(xpv_ant): cursor.execute(sql_update, (xpv, xpv_ant)) self.li_xpv[npos] = xpv updated = True break if not updated: cursor.execute(sql_insert, (xpv, )) self.li_xpv.append(xpv) for njug, move in enumerate(liMoves): for lim in move.variantes: limovnv = [liMoves[j].clona() for j in range(njug)] for move in limovnv: move.variantes = [] limovnv.extend(lim.liMoves) haz_partida(limovnv)
def getNumLinesPV(self, pv): xpv = LCEngine.pv2xpv(" ".join(pv)) li = [ num for num, xpv0 in enumerate(self.li_xpv, 1) if xpv0.startswith(xpv) ] return li
def addMoves(moves, depth, seq): for mv in moves.liMoves: if depth > maxDepth: break seqM1 = seq pv = mv.pv seq += LCEngine.pv2xpv(pv) reg = SQLDBF.Almacen() reg.PV = pv reg.XPV = seq reg.COMMENT = "\n".join(mv.comentarios) reg.FEN = mv.fen reg.NAG = 0 reg.ADV = 0 self.ultPos += 1 reg.POS = self.ultPos for critica in mv.criticas: if critica.isdigit(): t = int(critica) if t in (4, 2, 1, 3, 5, 6): reg.NAG = t elif t in (11, 14, 15, 16, 17, 18, 19): reg.ADV = t else: if critica in dnag: reg.NAG = dnag[critica] liReg.append(reg) if mv.variantes: for variante in mv.variantes: addMoves(variante, depth, seqM1) depth += 1
def readID(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 siBlancas = dbf.WHITE self.siJugamosConBlancas = siBlancas self.siRivalConBlancas = not siBlancas pv = LCEngine.xpv2pv(dbf.MOVS) self.partidaObj = Partida.Partida() self.partidaObj.leerPV(pv) self.posJugadaObj = 0 self.numJugadasObj = self.partidaObj.numJugadas() self.cabs = collections.OrderedDict() li = dbf.CABS.split("\n") for x in li: if x: clave, valor = x.split('=') self.cabs[clave] = valor dbf.cerrar() db.cerrar()
def liBR(npos, fi, ci): fil, col = LCEngine.posFC(npos) liM = [] ft = fil + fi ct = col + ci while True: if ft < 0 or ft > 7 or ct < 0 or ct > 7: break t = LCEngine.FCpos(ft, ct) liM.append(t) pz = self.casillas[LCEngine.posA1(t)] if pz: break ft += fi ct += ci add(liM)
def posPartida(self, partida): # return siNueva, numlinea, siAppend xpv_busca = LCEngine.pv2xpv(partida.pv()) for n, xpv in enumerate(self.li_xpv): if xpv.startswith(xpv_busca): return False, n, False if xpv == xpv_busca[:-2]: return False, n, True return True, None, None
def ajustaPlayer(self, mrm): posicion = self.partida.ultPosicion LCEngine.setFen(posicion.fen()) li = LCEngine.getExMoves() liOpciones = [] for rm in mrm.liMultiPV: liOpciones.append((rm, "%s (%s)" % (posicion.pgnSP( rm.desde, rm.hasta, rm.coronacion), rm.abrTexto()))) mv = rm.movimiento() for x in range(len(li)): if li[x].movimiento() == mv: del li[x] break for mj in li: rm = XMotorRespuesta.RespuestaMotor("", posicion.siBlancas) rm.desde = mj.desde() rm.hasta = mj.hasta() rm.coronacion = mj.coronacion() rm.puntos = None liOpciones.append( (rm, posicion.pgnSP(rm.desde, rm.hasta, rm.coronacion))) if len(liOpciones) == 1: return liOpciones[0][0] menu = QTVarios.LCMenu(self.pantalla) titulo = _("White") if posicion.siBlancas else _("Black") icono = Iconos.Carpeta() self.pantalla.cursorFueraTablero() menu.opcion(None, titulo, icono) menu.separador() icono = Iconos.PuntoNaranja( ) if posicion.siBlancas else Iconos.PuntoNegro() for rm, txt in liOpciones: menu.opcion(rm, txt, icono) while True: resp = menu.lanza() if resp: return resp
def mueveHumano(self, desde, hasta, coronacion=""): p0 = LCEngine.a1Pos(desde) p1 = LCEngine.a1Pos(hasta) if p1 in LCEngine.dicN[p0]: self.moves += 1 self.movesParcial += 1 self.ponNumMoves() if p1 not in self.camino: return False self.cpActivo.casillas[desde] = None self.cpActivo.casillas[hasta] = "N" if self.siBlancas else "n" self.tablero.ponPosicion(self.cpActivo) self.tablero.activaColor(self.siBlancas) self.posTemporal = p1 if p1 == self.camino[self.posActual + 1]: self.avanza() return True return True return False
def __getitem__(self, num): xpv = self.li_xpv[num] if xpv in self.cache: return self.cache[xpv] partida = Partida.Partida() pv = LCEngine.xpv2pv(xpv) partida.leerPV(pv) self.add_cache(xpv, partida) return partida
def append(self, partida): xpv = LCEngine.pv2xpv(partida.pv()) sql = "INSERT INTO LINES( XPV ) VALUES( ? )" cursor = self._conexion.cursor() cursor.execute(sql, (xpv, )) cursor.close() self._conexion.commit() self.li_xpv.append(xpv) self.li_xpv.sort() self.add_cache(xpv, partida)
def importarOtra(self, pathFichero, partida): xpvbase = LCEngine.pv2xpv(partida.pv()) tambase = len(xpvbase) otra = Opening(pathFichero) liPartidas = [] for n, xpv in enumerate(otra.li_xpv): if xpv.startswith(xpvbase) and tambase < len(xpv): liPartidas.append(otra[n]) otra.close() self.guardaPartidas(liPartidas)
def checkFen(self, fen): LCEngine.setFen(fen) liMoves = LCEngine.getMoves() dic = {} for xpv in liMoves: pv = xpv[1:] LCEngine.setFen(fen) LCEngine.movePV(pv[:2], pv[2:4], pv[4:]) xfen = LCEngine.getFen() wdl, dtz = self.wdl_dtz(xfen) if wdl is not None and dtz is not None: dic[pv] = -wdl, -dtz return dic
def importarOtra(self, pathFichero, partida): xpvbase = LCEngine.pv2xpv(partida.pv()) tambase = len(xpvbase) otra = Opening(pathFichero) lista = [] for n, xpv in enumerate(otra.li_xpv): if xpv.startswith(xpvbase) and len(xpv) > tambase: if xpv not in self.li_xpv: lista.append(xpv) otra.close() self.guardaLiXPV("%s,%s" % (_("Other opening lines"), otra.title), lista)
def getAllFen(self): stFENm2 = set() lilipv = [LCEngine.xpv2pv(xpv).split(" ") for xpv in self.li_xpv] for lipv in lilipv: LCEngine.setFenInicial() for pv in lipv: fen = LCEngine.getFen() fenM2 = LCEngine.fen2fenM2(fen) stFENm2.add(fenM2) LCEngine.makeMove(pv) return stFENm2
def ponSiguiente(self): posDesde = self.camino[0 if self.baseUnica else self.posActual] posHasta = self.camino[self.posActual + 1] tlist = LCEngine.liNMinimo(posDesde, posHasta, self.celdas_ocupadas) self.numMoves = len(tlist[0]) - 1 self.movesParcial = 0 cp = self.cpInicial.copia() self.posTemporal = posDesde ca = LCEngine.posA1(posDesde) cp.casillas[ca] = "N" if self.siBlancas else "n" cs = LCEngine.posA1(posHasta) cp.casillas[cs] = "k" if self.siBlancas else "K" self.cpActivo = cp self.tablero.ponPosicion(cp) self.tablero.activaColor(self.siBlancas) self.ponNumMoves()
def mover(self, desdeA1H8, hastaA1H8, coronacion=""): self.setLCE() mv = LCEngine.moveExPV(desdeA1H8, hastaA1H8, coronacion) if not mv: return False, "Error" self.liExtras = [] enrK = mv.isCastleK() enrQ = mv.isCastleQ() enPa = mv.isEnPassant() if coronacion: if self.siBlancas: coronacion = coronacion.upper() else: coronacion = coronacion.lower() self.liExtras.append(("c", hastaA1H8, coronacion)) elif enrK: if self.siBlancas: self.liExtras.append(("m", "h1", "f1")) else: self.liExtras.append(("m", "h8", "f8")) elif enrQ: if self.siBlancas: self.liExtras.append(("m", "a1", "d1")) else: self.liExtras.append(("m", "a8", "d8")) elif enPa: capt = self.alPaso.replace("6", "5").replace("3", "4") self.liExtras.append(("b", capt)) self.leeFen(LCEngine.getFen()) # despues de liExtras, por si enpassant return True, self.liExtras
def totree(self): parent = ItemTree(None, None, None, None) dic = AperturasStd.ap.dicFenM2 for xpv in self.li_xpv: lipv = LCEngine.xpv2pv(xpv).split(" ") lipgn = LCEngine.xpv2pgn(xpv).replace("\n", " ").strip().split(" ") linom = [] LCEngine.setFenInicial() for pv in lipv: LCEngine.makeMove(pv) fen = LCEngine.getFen() fenM2 = LCEngine.fen2fenM2(fen) linom.append(dic[fenM2].trNombre if fenM2 in dic else "") parent.addLista(lipv, lipgn, linom) return parent