def test7(): desc = [ ' ### ', ' #.# ', ' #$# ', ' ##$####', '####@ $$.#', '#.$$ ####', '####$## ', ' #$# ', ' #.# ', ' ### ', ] grilla = soko.crear_grilla(desc) assert soko.mover(grilla, OESTE) == grilla assert soko.mover(grilla, NORTE) == grilla grilla = soko.mover(grilla, ESTE) assert soko.mover(grilla, ESTE) == grilla assert soko.mover(grilla, NORTE) == grilla grilla = soko.mover(grilla, SUR) assert soko.mover(grilla, ESTE) == grilla assert soko.mover(grilla, SUR) == grilla grilla = soko.mover(grilla, OESTE) assert soko.mover(grilla, OESTE) == grilla assert soko.mover(grilla, SUR) == grilla
def test19(): ''' Prueba del primer nivel del TP2 ''' desc1 = [ "#### ", "# .# ", "# ###", "#* #", "#@ $ #", "# ###", "#### " ] desc2 = [ "#### ", "# .# ", "#$ ###", "#+ #", "# $ #", "# ###", "#### " ] grilla1 = soko.crear_grilla(desc1) grilla2 = soko.mover(grilla1, NORTE) verificar_estado(desc2, grilla2)
def test16(): ''' Prueba de pisar el objetivo ''' desc1 = [ '########', '# .@#', '# #', '########', ] desc2 = [ '########', '# + #', '# #', '########', ] desc3 = [ '########', '# @. #', '# #', '########', ] grilla1 = soko.crear_grilla(desc1) grilla2 = soko.mover(grilla1, OESTE) grilla3 = soko.mover(grilla2, OESTE) verificar_estado(desc1, grilla1) verificar_estado(desc2, grilla2) verificar_estado(desc3, grilla3)
def test4(): desc = [ '#####', '# *.#', '#@ $#', '#####', ] grilla = soko.crear_grilla(desc) verificar_estado(desc, grilla) assert not soko.juego_ganado(grilla)
def test8(): desc = [ '########', '#@ $ . #', '########', ] grilla = soko.crear_grilla(desc) verificar_estado(desc, grilla) assert not soko.juego_ganado(grilla) for direction in (OESTE, NORTE, SUR): grilla = soko.mover(grilla, direction) verificar_estado(desc, grilla) assert not soko.juego_ganado(grilla) grilla = soko.mover(grilla, ESTE) desc = [ '########', '# @$ . #', '########', ] verificar_estado(desc, grilla) assert not soko.juego_ganado(grilla) for direction in (NORTE, SUR): grilla = soko.mover(grilla, direction) verificar_estado(desc, grilla) assert not soko.juego_ganado(grilla) grilla = soko.mover(grilla, ESTE) verificar_estado([ '########', '# @$. #', '########', ], grilla) assert not soko.juego_ganado(grilla) grilla = soko.mover(grilla, OESTE) verificar_estado([ '########', '# @ $. #', '########', ], grilla) assert not soko.juego_ganado(grilla) grilla = soko.mover(grilla, ESTE) grilla = soko.mover(grilla, ESTE) verificar_estado([ '########', '# @* #', '########', ], grilla) assert soko.juego_ganado(grilla)
def test18(): ''' Prueba de un movimiento invalido con el jugador posicionado sobre un objetivo ''' desc1 = [ '########', '# $$+ #', '# #', '########', ] grilla1 = soko.crear_grilla(desc1) grilla2 = soko.mover(grilla1, OESTE) verificar_estado(desc1, grilla2)
def test15(): ''' Prueba de moverse a los limites del tablero ''' desc1 = [ '########', '# @#', '# * #', '########', ] grilla1 = soko.crear_grilla(desc1) grilla2 = soko.mover(grilla1, ESTE) grilla3 = soko.mover(grilla1, NORTE) assert grilla1 == grilla3
def test14(): ''' Prueba de que no se pueda mover una caja en objetivo adyacente a una fuera de objetivo ''' desc1 = [ '########', '# @*$#', '# . #', '########', ] grilla1 = soko.crear_grilla(desc1) grilla2 = soko.mover(grilla1, ESTE) assert not soko.juego_ganado(grilla2) assert grilla1 == grilla2
def test10(): ''' Prueba de que se pueda sacar una caja del objetivo ''' desc1 = [ '########', '# @* #', '# #', '########', ] grilla1 = soko.crear_grilla(desc1) grilla2 = soko.mover(grilla1, ESTE) assert not soko.juego_ganado(grilla2) assert grilla1 != grilla2
def test9(): ''' Prueba de que se pueda mover una caja hacia el objetivo ''' desc1 = [ '########', '# @$. #', '# #', '########', ] grilla1 = soko.crear_grilla(desc1) grilla2 = soko.mover(grilla1, ESTE) assert soko.juego_ganado(grilla2) assert grilla1 != grilla2
def test6(): desc1 = [ '######', '#@ $.#', '######', ] desc2 = [ '######', '# @$.#', '######', ] grilla1 = soko.crear_grilla(desc1) grilla2 = soko.mover(grilla1, ESTE) # Si el movimiento es válido, la función mover() debe devolver una grilla nueva # y NO modificar la grilla recibida. verificar_estado(desc1, grilla1) verificar_estado(desc2, grilla2)
def test17(): ''' Prueba de mover una caja con objetivo hacia otro objetivo ''' desc1 = [ '########', '# @*.#', '# #', '########', ] desc2 = [ '########', '# +*#', '# #', '########', ] grilla1 = soko.crear_grilla(desc1) grilla2 = soko.mover(grilla1, ESTE) verificar_estado(desc1, grilla1) verificar_estado(desc2, grilla2)
def reiniciar(juego, niveles, nivel, soluciones): return soko.crear_grilla(niveles[int(nivel)])
def juego_crear(nivel, niveles): '''Devuelve la grilla dependiendo del nivel, siendo este un numero entero que indicara el numero del indice en la lista''' return soko.crear_grilla(niveles[nivel])
def main(): niveles = cargar_memoria("niveles.txt") configuracion = cargar_configuracion_teclas("teclas.txt") for nivel in niveles: # Inicializar el estado del juego grilla = soko.crear_grilla(nivel[1]) gamelib.resize(len(grilla[0]) * 64, len(grilla) * 64) movimientos = Pila() while gamelib.is_alive(): # Dibujar la pantalla gamelib.draw_begin() juego_mostrar(grilla, nivel[0]) gamelib.draw_end() ev = gamelib.wait(gamelib.EventType.KeyPress) if not ev: break tecla = ev.key accion = pedir_accion(configuracion, tecla) # Actualizar el estado del juego, según la `tecla` presionada if accion == "PISTA": gamelib.draw_begin() juego_mostrar(grilla, nivel[0]) gamelib.draw_text("Pensando...", 40, 10, size=10, fill="white") gamelib.draw_end() solucion = buscar_solucion(grilla) gamelib.get_events() if not solucion[0]: gamelib.draw_begin() juego_mostrar(grilla, nivel[0]) gamelib.draw_text("No hay pistas disponibles :(", 85, 10, size=10, fill="white") gamelib.draw_end() ev = gamelib.wait(gamelib.EventType.KeyPress) continue if solucion[0]: gamelib.draw_begin() juego_mostrar(grilla, nivel[0]) gamelib.draw_text("Pista Disponible", 50, 10, size=10, fill="white") gamelib.draw_end() while not solucion[1].esta_vacia(): ev = gamelib.wait(gamelib.EventType.KeyPress) if not ev: break tecla = ev.key accion = pedir_accion(configuracion, tecla) if accion != None and accion != "PISTA": break if accion == "PISTA": movimientos.apilar(grilla) grilla = soko.mover(grilla, solucion[1].desapilar()) gamelib.draw_begin() juego_mostrar(grilla, nivel[0]) gamelib.draw_text("Pista Disponible", 50, 10, size=10, fill="white") gamelib.draw_end() if soko.juego_ganado(grilla): sleep(0.1) break if accion == "SALIR": return if accion == "REINICIAR": grilla = soko.crear_grilla(nivel[1]) movimientos = Pila() continue if accion == "DESHACER": if movimientos.esta_vacia(): continue grilla = movimientos.desapilar() continue if not accion: continue movimientos.apilar(grilla) grilla = soko.mover(grilla, accion) if soko.juego_ganado(grilla): gamelib.draw_begin() juego_mostrar(grilla, nivel[0]) gamelib.draw_end() sleep(0.1) break
def setear_juego(niveles, nivel): juego = soko.crear_grilla(niveles[nivel]) resize(juego) gamelib.title("Sokoban - Nivel: " + str(nivel)) return juego
def main(): '''Inicializa el juego''' gl.title("Sokoban") try: # Genera la lista de niveles, con la matriz de objetos, y el nombre del nivel. niveles = parser.lista_niveles(ARCHIVO_NIVELES) except (IOError, FileNotFoundError): render.error_archivo(ARCHIVO_NIVELES) ev = gl.wait(gl.EventType.KeyPress) return try: # Genera el diccionario con las teclas, y la accion que generan esas teclas controles = parser.dict_controles(ARCHIVO_CONTROLES) except (IOError, FileNotFoundError): render.error_archivo(ARCHIVO_CONTROLES) ev = gl.wait(gl.EventType.KeyPress) return nivel_nro = PRIMER_NIVEL - 1 # Empezar contador de tiempo para dar tiempo total luego de finalizados todos los niveles tiempo_inicial = time.time() # Itera por cada nivel while gl.is_alive(): nivel = niveles[nivel_nro].copy() grilla = nivel["grilla"] titulo = nivel["title"] nivel_actual = soko.crear_grilla(grilla) x, y = render.cambiar_tamanio_ventana(nivel_actual) render.titulo(titulo, (x, y)) time.sleep(1) accion = (0, 1) # Crea nuevas instancias, para que no genere errores cuando pase de nivel deshacer = Deshacer() backtraking = Backtracking() # Este ciclo solo espera al input del jugador while True: gl.draw_begin() render.nivel(nivel_actual, accion) gl.draw_end() ev = gl.wait(gl.EventType.KeyPress) if not ev: return tecla = ev.key if not tecla in controles: continue accion = controles[tecla] # Actualizar el estado del juego, según la `tecla` presionada if type(accion) == tuple: deshacer.agregar_estado(nivel_actual) backtraking.solucion_disponible = False nivel_actual = soko.mover(nivel_actual, accion) elif accion == "REINICIAR": deshacer.agregar_estado(nivel_actual) nivel_actual = soko.crear_grilla(grilla) backtraking.solucion_disponible = False elif accion == "PISTA": if not backtraking.solucion_disponible: render.pensando_solucion(nivel_actual) try: backtraking.generar_solucion(nivel_actual) except: render.error_backtracking() ev = gl.wait(gl.EventType.KeyPress) render.cambiar_tamanio_ventana(nivel_actual) else: deshacer.agregar_estado(nivel_actual) accion = backtraking.obtener_mov() nivel_actual = soko.mover(nivel_actual, accion) elif accion == "DESHACER": if deshacer.se_puede_deshacer(): nivel_actual = deshacer.deshacer_movimiento() backtraking.solucion_disponible = False else: gl.play_sound('src/alert.wav') elif accion == "SALIR": return if soko.juego_ganado(nivel_actual): break # Paso al siguiente nivel nivel_nro += 1 # Verifica que haya terminado todos los niveles if nivel_nro >= len(niveles): tiempo_final = time.time() tiempo_total = tiempo_final - tiempo_inicial # Genera horas, minutos y segundos tiempo = "Tiempo total " + convertir_segundos(tiempo_total) render.final((x, y), tiempo) ev = gl.wait(gl.EventType.KeyPress) return
def main(): # Inicializar el estado del juego deshacer = Pila() pistas = [] teclas = archivo_teclas(RUTA_TECLAS) niveles = archivo_niveles(RUTA_NIVELES) contador = es_nivel(gamelib.input("Eliga un nivel:"), niveles) juego = emparejar(niveles[contador]) #lista de cadenas c, f = soko.dimensiones(juego) gamelib.resize(c * DIM_CELDA, f * DIM_CELDA) juego = soko.crear_grilla(juego) #lista de listas dibujar_juego(contador, juego, 1) while gamelib.is_alive(): ev = gamelib.wait(gamelib.EventType.KeyPress) if not ev: break # Actualizar el estado del juego, según la `tecla` presionada tecla = ev.key if es_tecla(tecla, teclas) == None: continue if tecla == 'Escape': gamelib.say("Gracias por jugar Sokoban :)") break if tecla == 'h': if len(pistas) == 0: pistas = backtraking(contador, juego) if pistas == None: pistas = [] else: pista = pistas.pop() juego = soko.mover(juego, pista) deshacer.apilar(juego) dibujar_juego(contador, juego, 2) #pista disponible if soko.juego_ganado(juego): contador += 1 while not deshacer.esta_vacia(): deshacer.desapilar() gamelib.say("Pasaste al siguiente nivel :)") juego = emparejar(niveles[contador]) c, f = soko.dimensiones(juego) gamelib.resize(c * DIM_CELDA, f * DIM_CELDA) juego = soko.crear_grilla(juego) dibujar_juego(contador, juego, 1) if tecla == 'r': if len(pistas) != 0: pistas = [] juego = emparejar(niveles[contador]) c, f = soko.dimensiones(juego) gamelib.resize(c * DIM_CELDA, f * DIM_CELDA) juego = soko.crear_grilla(juego) dibujar_juego(contador, juego, 1) if tecla == 'Control_L': if not deshacer.esta_vacia(): juego = deshacer.desapilar() dibujar_juego(contador, juego, 1) if teclas[tecla] in DIRECCIONES: deshacer.apilar(juego) juego = soko.mover(juego, DIRECCIONES[teclas[tecla]]) dibujar_juego(contador, juego, 1) if tecla != 'h': #vaciar la lista if len(pistas) != 0: pistas = []