def verificar_assert( nombre_test, codigo_insertar_recibido, codigo_insertar_esperado, es_declaracion, ): """ A partir de las posibilidades dadas por el generador crea dos instancias de tablero (o partida), donde en una almacena el tablero que se espera recibir y en la otra el tablero donde la pc ya realizo su movimiento. Ambas varibles 'codigo...' llevan el codigo que se tiene que ejecutar para insertar en ambos tableros (recibido/esperado) los movimientos a testearse. """ for ( posicion_posible, posicion_esperada, tablero_jugado, ) in generador_posibilidades(): tablero_nuevo = Tablero() tablero_recibido = tablero_nuevo.get_tablero() tablero_esperado = tablero_jugado.get_tablero() if es_declaracion: exec(codigo_insertar_recibido) exec(codigo_insertar_esperado) else: eval(codigo_insertar_recibido) eval(codigo_insertar_esperado) self.__pc_insertar_movimiento(tablero_nuevo, pc) assert (tablero_recibido == tablero_esperado).all( ), "pc.insertar_posicion() ({} condicionada) no inserta la posicion esperada".format( nombre_test) print("SUCCEEDED pc.insertar_posicion() ({} condicionada)". format(nombre_test))
def coordenar(ancho, coordenadas): pass t = Tablero(ancho, ancho) for c in coordenadas: x, y = Tools.calccoord(ancho, c) t.tablero[x][y] = 1 return t
def __init__(self, columnas, filas, n_leones, n_antilopes, debug=False): super(Mundo, self).__init__() self.debug = debug self.etapa = 0 self.tablero = Tablero(filas, columnas) self.llenar_mundo(n_leones, n_antilopes)
def test_insertar_barco_fuera_del_tablero_falla_y_no_modifica_el_barco( self): titanic = Barco(100) oceano = Tablero(10, 10) with self.assertRaises(JuegoException): oceano.insert_item_in_position(titanic, 15, 2) self.assertEqual(titanic.get_column(), None, "Posicion X no es nula") self.assertEqual(titanic.get_row(), None, "Posicion Y no es nula")
def test_insertar_barco_dentro_del_tablero_cuadrado_queda_bien_posicionado( self): titanic = Barco(100) oceano = Tablero(10, 10) oceano.insert_item_in_position(titanic, 0, 0) self.assertEqual(oceano.get_item_from_position(0, 0), titanic, "En la posicion 0,0 no se ve el barco") self.assertEqual(titanic.get_column(), 0, "Posicion X no es 0") self.assertEqual(titanic.get_row(), 0, "Posicion Y no es 0")
def __init__(self): self.tablero = Tablero() # Composición #self.jugador = Jugador() # Asociación self.opciones = { "1" : self.iniciarpartida, "2" : self.elegirtablero, "3" : self.salir_app, #"4" : self.inicializarjugadores }
def __init__(self, figure): """Inicializador de clase Ajedrez. Parameters ---------- figure : QPyQt5Canvas Figura para desplegar tablero y piezas.""" self.figure = figure self.piezas = self.generar_piezas() self.tablero = Tablero(self.piezas, self.figure)
def __init__(self): self.Tablero = Tablero() self.turnoactual = "W" self.Check = Check(self) self.Enroque = Enroque(self) self.texto = {"W": "Las blancas!", "B": "Las negras!"} self.victoria = False self.turno = False self.enroque = None self.oficial = None
class TestTablero(unittest.TestCase): """ Clase que agrupa los tests unitarios de la clase Tablero. """ def setUp(self): self._tablero = Tablero(8, 8) def test_posiciones_vecinas_esquina(self): expected = ["A2", "B1"] actual = self._tablero.posiciones_vecinas("A1") self.assertEqual(expected, actual) def test_posiciones_vecinas_borde(self): expected = ["A1", "A3", "B2"] actual = self._tablero.posiciones_vecinas("A2") self.assertEqual(expected, actual) def test_posiciones_vecinas_medio_B2(self): expected = ["A2", "B1", "B3", "C2"] actual = self._tablero.posiciones_vecinas("B2") self.assertEqual(expected, actual) def test_posiciones_vecinas_medio_F4(self): expected = ["E4", "F3", "F5", "G4"] actual = self._tablero.posiciones_vecinas("F4") self.assertEqual(expected, actual) def test_posiciones_vecinas_parametro_mal_formado_eleva_ArgumentError(self): expected = ValueError callable = self._tablero.posiciones_vecinas parameter = "666" self.assertRaises(expected, callable, parameter) def test_posiciones_vecinas_columna_fuera_de_rango_superior_eleva_IndexError(self): expected = IndexError callable = self._tablero.posiciones_vecinas parameter = "B9" self.assertRaises(expected, callable, parameter) def test_posiciones_vecinas_columna_fuera_de_rango_inferior_eleva_IndexError(self): expected = IndexError callable = self._tablero.posiciones_vecinas parameter = "B0" self.assertRaises(expected, callable, parameter) def test_posiciones_vecinas_fila_fuera_de_rango_superior_eleva_IndexError(self): expected = IndexError callable = self._tablero.posiciones_vecinas parameter = "I1" self.assertRaises(expected, callable, parameter) def test_posiciones_vecinas_fila_fuera_de_rango_inferior_eleva_IndexError(self): expected = IndexError callable = self._tablero.posiciones_vecinas parameter = ".1" self.assertRaises(expected, callable, parameter)
class TestTablero: def setup_method(self, method): self.tablero = Tablero(15) def test_obtener_vehiculo(self): v = self.tablero.obtener_vehiculo('Lancha') # vehiculo no None assert v is not None def test_obtener_vehiculo_letra(self): v = self.tablero.obtener_vehiculo_letra('C') # vehiculo no None assert v is not None
def test_crear_juego_poner_barco_y_hacerlo_avanzar_actualiza_la_posicion_del_barco_y_tablero( self): titanic = Barco(100) oceano = Tablero(10, 10) juego = Juego(oceano, [titanic], 1) xInicial = titanic.get_column() yInicial = titanic.get_row() titanic.advance_to_new_position() self.assertEqual(titanic.get_column(), xInicial + 1, "La posicion del barco en x no se modifico") self.assertEqual(titanic.get_row(), yInicial, "La posicion del barco en y se modifico") self.assertEqual(oceano.get_item_from_position(xInicial, yInicial), None, "El barco sigue en su posicion original") self.assertEqual(oceano.get_item_from_position(xInicial + 1, yInicial), titanic, "El barco no avanzo en el tablero")
def __init__(self): self.tablero = Tablero(80, 80) self.screen = pygame.display.set_mode((len(self.tablero.matrix[0]) * 10, len(self.tablero.matrix) * 10 + 32), pygame.DOUBLEBUF) pygame.display.set_caption("Pathfinder") self.clock = pygame.time.Clock() self.pausa = True self.velocidad = 100 self.velocidad_algoritmo = 8 # a star self.pathfinder = PathFinder(self.tablero) # cursor self.cursor = Cursor(self.tablero, self.pathfinder) #fuente pygame.font.init() self.fuente = pygame.font.SysFont("default", 24) self.texto = self.fuente.render("Pausado", True, (255, 0, 255)) self.texto_algo = self.fuente.render("Velocidad: " + str(self.velocidad_algoritmo), True, (255, 0, 255))
def menu_principal(): while True: while True: print\ "Elija tipo de tablero u otras opciones\n",\ "\t1. Fácil\n",\ "\t2. Intermedio\n",\ "\t3. Difícil\n",\ "\t4. Tablero fijo\n",\ "\t5. Mejores puntuaciones (no implementado)\n",\ "\t6. Borrar mejores puntuaciones (no implementado)\n",\ "\t0. Salir\n" try: opcion = int(raw_input()) if opcion <= 6 and opcion >= 0: break else: raise except: print "Error: Seleccione una opcion válida" tablero = Tablero() if opcion == 1: tablero_facil(tablero) tablero.tipo_partida = 1 break elif opcion == 2: tablero_intermedio(tablero) tablero.tipo_partida = 2 break elif opcion == 3: tablero_dificil(tablero) tablero.tipo_partida = 3 break elif opcion == 4: menu_secundario(tablero) if tablero is not None: break elif opcion == 5: mejores_puntuaciones() elif opcion == 6: borrar_mejores_puntuaciones() elif opcion == 0: exit() return tablero
class Tateti: def __init__(self, jug1, jug2): self.jug1 = jug1 self.jug2 = jug2 self.tablero = Tablero() def jugarTateti(self): # Aleatorio quien empieza if R.randint(0, 1) == 0: jugAct = self.jug1 else: jugAct = self.jug2 ganar = False print(str(self.tablero)) # Se juega mientras no haya ganador y haya un lugar libre while not ganar and self.tablero.existe(NADA): print("JUEGA: " + str(jugAct)) coor = jugAct.jugar(self.tablero) # Pone la ficha en el tablero self.tablero.poner(coor.fila, coor.columna, jugAct.ficha) print(str(self.tablero)) #Se fija si hubo TATETI if self.esTateti(jugAct.ficha): ganar = True #En caso que no cambia de jugador else: jugAct = self.elOtroJugador(jugAct) #Si hubo ganador lo muestra por pantalla y lo devulve if ganar: print("Ganador: " + str(jugAct)) return jugAct #En caso de empate lo muestra y devuelve False else: print("EMPATE") return False def elOtroJugador(self, unJugador): # Dependiendo cual sea el jugador actual devuelve el contrario if unJugador == self.jug2: return self.jug1 return self.jug2 def esTateti(self, ficha): # Recorre las filas y se fija si en alguna hay TATETI for fila in range(self.tablero.cf): if self.tablero.filaIgual(fila, ficha): return True # Recorre las columnas y se fija si en alguna hay TATETI for columna in range(self.tablero.cc): if self.tablero.columnaIgual(columna, ficha): return True # Se fija si hay TATETI en la diagonal principal if self.tablero.digonalIgual(ficha): return True # Se fija si hay TATETI en la diagonal secundaria if self.tablero.digonalSecIgual(ficha): return True return False
def test_mortero_ataca_a_barco_y_le_saca_vida(self): titanic = Barco(100) mortero = Mortero([[40, 40, 40, 40, 40], [40, 40, 40, 40, 40], [40, 40, 40, 40, 40], [40, 40, 40, 40, 40], [40, 40, 40, 40, 40]]) oceano = Tablero(5, 5) juego = Juego(oceano, [titanic], [mortero]) mortero.attack(titanic) self.assertEqual(titanic.get_life_points(), 60, "El barco no perdio vida")
def __init__(self): """Constructor de la clase. Inicializa la interfaz grafica y los objetos que va a utilizar durante el juego.""" self.mazo = Mazo(paises.paises_por_tarjeta) self.dados = Dados() self.tablero = Tablero(paises.paises_por_continente, paises.paises_limitrofes) Interfaz.iniciar(paises.coordenadas_de_paises, paises.archivo_tablero, paises.color_tablero) self.jugadores = []
def comenzar_partida(self): """ Comenzar partida declara los jugadores, quien comienza el turno, y da comienzo a la partida. En caso de hallar un ganador se termina la partida. Caso contratio la partida finaliza cuando no hallan mas movimientos posibles. """ ganador = None seleccion = int(self.mostrar_menu()) jugadores = { 1: self.definir_jugadores_PVP, 2: self.definir_jugadores_PVC, 3: self.definir_jugadores_CVC, }[seleccion]() turnos = self.primer_turno(jugadores) partida = Tablero() movimientos = range(4) for _ in movimientos: for jugador in turnos: try: partida.insertar_posicion( jugador.get_simbolo(), jugador.insertar_posicion(partida)) except KeyboardInterrupt: input( self.COLOR_COLORADO + "\nPerdiste por abandono!\nPresiona enter para salir..." + self.COLOR_END) sys.exit() ganador = partida.verificar_tablero() if ganador is not None: print(self.victoria(ganador)) break else: continue break else: print(self.COLOR_COLORADO + "\nNo hay mas movimientos posibles! :c" + self.COLOR_END) return
def crea_tablero(self, i, titulo): newWindow = tk.Toplevel(self.ventana) newWindow.geometry("650x420") newWindow.title(titulo) moves = self.list_game[i].moves next_move = tk.Button(newWindow, text="Adelante", command=lambda: self.move(True)) next_move.pack() next_move.place(x=180, y=360) back_move = tk.Button(newWindow, text="Atras", command=lambda: self.move(False)) back_move.pack() back_move.place(x=50, y=360) list = tk.Listbox(newWindow, width=18, height=20) jugada = "" j = 0 result = self.list_game[i].header['result'] i = 1 leng = len(moves) for j in range(0, leng, 2): if (j <= leng): jugada += str(i) + ". " + moves[j] if (j + 1 < leng): jugada += " " + moves[j + 1] list.insert(tk.END, jugada) jugada = "" i += 1 self.tablero = Tablero(newWindow, moves) self.tablero.pack() self.tablero.place(x=10, y=10) list.pack() list.place(x=460, y=10)
def test_crear_juego_ubica_los_barcos_en_el_tablero(self): titanic = Barco(100) santamaria = Barco(50) oceano = Tablero(10, 10) juego = Juego(oceano, [titanic, santamaria], 1) self.assertNotEqual(titanic.get_column(), None, "Posicion X no fue seteada") self.assertNotEqual(titanic.get_row(), None, "Posicion Y no fue seteada") self.assertEqual( oceano.get_item_from_position(titanic.get_column(), titanic.get_row()), titanic, "El barco no se ubico en el tablero") self.assertNotEqual(santamaria.get_column(), None, "Posicion X no fue seteada") self.assertNotEqual(santamaria.get_row(), None, "Posicion Y no fue seteada") self.assertEqual( oceano.get_item_from_position(santamaria.get_column(), santamaria.get_row()), santamaria, "El barco no se ubico en el tablero")
def test_insertar_barco_dentro_del_borde_del_tablero_rectangular_queda_bien_posicionado( self): titanic = Barco(100) oceano = Tablero(10, 20) oceano.insert_item_in_position(titanic, 9, 2) self.assertEqual(oceano.get_item_from_position(9, 2), titanic, "En la posicion 9,2 no se ve el barco") self.assertEqual(titanic.get_column(), 9, "Posicion X no es 9") self.assertEqual(titanic.get_row(), 2, "Posicion Y no es 2") oceano.insert_item_in_position(titanic, 5, 19) self.assertEqual(oceano.get_item_from_position(5, 19), titanic, "En la posicion 5,19 no se ve el barco") self.assertEqual(titanic.get_column(), 5, "Posicion X no es 5") self.assertEqual(titanic.get_row(), 19, "Posicion Y no es 19")
def test_barco_avanza_hasta_el_final_y_da_la_vuelta(self): titanic = Barco(100) oceano = Tablero(3, 3) juego = Juego(oceano, [titanic], 1) xInicial = titanic.get_column() yInicial = titanic.get_row() titanic.advance_to_new_position() self.assertEqual(titanic.get_column(), xInicial + 1, "La posicion del barco en x no se modifico") self.assertEqual(oceano.get_item_from_position(xInicial + 1, yInicial), titanic, "El barco no avanzo en el tablero") titanic.advance_to_new_position() self.assertEqual(titanic.get_column(), xInicial + 2, "La posicion del barco en x no se modifico") self.assertEqual(oceano.get_item_from_position(xInicial + 2, yInicial), titanic, "El barco no avanzo en el tablero") titanic.advance_to_new_position() self.assertEqual(titanic.get_column(), xInicial, "El barco no dio la vuelta") self.assertEqual(titanic.get_row(), yInicial, "La posicion del barco en y se modifico") self.assertEqual(oceano.get_item_from_position(xInicial, yInicial), titanic, "El barco no dio la vuelta en el tablero") self.assertEqual(oceano.get_item_from_position(xInicial + 2, yInicial), None, "El barco no se fue del final del tablero")
def __init__(self, interfaz, jugadores): """Inicializa una partida para un jugador""" self.interfaz = interfaz nombre_jugador = self.interfaz.registrar_jugador() ficha_jugador = self.interfaz.seleccionar_ficha(self.fichas) jugador = Jugador(nombre_jugador, ficha_jugador) if self.fichas.index(jugador.ficha) == 0: ficha_oponente = self.fichas[1] else: ficha_oponente = self.fichas[0] if jugadores < 2: jugador2 = Computadora(ficha_oponente) else: nombre_jugador = self.interfaz.registrar_jugador() jugador2 = Jugador(nombre_jugador, ficha_oponente) self.tablero = Tablero() #inicializa un ciclo entre computadora y jugador. self.jugadores = (jugador, jugador2) self.turnos = cycle(self.jugadores)
def main(): file_name = sys.argv[1] algoritmo = int(sys.argv[2]) newtablero = Tablero() amplitud = Amplitud(newtablero) profundidad = Profundidad(newtablero) iterativa = ProfundidadI(newtablero) newtablero.cargarTablero(file_name) if algoritmo == 1: amplitud.buscar(newtablero) elif algoritmo == 2: profundidad.buscar(newtablero) elif algoritmo == 3: iterativa.buscar(newtablero) else: print("No se definio algoritmo")
class Ajedrez: #Ajedrez """Despliega el menu de inicio para el usuario en la terminal, y espera entrada de teclado""" def __init__(self): self.tablero = Tablero() # Composición #self.jugador = Jugador() # Asociación self.opciones = { "1" : self.iniciarpartida, "2" : self.elegirtablero, "3" : self.salir_app, #"4" : self.inicializarjugadores } def desplegar1(self): print(""" Inicia una partida de AJEDREZ Selecciona la opcion deseada: 1. Iniciar nuevo juego. 2. Seleccionar color del tablero. 3. Salir del juego. """)# 4. Ingresa el nombre de los jugadores.) #self.tablero.generartab() def run(self): """Desplegar el menu y esperar la seleccion del usuario""" while(True): self.desplegar1() opcion = input("""\nIntroduce la opcion deseada: """) accion = self.opciones.get(opcion) if accion: accion() else: try: raise InvalidOption() except InvalidOption: print("Opcion Inválida") #No funciona bien la excepción para salir si se agrega try y except se necesita reiniciar el kernel para volver a comenzar, no sale del menú, además no marca el error solo impime lo que hay en el except, no se puede quitar el while o no permanece el menú, se se queda así sale el error pero tambien sale del menú def elegirtablero(self): """Elegir el tablero""" self.tablero.elegirtab() #self.tablero.iniciar() def iniciarpartida(self): """Inicia un nuevo Juego""" self.tablero.generartab() self.tablero.dibujarpiezas() #self.tablero.seleccionar() def salir_app(self): print("""Gracias por jugar Ajedrez, regresa pronto dude!""") sys.exit()
class Partida(): """Controlador de partida para un jugador""" fichas = ["X", "O"] tipos_partida = {"jugador_vs_computadora" : 0, "jugador_vs_jugador": 1} def __init__(self, interfaz, jugadores): """Inicializa una partida para un jugador""" self.interfaz = interfaz nombre_jugador = self.interfaz.registrar_jugador() ficha_jugador = self.interfaz.seleccionar_ficha(self.fichas) jugador = Jugador(nombre_jugador, ficha_jugador) if self.fichas.index(jugador.ficha) == 0: ficha_oponente = self.fichas[1] else: ficha_oponente = self.fichas[0] if jugadores < 2: jugador2 = Computadora(ficha_oponente) else: nombre_jugador = self.interfaz.registrar_jugador() jugador2 = Jugador(nombre_jugador, ficha_oponente) self.tablero = Tablero() #inicializa un ciclo entre computadora y jugador. self.jugadores = (jugador, jugador2) self.turnos = cycle(self.jugadores) def iniciar_partida(self): """inicializa la partida""" partida_terminada = False jugador = self.alternar_turno() while not partida_terminada: if isinstance(jugador, Jugador): casilla = self.interfaz.pedir_jugada() jugada = Jugada(casilla, jugador.ficha) self.tablero.marcar_casilla(jugada) partida_terminada = self.tablero.buscar_ganador(jugada) elif isinstance(jugador, Computadora): casilla = jugador.jugar(self.tablero) jugada = Jugada(casilla, jugador.ficha) self.tablero.marcar_casilla(jugada) partida_terminada = self.tablero.buscar_ganador(jugada) self.interfaz.mostrar_tablero(self.tablero) jugador = self.alternar_turno() self.interfaz.mostrar_tablero(self.tablero) print("partida terminada! ganador {0}".format(jugador.ficha)) def alternar_turno(self): """intercala los turnos entre los jugadores""" return next(self.turnos)
def generador_posibilidades(): """ Genera todas las posibilidades que se pueden dar en una partida """ # Como el movimiento condicionado se da a partir de dos simbolos iguales en la misma linea # unicamente lo hice con un simbolo. tablero_esperado = Tablero() movimientos_posibles = np.array([["X", "X", "-"], ["X", "-", "X"], ["-", "X", "X"]]) movimientos_esperados = np.array([["X", "X", "O"], ["X", "O", "X"], ["O", "X", "X"]]) for indice in range(3): yield ( movimientos_posibles[indice], movimientos_esperados[indice], tablero_esperado, )
def test_insertar_posicion_aleatoria(self): """ Testea cuando la pc inserta sin amenazas (x x -) o posibles victorias (o o -). """ # Para este test voy a necesitar instanciar un tablero nuevo, es decir sin # ningun simbolo. pc = Pc("O") tablero_vacio = Tablero() self.__pc_insertar_movimiento(tablero_vacio, pc) tablero_recibido = tablero_vacio.get_tablero() posiciones_tablero = np.array([["O", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]) tablero_jugado = Tablero() tablero_jugado.set_tablero(posiciones_tablero) tablero_esperado = tablero_jugado.get_tablero() assert (tablero_recibido == tablero_esperado).all( ), "pc.insertar_posicion() no inserta la posicion esperada" print("SUCCEEDED pc.insertar_posicion()")
def test_barco_avanza_y_el_mortero_lo_va_atacando_hasta_destruirlo(self): titanic = Barco(100) mortero = Mortero([[40, 40, 40, 40, 40], [30, 30, 30, 30, 30], [20, 20, 20, 20, 20], [15, 15, 15, 15, 15], [40, 40, 40, 40, 40]]) oceano = Tablero(5, 5) juego = Juego(oceano, [titanic], [mortero]) mortero.attack(titanic) self.assertEqual(titanic.get_life_points(), 60, "El barco no perdio vida") titanic.advance_to_new_position() mortero.attack(titanic) self.assertEqual(titanic.get_life_points(), 30, "El barco no perdio vida") titanic.advance_to_new_position() mortero.attack(titanic) self.assertEqual(titanic.get_life_points(), 10, "El barco no perdio vida") titanic.advance_to_new_position() mortero.attack(titanic) self.assertTrue(titanic.is_dead(), "El barco no murio")
def main(): t1 = Tablero() t1.poner(0,0,CRUZ) t1.poner(1,0,CRUZ) print(t1) jug1 = ComputadoraDificil("Compu",CRUZ) c1=jug1.atacar(t1) print(c1) print('---------') print('---------') t2 = Tablero() print(t2) print("---------------------") t2.poner(0,0,CRUZ) t2.poner(0,2,CRUZ) print(t2) jug2 = ComputadoraDificil("Compu",CRUZ) c2=jug2.atacar(t2) print(c2) print('---------') print('---------') t3 = Tablero() print(t3) print("---------------------") t3.poner(0,0,CRUZ) print(t3) jug3 = ComputadoraDificil("Compu",CRUZ) c3=jug3.atacar(t3) print(c3) print('++++++++++++++++++++')
def Cargar_Mapa(map_str): tablero_nuevo = Tablero() map_lineas = map_str.split('\n') tablero_nuevo.num_lineas = int(len(map_lineas[0].strip())) for y, linea in enumerate(map_lineas[0:]): linea = linea.replace('\n', '') if linea: for x, char in enumerate(linea): pos = (x, y) if char in PARED: tablero_nuevo.add_pared(pos) if char in OBJETIVO: tablero_nuevo.add_objetivo(pos) if char in CAJA: tablero_nuevo.add_caja(pos) if char in JUGADOR: tablero_nuevo.add_jugador(pos) return tablero_nuevo
u.send(f"{BLUE}{nick}>{DEFAULT} {line}".encode("UTF-8")) else: u.send(f"{RED}{nick}>{DEFAULT} {line}".encode("UTF-8")) u.send(tablero.dibujarMesa(tablero.M, abs(p-1)).encode("UTF-8")) s.send(tablero.dibujarMesa(tablero.M, p).encode("UTF-8")) if tablero.comprobarPartida() == False: if tablero.jugador == 0: u.send(("EL GANADOR ES EL JUGADOR ROJO\n").encode("UTF-8")) s.send(("EL GANADOR ES EL JUGADOR ROJO\n").encode("UTF-8")) else: u.send(("EL GANADOR ES EL JUGADOR AZUL\n").encode("UTF-8")) s.send(("EL GANADOR ES EL JUGADOR AZUL\n").encode("UTF-8")) else: s.send("Comanda erronea\n".encode("UTF-8")) s.close() with lock: del users[p] lock = threading.Lock() users = {} #users = {azul:{nick1:socket1} # rojo:{nick2:socket2}} tablero = Tablero() serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serv.bind(('', int(sys.argv[1]))) serv.listen(2) #Si es passa un argument numéric és el màxim de clients abans de "tombar" nous while len(users) < 1: s, _ = serv.accept() threading.Thread(target=client, args = (s,)).start()
################################################## # Sistemas Inteligentes - Práctica 1 # # Bartomeu Ramis Tarragó y David Cantero Tirado # ################################################## from tablero import Tablero from button import Button from graphics import GraphWin, color_rgb, Rectangle, Point, Text from tkRepeatingTask import TkRepeatingTask, BackgroundTask import threading import time import graphics numFilas = 9 numColumnas = 15 tablero = Tablero(numColumnas, numFilas) paused = True walls = False roombas = False roboThread = None butStart = Button(5, 5, 100, 40, "Start/Stop", True) butWalls = Button(110, 5, 100, 40, "Walls", True) butRobot = Button(215, 5, 100, 40, "Robot", True) butClear = Button(320, 5, 100, 40, "Clear", False) def func_start(pressed): global paused if (pressed): if (tablero.hasRobot()):
def main(): key = '' load_succesful = False while (key != '3'): key = menu_main() if (key == '2'): g = menu_load() load_succesful = True elif (key == '3'): sys.exit() if ((key == '1') or (load_succesful is True)): if (load_succesful is False): modo = menu_game_modes() if (modo == '1'): """Modo Normal""" tab_size = int(input('\n' + 'Tamaño del tablero: ')) t = Tablero(tab_size, tab_size) random_place = input('\n' + 'Usar patron al azar? (s/n): ') if (random_place == 's'): cell_alive = int( input('\n' + 'Cantidad ' 'de celdas vivas? ')) t.fill(cell_alive) else: t.manual_fill() g = Game(int(modo), t) elif (modo == '2'): """Modo Vidas Estaticas""" tab_size = int(input('\n' + 'Tamaño del tablero: ')) cell_alive = int(input('\n' + 'Cantidad de celdas vivas? ')) t = Tablero(tab_size, tab_size) g = Game(int(modo), t, cell_alive) if (modo != '3'): g.running = True while (g.running): try: g.run() except KeyboardInterrupt: key = menu_pause() if (key == '1'): continue elif (key == '2'): menu_save(g) elif (key == '3'): g = menu_load() elif (key == '4'): g.tablero.manual_fill() elif (key == '5'): g.running = False
class TEG(object): """Implementa la logica de una partida de TEG.""" def __init__(self): """Constructor de la clase. Inicializa la interfaz grafica y los objetos que va a utilizar durante el juego.""" self.mazo = Mazo(paises.paises_por_tarjeta) self.dados = Dados() self.tablero = Tablero(paises.paises_por_continente, paises.paises_limitrofes) Interfaz.iniciar(paises.coordenadas_de_paises, paises.archivo_tablero, paises.color_tablero) self.jugadores = [] # Eventualmente aca haya falta agregar mas cosas... def configurar_el_juego(self): """Pone a los jugadores en el juego.""" Interfaz.setear_titulo('Configurando el juego') n = Interfaz.elegir('Jugadores', 'Seleccione el numero de jugadores', range(2,7)) nombre_colores = NOMBRE_COLORES.values() for i in range(n): nombre = Interfaz.elegir('Jugador %d' % (i + 1), 'Ingrese el nombre del jugador %d' % (i + 1)) color = Interfaz.elegir('Jugador %d' % (i + 1), 'Ingrese el color del jugador %d' % (i + 1), nombre_colores) nombre_colores.remove(color) c = NOMBRE_COLORES.keys()[NOMBRE_COLORES.values().index(color)] self.jugadores.append(Jugador(c, nombre)) def repartir_paises(self): """Reparte en ronda las tarjetas de paises y pone un ejercito en cada uno de los paises.""" Interfaz.setear_titulo('Repartiendo paises iniciales') ntarjetas = self.mazo.cantidad_tarjetas() njugadores = len(self.jugadores) for jugador in \ self.jugadores * (ntarjetas / njugadores) + \ random.sample(self.jugadores, ntarjetas % njugadores): t = self.mazo.sacar_tarjeta() self.tablero.ocupar_pais(t.pais, jugador.color, 1) self.mazo.devolver_tarjeta(t) def agregar_ejercitos_inicial(self, inicia_ronda): """Realiza la primer fase de colocacion de ejercitos.""" Interfaz.setear_titulo('Incorporando ejercitos') ejercitos_primera = int(math.ceil(self.tablero.cantidad_paises() / 10.0)) ejercitos_segunda = int(math.ceil(self.tablero.cantidad_paises() / 20.0)) for cantidad in (ejercitos_primera, ejercitos_segunda): for i in range(len(self.jugadores)): jugador = self.jugadores[(inicia_ronda + i) % len(self.jugadores)] Interfaz.alertar(jugador, '%s pone ejercitos' % jugador) # cantidad de ejercitos #en cualquier continente ejercitos = jugador.agregar_ejercitos(self.tablero, {"": cantidad}) assert(sum(ejercitos.values()) == cantidad) for pais in ejercitos: assert(self.tablero.color_pais(pais) == jugador.color) self.tablero.asignar_ejercitos(pais, ejercitos[pais]) self.tablero.actualizar_interfaz() def realizar_fase_ataque(self, jugador): """Implementa la fase de ataque de un jugador. Sucesivamente hace combatir a los paises seleccionados. Devuelve el numero de paises conquistados.""" Interfaz.setear_titulo('%s ataca' % jugador) Interfaz.alertar(jugador, '%s ataca' % jugador) paises_ganados = 0 while True: ataque = jugador.atacar(self.tablero) if not ataque: break atacante, atacado = ataque assert(self.tablero.es_limitrofe(atacante, atacado)) assert(self.tablero.ejercitos_pais(atacante) > 1) self.dados.lanzar_dados(self.tablero.ejercitos_pais(atacante), self.tablero.ejercitos_pais(atacado)) self.tablero.asignar_ejercitos(atacante, -self.dados.ejercitos_perdidos_atacante()) self.tablero.asignar_ejercitos(atacado, -self.dados.ejercitos_perdidos_atacado()) Interfaz.setear_titulo('%s: -%d, %s: -%d %s' % (atacante, self.dados.ejercitos_perdidos_atacante(), atacado, self.dados.ejercitos_perdidos_atacado(), self.dados)) if self.tablero.ejercitos_pais(atacado) == 0: paises_ganados += 1 mover = Interfaz.elegir(jugador, 'Cuantos ejercitos se desplazan a %s?' % atacado, range(1, min(self.tablero.ejercitos_pais(atacante) - 1, 3) + 1)) self.tablero.asignar_ejercitos(atacante, -mover) self.tablero.ocupar_pais(atacado, jugador.color, mover) self.tablero.actualizar_interfaz() else: self.tablero.actualizar_interfaz() time.sleep(1) return paises_ganados def realizar_fase_reagrupamiento(self, jugador): """ Realiza el reagrupamiento de ejercitos. """ Interfaz.setear_titulo('%s reagrupa' % jugador) Interfaz.alertar(jugador, '%s reagrupa' % jugador) lista = jugador.reagrupar(self.tablero) # Se fija que el reagrupamiento sea consistente: salientes = {} for origen, destino, cantidad in lista: assert(self.tablero.es_limitrofe(origen, destino)) assert(self.tablero.color_pais(origen) == jugador.color) assert(self.tablero.color_pais(destino) == jugador.color) salientes[origen] = salientes.get(origen, 0) + cantidad for pais in salientes: assert(self.tablero.ejercitos_pais(pais) > salientes[pais]) # Aplica la lista de cambios: for origen, destino, cantidad in lista: self.tablero.asignar_ejercitos(origen, -cantidad) self.tablero.asignar_ejercitos(destino, cantidad) def manejar_tarjetas(self, jugador, paises_ganados): """ Realiza la fase de obtencion de tarjetas de pais. 1) Si el jugador gano un pais del cual no habia usado una tarjeta que posee, se colocan 2 ejercitos en ese pais. 2) Si el jugador realizo menos de 3 canjes y gano al menos un pais o si realizo 3 o mas cajes y gano al menos dos paises, recibe una nueva tarjeta de pais. 3) Si recibio tarjeta de pais y posee ese pais, recibe 2 ejercitos adicionales en el mismo. """ raise NotImplementedError() def agregar_ejercitos(self, inicia_ronda): """Realiza la fase general de colocacion de ejercitos. La cantidad de ejercitos a agregar son: 1) Si el jugador tiene tres tarjetas con el mismo simbolo o si tiene tres tarjetas con distinto simbolo, entonces se realizara el canje. Cuando se realiza el canje, las tarjetas del jugador se devuelven al mazo. El primer canje otorgara 4 ejercitos adicionales para ser colocados en cualquier pais, el segundo 7, el tercero 10 y a partir de ahi 15, 20, 25, etc. 2) El jugador agregara tantos ejercitos como paises / 2 posea (division entera, truncando) en cualquiera de sus paises. 3) Si el jugador poseyera continentes completos agregara el adicional que indica ejercitos_por_continente obligatoriamente en dicho continente.""" raise NotImplementedError def jugador_es_ganador(self, jugador): """Verifica si el jugador gano el juego. Un jugador gana el juego si conquista el 100% de los paises.""" raise NotImplementedError def jugador_esta_vivo(self, jugador): """Verifica si un jugador sigue en carrera. Un jugador muere cuando se queda sin paises.""" raise NotImplementedError def jugar(self): Interfaz.setear_titulo('Trabajo de Entrega Grupal') Interfaz.alertar('Bienvenido!', 'Bienvenido al Trabajo de Entrega Grupal') # Se selecciona el numero de jugadores y se crean los mismos: self.configurar_el_juego() # Se reparten los paises iniciales: self.repartir_paises() self.tablero.actualizar_interfaz() # Se sortea que jugador iniciara el juego: inicia_ronda = random.randrange(len(self.jugadores)) Interfaz.setear_texto("Ronda: %s" % self.texto_ronda(inicia_ronda)) # Primer refuerzo de ejercitos: self.agregar_ejercitos_inicial(inicia_ronda) # Bucle principal del juego: while Interfaz.esta_corriendo(): # Para cada jugador en la ronda: for i in range(len(self.jugadores)): jugador = self.jugadores[(inicia_ronda + i) % len(self.jugadores)] # El jugador puede haber muerto durante esta ronda: if not self.jugador_esta_vivo(jugador): continue # El jugador juega su fase de ataques: paises_ganados = self.realizar_fase_ataque(jugador) # Se verifica si gano el juego: if self.jugador_es_ganador(jugador): Interfaz.alertar('Hay ganador!', 'El jugador %s ha ganado el juego' % jugador) return # El jugador realiza sus reagrupamientos: self.realizar_fase_reagrupamiento(jugador) # Se entrega la tarjeta y se verifica si ocupa # algun pais del cual posee tarjeta. self.manejar_tarjetas(jugador, paises_ganados) # Si algun jugador hubiera perdido durante la ronda # anterior se lo saca del juego: for i in range(len(self.jugadores) - 1, -1, -1): if not self.jugador_esta_vivo(self.jugadores[i]): Interfaz.alertar('Uno menos!', 'El jugador %s ha quedado eliminado' % jugador) self.jugadores.pop(i) if inicia_ronda >= i: inicia_ronda -= 1 # La siguiente ronda es iniciada por el siguiente jugador: inicia_ronda = (inicia_ronda + 1) % len(self.jugadores) Interfaz.setear_texto("Ronda: %s" % self.texto_ronda(inicia_ronda)) # Los jugadores refuerzan sus ejercitos: self.agregar_ejercitos(inicia_ronda) def texto_ronda(self, inicia_ronda): """Magia negra de Python. (Devuelve el nombre de los jugadores en el orden de la ronda.)""" return ', '.join([str(x) for x in self.jugadores[inicia_ronda:] + self.jugadores[:inicia_ronda]])
class Program(object): def __init__(self): self.tablero = Tablero(80, 80) self.screen = pygame.display.set_mode((len(self.tablero.matrix[0]) * 10, len(self.tablero.matrix) * 10 + 32), pygame.DOUBLEBUF) pygame.display.set_caption("Pathfinder") self.clock = pygame.time.Clock() self.pausa = True self.velocidad = 100 self.velocidad_algoritmo = 8 # a star self.pathfinder = PathFinder(self.tablero) # cursor self.cursor = Cursor(self.tablero, self.pathfinder) #fuente pygame.font.init() self.fuente = pygame.font.SysFont("default", 24) self.texto = self.fuente.render("Pausado", True, (255, 0, 255)) self.texto_algo = self.fuente.render("Velocidad: " + str(self.velocidad_algoritmo), True, (255, 0, 255)) def draw_matriz(self): for linea in self.tablero.matrix: for casilla in linea: if casilla.estado == "D": pygame.draw.rect(self.screen, (100, 40, 0), casilla.rect) elif casilla.estado == "A": pygame.draw.rect(self.screen, (255, 255, 0), casilla.rect) elif casilla.estado == "B": pygame.draw.rect(self.screen, (0, 255, 100), casilla.rect) else: pygame.draw.rect(self.screen, (20, 170, 170), casilla.rect) for posibles in self.pathfinder.open_list: pygame.draw.rect(self.screen, (0, 0, 0), posibles.rect) if self.pathfinder.encontrado: for casillas in self.pathfinder.ruta: pygame.draw.rect(self.screen, (0, 255, 0), casillas.rect) else: for analizados in self.pathfinder.closed_list: pygame.draw.rect(self.screen, (255, 255, 240), analizados.rect) def execute(self): self.salir = False while not self.salir: self.clock.tick(self.velocidad) # eventos de teclado for event in pygame.event.get(): if event.type == pygame.QUIT: self.salir = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.pausa = True # submenu if self.pausa: while self.pausa: self.clock.tick(self.velocidad) for event in pygame.event.get(): if event.type == pygame.QUIT: self.pausa = False self.salir = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.pausa = False if event.key == pygame.K_2: if self.velocidad_algoritmo < 30: self.velocidad_algoritmo += 1 if event.key == pygame.K_1: if self.velocidad_algoritmo > 0: self.velocidad_algoritmo -= 1 if event.key == pygame.K_d: if self.cursor.modo_borrar: self.cursor.modo_borrar = False self.texto = self.fuente.render("Pausado", True, (255, 0, 255)) else: self.cursor.modo_borrar = True self.texto = self.fuente.render("Pausado Modo borrar paredes", True, (255, 0, 255)) if event.key == pygame.K_r: self.tablero.matrix = self.tablero.rellenaRandom() self.pathfinder.reset() self.tablero.reset_ab() if pygame.key.get_pressed()[pygame.K_l] and pygame.key.get_pressed()[pygame.K_n]: self.tablero = Tablero(80, 80) self.pathfinder = PathFinder(self.tablero) self.cursor = Cursor(self.tablero, self.pathfinder) #updates self.cursor.update() self.cursor.changeState() self.texto_algo = self.fuente.render("Velocidad: " + str(self.velocidad_algoritmo), True, (255, 0, 255)) # draws self.screen.fill((0, 0, 0)) self.draw_matriz() self.screen.blit(self.texto, (8, self.screen.get_height() - 28)) self.screen.blit(self.texto_algo, (self.screen.get_width() - 200, self.screen.get_height() - 28)) pygame.draw.rect(self.screen, (250, 0, 0), self.cursor.rect) pygame.display.update() #pathfinder #self.pathfinder.run2() for i in range(self.velocidad_algoritmo): self.pathfinder.run() # el que funciona # updates self.cursor.update() # draws self.screen.fill((0, 0, 0)) self.draw_matriz() pygame.display.update()
def main(): key = '' load_succesful = False while (key != '3'): key = menu_main() if (key == '2'): g = menu_load() load_succesful = True elif (key == '3'): sys.exit() if ((key == '1') or (load_succesful is True)): if (load_succesful is False): modo = menu_game_modes() if (modo == '1'): """Modo Normal""" tab_size = int(input('\n' + 'Tamaño del tablero: ')) t = Tablero(tab_size, tab_size) random_place = input('\n' + 'Usar patron al azar? (s/n): ') if (random_place == 's'): cell_alive = int(input('\n' + 'Cantidad ' 'de celdas vivas? ')) t.fill(cell_alive) else: t.manual_fill() g = Game(int(modo), t) elif (modo == '2'): """Modo Vidas Estaticas""" tab_size = int(input('\n' + 'Tamaño del tablero: ')) cell_alive = int( input('\n' + 'Cantidad de celdas vivas? ')) t = Tablero(tab_size, tab_size) g = Game(int(modo), t, cell_alive) if (modo != '3'): g.running = True while (g.running): try: g.run() except KeyboardInterrupt: key = menu_pause() if (key == '1'): continue elif (key == '2'): menu_save(g) elif (key == '3'): g = menu_load() elif (key == '4'): g.tablero.manual_fill() elif (key == '5'): g.running = False
def setUp(self): self._tablero = Tablero(8, 8)
def execute(self): self.salir = False while not self.salir: self.clock.tick(self.velocidad) # eventos de teclado for event in pygame.event.get(): if event.type == pygame.QUIT: self.salir = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.pausa = True # submenu if self.pausa: while self.pausa: self.clock.tick(self.velocidad) for event in pygame.event.get(): if event.type == pygame.QUIT: self.pausa = False self.salir = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.pausa = False if event.key == pygame.K_2: if self.velocidad_algoritmo < 30: self.velocidad_algoritmo += 1 if event.key == pygame.K_1: if self.velocidad_algoritmo > 0: self.velocidad_algoritmo -= 1 if event.key == pygame.K_d: if self.cursor.modo_borrar: self.cursor.modo_borrar = False self.texto = self.fuente.render("Pausado", True, (255, 0, 255)) else: self.cursor.modo_borrar = True self.texto = self.fuente.render("Pausado Modo borrar paredes", True, (255, 0, 255)) if event.key == pygame.K_r: self.tablero.matrix = self.tablero.rellenaRandom() self.pathfinder.reset() self.tablero.reset_ab() if pygame.key.get_pressed()[pygame.K_l] and pygame.key.get_pressed()[pygame.K_n]: self.tablero = Tablero(80, 80) self.pathfinder = PathFinder(self.tablero) self.cursor = Cursor(self.tablero, self.pathfinder) #updates self.cursor.update() self.cursor.changeState() self.texto_algo = self.fuente.render("Velocidad: " + str(self.velocidad_algoritmo), True, (255, 0, 255)) # draws self.screen.fill((0, 0, 0)) self.draw_matriz() self.screen.blit(self.texto, (8, self.screen.get_height() - 28)) self.screen.blit(self.texto_algo, (self.screen.get_width() - 200, self.screen.get_height() - 28)) pygame.draw.rect(self.screen, (250, 0, 0), self.cursor.rect) pygame.display.update() #pathfinder #self.pathfinder.run2() for i in range(self.velocidad_algoritmo): self.pathfinder.run() # el que funciona # updates self.cursor.update() # draws self.screen.fill((0, 0, 0)) self.draw_matriz() pygame.display.update()