def new_casilla(self, request): """ Generates a new casilla in the platform. """ logging.debug("[FrontEnd] - Casilla - national id = {0}".format( request.national_id)) logging.debug("[FrontEnd] - Distrito - national id = {0}".format( request.distrito)) logging.debug("[FrontEnd] - casilla name = {0}".format(request.name)) logging.debug("[FrontEnd] - loc = {0}".format(request.loc)) logging.debug("[FrontEnd] - address = {0}".format(request.address)) logging.debug("[FrontEnd] - picture_url = {0}".format( request.picture_url)) resp = messages.CreateCasillaResponse() try: Casilla.create(loc=request.loc, name=request.name, address=request.address, picture_url=request.picture_url, national_id=request.national_id, distrito=request.distrito) except CasillaCreationError as e: resp.error = e.value else: resp.ok = True return resp
def levantar_auto(matr): for i in range(len(matr)): for j in range(len(matr[0])): if Casilla.get_lev(matr[i][j]) == True: if Casilla.get_val(matr[i][j]) == 0: if numero(i, j).analizar_minas(matr) == 0: for x in range(max(i - 1, 0), min(i + 2, len(matr))): for y in range(max(j - 1, 0), min(j + 2, len(matr))): Casilla.set_lev(matr[x][y], True) return matr
def actualizar_y_dibujar_tablero(lista, x, y): print((int(y) + 1) * "-+-") print(" |", end="") for i in range(int(y)): if i >= 10: print(f"{i}|", end="") else: print(f" {i}|", end="") print("\n" + (int(y) + 1) * "-+-") for i in range(int(x)): if i >= 10: print(f"{i}|", end="") else: print(f" {i}|", end="") for j in range(int(y)): if Casilla.get_lev(lista[i][j]) == True: if Casilla.get_val(lista[i][j]) == 0: colorrojo = '\033[31m' colorazul = '\033[34m' coloramarillo = '\033[33m' colorverde = '\033[32m' acabarcolor = '\033[m' cant_de_minas = numero(i, j).analizar_minas(lista) if cant_de_minas == 0: print(" |", end="") elif cant_de_minas < 2: print( f" {colorazul + str(cant_de_minas) + acabarcolor}|", end="") elif cant_de_minas < 3: print( f" {colorverde + str(cant_de_minas) + acabarcolor}|", end="") elif cant_de_minas < 5: print( f" {coloramarillo + str(cant_de_minas) + acabarcolor}|", end="") elif cant_de_minas < 9: print( f" {colorrojo + str(cant_de_minas) + acabarcolor}|", end="") else: print(" X|", end="") else: if Casilla.get_banderilla(lista[i][j]) == '!': print(" !|", end="") elif Casilla.get_banderilla(lista[i][j]) == '?': print(" ?|", end="") else: print(" x|", end='') print()
def __init__(self, turno = 1): self.tablero_ = [[Casilla(X,Y) for Y in range(0, self.N)] for X in range(0, self.N)] self.confInicial() self.NroFichas = 4 #inicializar las 4 fichas self.turno_ = 1
def save_to_datastore(cls, observador, casilla, clasificacion, filled_checklist): """ Saves a Observacion as a new entity on the datastore. :param observador: (String) email :param casilla: (String) national id :param clasificacion: URL safe key of the Observador selected clasificacion :param filled_checklist: JSON of checklist filled by the Observador :return key: If creation successful URL safe key of the new observacion, exception otherwise """ try: c = Casilla.get_from_datastore(casilla) o = Observador.get_from_datastore(observador) new = Observacion(casilla=c.key, observador=o.key, clasificacion=ndb.Key(urlsafe=clasificacion), filled_checklist=filled_checklist) key = new.put() except Exception as e: logging.exception("[Observacion] - "+e.message) raise ObservacionCreationError('Error creating the observacion in datastore: '+e.__str__()) else: logging.debug('[Observacion] - New Observacion, Key = {0}'.format(key)) return key.urlsafe()
def assign_casilla(self, request): """ Assigns a casilla to a observador """ logging.debug("[FrontEnd] - assign - Casilla: {0}".format( request.casilla)) logging.debug("[FrontEnd] - assign - Observador: {0}".format( request.observador)) resp = messages.AssignCasillaToObservadorResponse() try: r = Casilla.assign_to_observador(email=request.observador, national_id=request.casilla) r_c = messages.Casilla() if r: logging.debug( "[FrontEnd] - assign - Observador assignment successful") else: logging.debug( "[FrontEnd] - assign - Observador assignment failed!!!") except Exception as e: resp.error = e.__str__() else: resp.ok = True return resp
def get_casilla(self, request): """ Gets the details of a given casilla national_id. """ logging.debug("[FrontEnd] - get_casilla_details - Casilla: {0}".format( request.casilla)) resp = messages.GetCasillaDetailResponse() try: r = Casilla.get_from_datastore(request.casilla) r_c = messages.Casilla() if r.observador: r_c.observador = r.observador.urlsafe() else: r_c.observador = 'Observador no Asignado' r_c.distrito = r.distrito.urlsafe() r_c.national_id = r.national_id r_c.loc = str(r.loc) r_c.name = r.name r_c.address = r.address r_c.picture_url = r.picture_url resp.casilla = r_c except GetClasificacionError as e: resp.error = e.value else: resp.ok = True return resp
def save_to_datastore(cls, observador, casilla, clasificacion, filled_checklist): """ Saves a Observacion as a new entity on the datastore. :param observador: (String) email :param casilla: (String) national id :param clasificacion: URL safe key of the Observador selected clasificacion :param filled_checklist: JSON of checklist filled by the Observador :return key: If creation successful URL safe key of the new observacion, exception otherwise """ try: c = Casilla.get_from_datastore(casilla) o = Observador.get_from_datastore(observador) new = Observacion(casilla=c.key, observador=o.key, clasificacion=ndb.Key(urlsafe=clasificacion), filled_checklist=filled_checklist) key = new.put() except Exception as e: logging.exception("[Observacion] - " + e.message) raise ObservacionCreationError( 'Error creating the observacion in datastore: ' + e.__str__()) else: logging.debug( '[Observacion] - New Observacion, Key = {0}'.format(key)) return key.urlsafe()
def get_all(cls, casilla): """ Gets all the observaciones for a given casilla :param casilla: :return: list of all observaciones """ try: observaciones = [] c = Casilla.get_from_datastore(casilla) query_response = Observacion.query( Observacion.casilla == c.key).fetch() if query_response: for r in query_response: observaciones.append(r) else: raise GetObservacionError( 'No Observaciones found under specified criteria: Casilla: {0}' .format(casilla)) except Exception as e: logging.exception("[Observacion] - " + e.message) raise GetObservacionError('Error getting Observaciones: ' + e.__str__()) else: for r in observaciones: logging.debug("[Observacion] = {0}".format(r)) return observaciones
def get_casilla(self, request): """ Gets the details of a given casilla national_id. """ logging.debug("[FrontEnd] - get_casilla_details - Casilla: {0}".format(request.casilla)) resp = messages.GetCasillaDetailResponse() try: r = Casilla.get_from_datastore(request.casilla) r_c = messages.Casilla() if r.observador: r_c.observador = r.observador.urlsafe() else: r_c.observador = 'Observador no Asignado' r_c.distrito = r.distrito.urlsafe() r_c.national_id = r.national_id r_c.loc = str(r.loc) r_c.name = r.name r_c.address = r.address r_c.picture_url = r.picture_url resp.casilla = r_c except GetClasificacionError as e: resp.error = e.value else: resp.ok = True return resp
def contar_levantadas(matr): cant_levantables = 0 levantados = 0 for i in range(len(matr)): for j in range(len(matr[0])): if Casilla.get_val(matr[i][j]) == 0: cant_levantables += 1 for i in range(len(matr)): for j in range(len(matr[0])): if Casilla.get_val(matr[i][j]) == 0 and Casilla.get_lev( matr[i][j]) == True: levantados += 1 if cant_levantables == levantados: return True else: return False
def crearTableroPorMapa(self, mapa): # Se obtinen las dimensiones dimension_x = len(mapa) - 1 dimension_y = len(mapa[0]) - 1 self.dimensiones = (dimension_x, dimension_y) # Se recorre la matriz de simbolos para crear la matriz de Casillas for fila in mapa: nueva_fila = [] for elem in fila: # para crear nuestra matriz de Casillas aprovechamos para marcar su tipo (muro, tuberia, mario) casilla_aux = Casilla() casilla_aux.asignarTipo(elem) # Agregamos la casilla a la fila nueva_fila.append(casilla_aux) #Agregamos la fila a la matriz self.casillas.append(nueva_fila) self.definirPosicionesDeMurosYMario()
def crearTableroPorParametros(self, dimension_x, dimension_y, pos_muros, pos_tuberias, pos_mario): # definimos propiedades utiles de la clase disminuyendo en uno, debido a la adaptacion de indices que inician en 0 self.pos_tuberias = map(lambda posicion: (posicion[0]-1, posicion[1]-1) ,pos_tuberias) self.pos_mario = (pos_mario[0]-1, pos_mario[1]-1) self.dimensiones = (dimension_x-1, dimension_y-1) # Las casillas se van a formar con las dimensiones proporcionadas # Teniendo una lista de listas de la clase Casilla self.casillas = [[Casilla() for y in range(dimension_y)] for x in range(dimension_x)] self.ponerMurosTuberiasYMario(pos_muros, pos_tuberias, pos_mario)
def crear_tab(self): matr = [] matraux = [] for i in range(self.i): for j in range(self.j): if len(matraux) < self.j: matraux.append(Casilla(i, j)) matr.append(matraux) matraux = [] return matr
def table(matr, x, y): lista = [] listaux = [] for i in range(int(x)): for j in range(int(y)): if len(listaux) < int(y): listaux.append(Casilla(i, j).get_val()) lista.append(listaux) listaux = [] return lista
def get_casillas_assigned_to_observador(self, request): """ Gets all the Casillas assigned to a given Observador. """ logging.debug("[FrontEnd] - Get Casillas Assigned to Observador - Observador = {0}".format(request.email)) resp = messages.GetCasillasAssignedToObservadorResponse() try: resp.casillas = Casilla.get_based_on_observador(email=request.email) except GetCasillaError as e: resp.error = e.value else: resp.ok = True return resp
def crearTableroPorMapa(): # Extraemos la simbologia de los tipos de casillas simbologia = Casilla().simbologia print(f' La simbologia de los elementos es la siguiente: {" ".join([f" {simbolo} para {nombre}," for nombre, simbolo in simbologia.items()])}') print("Ingrese fila por fila separados por un espacio los elementos del tablero. Para terminar ingrese un punto despues de la ultima linea") tablero_ingreso = [] # Ingresamos en una lista las lineas del tablero como listas creando una matriz de simbolos for linea in stdin: if linea == ".\n": break tablero_ingreso.append([num for num in linea.split()]) # Se crea el tablero tablero.crearTableroPorMapa(tablero_ingreso)
def crea_tablero(self, tamx, tamy): x = 2 y = 2 matriz = [] for i in range(tamy): linea = [] for j in range(tamx): casilla = Casilla(x, y) casilla.x = j casilla.y = i if i == 0 or j == 0 or i == tamy - 1 or j == tamx - 1: casilla.estado = "P" linea.append(casilla) x += 10 matriz.append(linea) x = 2 y += 10 return matriz
def initialize(self): self.parent.title("Buscaminas") self.parent.grid_rowconfigure(1, weight=1) self.parent.grid_columnconfigure(1, weight=1) self.frame = tk.Frame(self.parent) self.frame.pack(fill=tk.X, padx=5, pady=5) casillas = [] botones = [] x = int(raw_input("X:")) self.dim_x = x y = int(raw_input("Y:")) self.dim_y = y minas = int(raw_input("Minas: ")) contador_minas = 0 for i in range(y): casillas.append([]) botones.append([]) for j in range(x): rnd = randint(0, 100) casilla_tmp = Casilla(rnd, callback=self.game_over) if rnd <= 50 and contador_minas < minas: casilla_tmp.mina = True contador_minas = contador_minas + 1 casillas[i].append(casilla_tmp) button = tk.Button( self.frame, text="C") #, command=casillas[i][j].click_izq) button.bind('<Button-1>', casillas[i][j].click_izq) button.bind('<Button-3>', casillas[i][j].click_der) casillas[i][j].button = button casillas[i][j].button.bind button.grid(row=j, column=i) botones[i].append(button) self.botones = botones self.casillas = casillas self.set_numeros()
def new_casilla(self, request): """ Generates a new casilla in the platform. """ logging.debug("[FrontEnd] - Casilla - national id = {0}".format(request.national_id)) logging.debug("[FrontEnd] - Distrito - national id = {0}".format(request.distrito)) logging.debug("[FrontEnd] - casilla name = {0}".format(request.name)) logging.debug("[FrontEnd] - loc = {0}".format(request.loc)) logging.debug("[FrontEnd] - address = {0}".format(request.address)) logging.debug("[FrontEnd] - picture_url = {0}".format(request.picture_url)) resp = messages.CreateCasillaResponse() try: Casilla.create(loc=request.loc, name=request.name, address=request.address, picture_url=request.picture_url, national_id=request.national_id, distrito=request.distrito) except CasillaCreationError as e: resp.error = e.value else: resp.ok = True return resp
def get_casillas_assigned_to_observador(self, request): """ Gets all the Casillas assigned to a given Observador. """ logging.debug( "[FrontEnd] - Get Casillas Assigned to Observador - Observador = {0}" .format(request.email)) resp = messages.GetCasillasAssignedToObservadorResponse() try: resp.casillas = Casilla.get_based_on_observador( email=request.email) except GetCasillaError as e: resp.error = e.value else: resp.ok = True return resp
def generar_tuplas(self): ''' Generamos las tuplas (coordenadas) y sus respectivos objetos casilla''' tuplas=[] casillas=[] self.prueba=3 i=0 j=0 while i<self.filas: t=(i,0) while j<self.columnas: t=(i,j) casilla=Casilla(t,0) tuplas.append(t) casillas.append(casilla) j+=1 i+=1 j=0 return tuplas,casillas
def assign_casilla(self, request): """ Assigns a casilla to a observador """ logging.debug("[FrontEnd] - assign - Casilla: {0}".format(request.casilla)) logging.debug("[FrontEnd] - assign - Observador: {0}".format(request.observador)) resp = messages.AssignCasillaToObservadorResponse() try: r = Casilla.assign_to_observador(email=request.observador, national_id=request.casilla) r_c = messages.Casilla() if r: logging.debug("[FrontEnd] - assign - Observador assignment successful") else: logging.debug("[FrontEnd] - assign - Observador assignment failed!!!") except Exception as e: resp.error = e.__str__() else: resp.ok = True return resp
def new_location(self, request): """ Generates a new location in the platform. """ logging.debug("[FrontEnd] - Observacion - Observador = {0}".format(request.observador)) logging.debug("[FrontEnd] - Observacion - Loc = {0}".format(request.loc)) resp = messages.CreateLocationResponse() try: Location.create(observador=request.observador, loc=request.loc) except LocationCreationError as e: resp.error = e.value else: try: # Find a near casilla c = Casilla.get_based_on_location(request.loc, 10) except GetCasillaError as e: resp.error = e.value else: resp.casilla_near = c.key.urlsafe() resp.ok = True return resp
def new_location(self, request): """ Generates a new location in the platform. """ logging.debug("[FrontEnd] - Observacion - Observador = {0}".format( request.observador)) logging.debug("[FrontEnd] - Observacion - Loc = {0}".format( request.loc)) resp = messages.CreateLocationResponse() try: Location.create(observador=request.observador, loc=request.loc) except LocationCreationError as e: resp.error = e.value else: try: # Find a near casilla c = Casilla.get_based_on_location(request.loc, 10) except GetCasillaError as e: resp.error = e.value else: resp.casilla_near = c.key.urlsafe() resp.ok = True return resp
def get_all(cls, casilla): """ Gets all the observaciones for a given casilla :param casilla: :return: list of all observaciones """ try: observaciones = [] c = Casilla.get_from_datastore(casilla) query_response = Observacion.query(Observacion.casilla == c.key).fetch() if query_response: for r in query_response: observaciones.append(r) else: raise GetObservacionError('No Observaciones found under specified criteria: Casilla: {0}' .format(casilla)) except Exception as e: logging.exception("[Observacion] - "+e.message) raise GetObservacionError('Error getting Observaciones: '+e.__str__()) else: for r in observaciones: logging.debug("[Observacion] = {0}".format(r)) return observaciones
def __init__(self, tupla, valor, vecinos=[]): Casilla.__init__(self, tupla, valor) self.vecinos = vecinos
def read_json(self,fichero_json): try: with open(fichero_json) as f: datos=f.read() datos=json.loads(datos) except: print("No se ha podido leer el fichero json") else: self.filas=datos["rows"] self.columnas=datos["cols"] self.max_nmax_n=datos["max_n"] self.mov=datos["mov"] self.id_mov=datos["id_mov"] self.cells=datos["cells"] self.casillas=[] for entity in self.cells: valor1=entity.split(',')[0].split('(')[1] valor2=entity.split(',')[1].split(')')[0] tupla=(int(valor1),int(valor2)) v=self.cells[entity]["value"] neighbors=self.cells[entity]["neighbors"] casilla=Casilla(tupla,v) casilla.set_N(neighbors[0]) casilla.set_E(neighbors[1]) casilla.set_S(neighbors[2]) casilla.set_O(neighbors[3]) casilla.set_valor(v) self.casillas.append(casilla)
matr = table(matr, x, y) matr = crear_minas_numeros(matr, x, y) has_ganado = False antes = int(round(time.time(), 0)) print("0h 0' 00\"") actualizar_y_dibujar_tablero(matr, x, y) try: while True: jugada = input( "Tu jugada(fila,columna,opción[!,?,q(uitar),j(ugar)]), o escribe 'salir': " ) if jugada == 'salir': break else: (jx, jy, jz) = jugada.split(",") if Casilla.get_lev(matr[int(jx)][int(jy)]) == False: if jz == 'j': if Casilla.get_val(matr[int(jx)][int(jy)]) == 1: break else: Casilla.set_lev(matr[int(jx)][int(jy)], True) elif jz == '!': Casilla.set_banderilla(matr[int(jx)][int(jy)], '!') elif jz == '?': Casilla.set_banderilla(matr[int(jx)][int(jy)], '?') elif jz == 'q': Casilla.set_banderilla(matr[int(jx)][int(jy)], '') else: print("Ya levantado... -.-") matr = levantar_auto(matr) has_ganado = contar_levantadas(matr)