def test_longitud(self): # Arrange juego = Juego() # Act juego.setear_palabra("Roma") x = juego.devolver_longitud() # Assert self.assertEqual(x, 4)
def test_letra_no_incluida(self): # Arrange juego = Juego() juego.setear_palabra("Londres") # Act letra = 'a' ingreso = juego.esta_incluida(letra) # Assert self.assertFalse(ingreso)
def test_dificultad(self): # Arrange juego = Juego() # Act dificultad = 3 juego.setear_dificultad(dificultad) x = juego.devolver_dificultad() # Assert self.assertEqual(x, dificultad)
def test_seleccionar_palabra(self): # Arrange juego = Juego() # Act a = juego.seleccionar_palabra(2) if a != None: x = True #Assert self.assertTrue(x)
def manejar_accion(self, accion): '''Maneja la acción recibida del cliente.''' print(f'Acción recibida: {accion}') # -------------------- # Completar desde aquí tipo = accion[ "comando"] # Obtener el tipo de acción que envió el cliente. # Completar hasta aquí # -------------------- if tipo == '\\juego_nuevo': self.juego = Juego() self.juego.crear_tablero() self.enviar_estado('', True) elif tipo == '\\salir': self.enviar_estado('¡Adios!', False) self.juego = None self.socket_cliente.close() print('Cliente desconectado.\n') self.socket_cliente = None elif tipo == '\\jugada': if self.juego is None: self.enviar_estado('Ningún juego ha iniciado.', True) else: # -------------------- # Completar desde aquí # Obtener la jugada que envió el cliente. jugada = int(accion["columna"]) # Completar hasta aquí # -------------------- if not self.juego.es_jugada_valida(jugada): self.enviar_estado('Jugada inválida.', True) else: gano = self.juego.turno_jugador(jugada) if gano: self.enviar_estado('¡Ganaste! Se acabó el juego.', True) self.juego = None else: perdio = self.juego.turno_cpu() if perdio or self.juego.empate(): self.enviar_estado( 'No ganaste :( Se acabó el juego.', True) self.juego = None else: self.enviar_estado('', True)
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 test_palabra_incorrecta_numero_intento(self): # Arrange juego = Juego() juego.setear_palabra("Paris") # Act intentos = 3 juego.setear_intentos(intentos) intentos_test = juego.devolver_intento() intentos_test -= 1 palabra_incorrecta = 'Madrid' juego.palabra_correcta(palabra_incorrecta) intentos_clase = juego.devolver_intento() # Assert self.assertEqual(intentos_test, intentos_clase)
def test_palabra_incorrecta_condicion(self): # Arrange juego = Juego() juego.setear_palabra("Paris") # Act intentos = 3 juego.setear_intentos(intentos) palabra_incorrecta = 'Madrid' juego.palabra_correcta(palabra_incorrecta) c = juego.devolver_condicion() # Assert self.assertFalse(c)
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 test_letra_correcta_no_restar_intento(self): # Arrange juego = Juego() a = 'Roma' juego.setear_palabra(a) intentos = 3 juego.setear_intentos(intentos) # Act letra_correcta = 'a' juego.letra_correcta(letra_correcta) intentos_clase = juego.devolver_intento() #Assert self.assertEqual(intentos_clase, 3)
def registrarJuego(): juego = Juego( nombre=request.json['nombre'], anio=request.json['anio'], precio=request.json['precio'], foto=request.json['foto'], banner=request.json['banner'], descripcion=request.json['descripcion'], create_user='******', ) db.session.add(juego) db.session.commit() return jsonify(msg='Juego agregado correctamente!!!'), 200
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 test_palabra_correcta(self): # Arrange juego = Juego() # Act a = 'Roma' juego.setear_palabra(a) x = juego.palabra_correcta(a) c = juego.devolver_condicion() # Assert self.assertTrue(c)
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_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 test_puntaje_segundo(self): # Arrange juego = Juego() # Act dificultad = 2 palabra_correcta = "Londres" intentos = 8 juego.setear_dificultad(dificultad) juego.setear_palabra(palabra_correcta) juego.setear_intentos(intentos) juego.palabra_correcta("Berlin") juego.palabra_correcta("Berlin") juego.palabra_correcta("Berlin") juego.palabra_correcta("Berlin") juego.palabra_correcta("Londres") x = juego.calcular_puntajes() # Assert self.assertEqual(x, 40)
import network import utime as time from credenciales import ssid, password from apds9930 import APDS9930 from juego import Juego def conectar_wifi(): print('\nConectandose a la wifi...', end='') red = network.WLAN(network.STA_IF) red.active(True) red.connect(ssid, password) while not red.isconnected(): time.sleep(0.1) print('conectado!') print(red.ifconfig()) i2c = I2C(sda=Pin(4), scl=Pin(5)) try: sensor = APDS9930(i2c) sensor.activar_proximidad() except Exception as e: sensor = None conectar_wifi() juego = Juego("Rober .H") juego.metodo_entrada(sensor) juego.start()
def iniciar(self): juego = Juego(self) juego.show() self.setVisible(False)
def test_finalizacion_juego_ganado(self): # Arrange juego = Juego() # Act palabra_correcta = "Londres" intentos = 4 juego.setear_palabra(palabra_correcta) juego.setear_intentos(intentos) letra = 'L' ingreso = juego.arriesgar(letra) letra = 'o' ingreso = juego.arriesgar(letra) letra = 'n' ingreso = juego.arriesgar(letra) letra = 'd' ingreso = juego.arriesgar(letra) letra = 'r' ingreso = juego.arriesgar(letra) letra = 'e' ingreso = juego.arriesgar(letra) letra = 'e' ingreso = juego.arriesgar(letra) resultado = juego.devolver_condicion() # Assert self.assertTrue(resultado)
def main(): bazas = Juego() gamelib.resize(1230, 700) graficos.dibujar_tablero() bazas.inicializar_juego(pedir_opcion()) while not bazas.terminado(): bazas.mezclar_mazo() bazas.repartir_cartas() mostrar_estado_juego(bazas) bazas.suma_apuestas = 0 for indice, jugador in enumerate(bazas.lista_jugadores): jugador.pedir_apuesta(indice, bazas.suma_apuestas, bazas) bazas.rotar_jugadores() mostrar_estado_juego(bazas) #bazas.pedir_apuestas() while not bazas.ronda_terminada(): mostrar_estado_juego(bazas) for jugador in bazas.lista_jugadores: jugador.pedir_jugada() bazas.rotar_jugadores() mostrar_estado_juego(bazas) bazas.determinar_ganador_ronda() bazas.contabilizar_puntos_ronda() mostrar_ganador(bazas)
def setUp(self): print("Iniciando la clase Juego") self.juegoEjemplo = Juego("diablo 3", 65)
from juego import Juego game = Juego(7, 7, 6, None) print(game.evolucionar())
import os import time from threading import Thread import cursor from juego import Juego miJuego = Juego(25, 25) os.system("cls") cursor.hide() class Input(Thread): def __init__(self): Thread.__init__(self) def run(self): global miJuego while miJuego.jugar: miJuego.input() input = Input() input.start() while miJuego.jugar: print("\033[%d;%dH" % (0, 0)) miJuego.update()
# it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor Boston, MA 02110, USA # or see <http://www.gnu.org/licenses/> from juego import Juego def show_license(): text = """ waratsea Copyright (C) 2008 Alejandro Varas This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. """ print text if __name__ == '__main__': show_license() juego = Juego() juego.main()
class Juego_test(unittest.TestCase): def setUp(self): print("Iniciando la clase Juego") self.juegoEjemplo = Juego("diablo 3", 65) def test_juego_inicio(self): self.assertEqual(self.juegoEjemplo.nombre, 'diablo 3') self.assertEqual(self.juegoEjemplo.precio, 65) self.assertEqual(self.juegoEjemplo.precioRebajado, 32.5) def test_comprobar_nombre(self): with self.assertRaises(Exception) as context: self.juegoEjemplo.cambiar_nombre(43) self.assertTrue(context, "El nombre no puede ser un numero") self.juegoEjemplo.cambiar_nombre("Zelda") def test_comprobar_precio_total(self): with self.assertRaises(Exception) as context: self.juegoEjemplo.cambiar_precio_final(-200) self.assertTrue(context, "El precio no puede ser menor que 0") def test_comprobar_precio_rebajado(self): with self.assertRaises(Exception) as context: self.juegoEjemplo.cambiar_precio_rebajado(0) self.assertTrue(context, "El precio rebajado no puede ser menor que 0") def test_comprobar_precios(self): with self.assertRaises(Exception) as context: self.juegoEjemplo.cambiar_precios(0, 0.15) self.assertTrue(context, "El precio no puede ser menor que 0") with self.assertRaises(Exception) as context: self.juegoEjemplo.cambiar_precios(15, 0) self.assertTrue(context, "El precio rebajado no puede ser menor que 0")
from ficha import Ficha from jugador import Jugador from juego import Juego from tablero import Tablero multijugador = False correcto = False while (not correcto): try: respuestaMenu = int( input( "BIENVENIDO A PYTHONMINO!!! \n Como desea Jugar? \n1.Individual\n2.Equipos\nElija:" )) if (respuestaMenu != 1 and respuestaMenu != 2): print("Error! Debe ser 1 o 2") else: correcto = True except ValueError: print("Error! Debe ser 1 o 2") if respuestaMenu == 1: multijugador = False else: multijugador = True domino = Juego() tablero = Tablero() domino.iniciarJuego(True, multijugador) domino.jugando(80, multijugador)
led.value(1) # apagamos led para indicar que ya estamos conectados i2c = I2C( sda=Pin(4), scl=Pin(5)) # instanciamos y configuramos bus I2C en los pines sda y scl try: sensor = APDS9930( i2c ) # creamos una instancia del sensor y le pasamos el manejador del i2c sensor.activar_proximidad( ) # este metodo modifica un registro interno del APDS9930 para activar el sensor de proximidad except Exception as e: print( "No se ha podido iniciar el sensor APDS9930. El juego funcionará con el boton. Error:" ) print(e) sensor = None conectar_wifi() juego = Juego("Dani") # instanciamos el juego pasandole el nombre del jugador juego.usar_sensor( sensor) # si comentamos esta linea funcionaria con el boton de la placa try: juego.comenzar() # bucle infinito except Exception as e: print(e) juego.finalizar() # uos.remove("juegodb") # con esta linea podemos eliminar la base de datos para empezar de cero
from domador import Domador from dragon import Dragon from juego import Juego dragon1 = Dragon(0, 30, "Flofi") dragon2 = Dragon(10, 21, "Rufus") dragon3 = Dragon(15, 12, "Nicolas Harari") listaDragones = [dragon1, dragon2, dragon3] domador1 = Domador(10, 15, "Pablo") domador2 = Domador(20, 20, "Tania") domador3 = Domador(30, 30, "Renata") listaDomadores = [domador1, domador2, domador3] juego = Juego(100, listaDragones, listaDomadores) while not juego.estaTerminado(): juego.avanzarTurno()
class Servidor: def __init__(self): '''Inicializador de servidor. Crea socket de servidor, lo vincula a un puerto.''' # ----------------------------------------- # Completar y agregar argumentos desde aquí self.host = socket.gethostbyname(socket.gethostname()) self.port = 9001 self.socket_servidor = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Aqui deberas preparar el socket para que escuche una conexion self.socket_servidor.bind((self.host, self.port)) self.socket_servidor.listen() # Completar y agregar argumentos hasta aquí # ----------------------------------------- print("Servidor iniciado.") self.juego = None # Juego comienza nulo. self.socket_cliente = None # Aún no hay cliente. def esperar_conexion(self): '''Espera a la conectarse con un cliente y obtiene su socket.''' print("Esperando cliente...") # -------------------- # Completar desde aquí # Debes actualizar el valor de self.socket_cliente al conectar try: self.socket_cliente, address = self.socket_servidor.accept() except ConnectionError: print("Ocurrió un error.") # Completar hasta aquí # -------------------- print("¡Servidor conectado a cliente!") self.interactuar_con_cliente() def interactuar_con_cliente(self): '''Comienza ciclo de interacción con cliente. Recibe un acción y responde apropiadamente.''' self.enviar_estado('', True) while self.socket_cliente: accion = self.recibir_accion() self.manejar_accion(accion) def enviar_estado(self, mensaje, continuar): '''Envia estado del juego en el servidor.''' if continuar: if self.juego is not None: mensaje = f'{self.juego.tablero_string()}\n{mensaje}\n' acciones = ("¿Qué deseas hacer?\n" "Para jugar nuevo juego: \\juego_nuevo\n" "Para jugar en una columna: \\jugada columna\n" "Para salir: \\salir\n") mensaje = mensaje + acciones # ----------------------------------------------------- # Completar y usar un metodo para todo largo de mensaje dict_msg = {"mensaje": mensaje, "continuar": continuar} mensaje_codificado = pickle.dumps(dict_msg) largo_msg = len(mensaje_codificado).to_bytes(4, byteorder='big') self.socket_cliente.sendall(largo_msg + mensaje_codificado) # Completar hasta aquí # -------------------- def recibir_accion(self): '''Recibe mensaje desde el cliente y lo decodifica.''' # ----------------------------------------------------- # Completar y usar un metodo para todo largo de mensaje largo_msg = int.from_bytes(self.socket_cliente.recv(4), byteorder='big') bytes_recibidos = bytearray() while len(bytes_recibidos) < largo_msg: largo_leer = min(200, largo_msg - len(bytes_recibidos)) bytes_recibidos.extend(self.socket_cliente.recv(largo_leer)) mensaje_serializado = bytes_recibidos.decode("UTF-8") accion = json.loads(mensaje_serializado) # Completar hasta aquí # -------------------- return accion def manejar_accion(self, accion): '''Maneja la acción recibida del cliente.''' print(f'Acción recibida: {accion}') # -------------------- # Completar desde aquí tipo = accion[ "comando"] # Obtener el tipo de acción que envió el cliente. # Completar hasta aquí # -------------------- if tipo == '\\juego_nuevo': self.juego = Juego() self.juego.crear_tablero() self.enviar_estado('', True) elif tipo == '\\salir': self.enviar_estado('¡Adios!', False) self.juego = None self.socket_cliente.close() print('Cliente desconectado.\n') self.socket_cliente = None elif tipo == '\\jugada': if self.juego is None: self.enviar_estado('Ningún juego ha iniciado.', True) else: # -------------------- # Completar desde aquí # Obtener la jugada que envió el cliente. jugada = int(accion["columna"]) # Completar hasta aquí # -------------------- if not self.juego.es_jugada_valida(jugada): self.enviar_estado('Jugada inválida.', True) else: gano = self.juego.turno_jugador(jugada) if gano: self.enviar_estado('¡Ganaste! Se acabó el juego.', True) self.juego = None else: perdio = self.juego.turno_cpu() if perdio or self.juego.empate(): self.enviar_estado( 'No ganaste :( Se acabó el juego.', True) self.juego = None else: self.enviar_estado('', True)
from juego import Juego import pyglet from pyglet.gl import * from pyglet import clock from pyglet.window import key from numeros import numeros window = pyglet.window.Window() clock.set_fps_limit(60) j = Juego() j.ant = j.tablero.copy() @window.event def on_key_press(symbol, modifiers): if symbol == key.B: j.tablero = j.ant j.ant = j.tablero.copy() if symbol == key.LEFT: j.moveLeft() elif symbol == key.RIGHT: j.moveRigth() elif symbol == key.UP: j.moveUp() elif symbol == key.DOWN: j.moveDown() @window.event
def step(context, manojugador, manorepartidor): # context.jugador=Jugador context.mano = manojugador context.mano2 = manorepartidor context.juego = Juego()
from juego import Juego #Gen0 juego = Juego(7, 7, 6, [(1, 2), (2, 1), (2, 2), (2, 3)]) print(f"-Genracion 1-") juego.imprime_grid() juego.contarVivas() print("") #juego.evolucionar()#Metodo de juego, toma el array clonado. #juego.imprime_grid()#imprime la matriz #print(juego.get_numero_vecinos_vivos(1,2))#Probar cuadro CelulaViva. for grc in range(juego.generacioness()): print("") juego.evolucionar() print(f"-Generacion {grc + 2 }-") juego.imprime_grid() juego.contarVivas()