def main(): # Inicializar el estado del juego gamelib.resize(ANCHO_PANTALLA, ALTO_PANTALLA) timer_bajar = ESPERA_DESCENDER juego = crear_juego(tetris.ALTO_JUEGO, tetris.ANCHO_JUEGO) while gamelib.loop(fps=30): gamelib.draw_begin() dibujar_interfaz(juego) gamelib.draw_end() if tetris.terminado(juego.superficies): time.sleep(10) return for event in gamelib.get_events(): if not event: break if event.type == gamelib.EventType.KeyPress: tecla = event.key if tecla == "g": guardar_partida(juego, "partidas.txt") if tecla == "c": juego = cargar_partida(juego, "partidas.txt") if tecla == "Escape": return actualizar_juego(juego, tecla) # Actualizar el juego, según la tecla presionada timer_bajar -= 1 if timer_bajar == 0: actualizar_juego(juego) timer_bajar = ESPERA_DESCENDER
def main(): juego = juego_crear() turno = 0 # Ajustar el tamaño de la ventana gamelib.resize(300, 350) # Mientras la ventana esté abierta: while gamelib.is_alive(): # Todas las instrucciones que dibujen algo en la pantalla deben ir # entre `draw_begin()` y `draw_end()`: gamelib.draw_begin() juego_mostrar(juego,turno) gamelib.draw_end() # Terminamos de dibujar la ventana, ahora procesamos los eventos (si el # usuario presionó una tecla o un botón del mouse, etc). # Esperamos hasta que ocurra un evento ev = gamelib.wait() if not ev: # El usuario cerró la ventana. break if ev.type == gamelib.EventType.KeyPress and ev.key == 'Escape': # El usuario presionó la tecla Escape, cerrar la aplicación. break if ev.type == gamelib.EventType.ButtonPress: # El usuario presionó un botón del mouse x, y = ev.x, ev.y # averiguamos la posición donde se hizo click juego, turno = juego_actualizar(juego, x, y, turno) print(juego)
def main(): # Inicializar el estado del juego niveles = archivos.cargar_niveles('niveles.txt') acciones = archivos.cargar_accion_de_tecla('teclas.txt') grilla, nivel = juego_inicializar(niveles) x, y = soko.dimensiones(grilla) gamelib.resize(x * PIXELES_GIF, y * PIXELES_GIF) while gamelib.is_alive(): gamelib.draw_begin() mostrar_interfaz(grilla) gamelib.draw_end() ev = gamelib.wait(gamelib.EventType.KeyPress) if not ev: break tecla = ev.key accion = procesar_tecla_presionada(tecla, acciones) grilla = juego_actualizar(grilla, nivel, niveles, accion) if not grilla: break if soko.juego_ganado(grilla): nivel, grilla = juego_pasar_nivel(nivel, niveles) if not grilla: break
def main(): gamelib.resize(300, 300) gamelib.draw_begin() gamelib.draw_text('Hello world!', 150, 150) gamelib.draw_end() gamelib.wait(gamelib.EventType.KeyPress)
def pensando_solucion(nivel_actual): '''Muestra en pantalla que el backtracing se esta realizando''' gl.draw_begin() nivel(nivel_actual) gl.draw_text('Pensando una solucion', 10, 20, fill='white', anchor='w') gl.draw_end()
def main(): gamelib.resize(1500, 1000) gamelib.draw_begin() gamelib.draw_text('Hello world!', 150, 150) dibujar_pantalla_de_inicio() gamelib.draw_end() gamelib.wait(gamelib.EventType.KeyPress)
def main(): # Inicializar el estado del juego #siguiente_pieza = tetris.generar_pieza() siguiente = tetris.generar_pieza() t1= time.time() juego = tetris.crear_juego(tetris.generar_pieza()) ancho, alto = tetris.dimensiones(juego) lista_teclas = leer_teclas() gamelib.resize(800, 900) timer_bajar = ESPERA_DESCENDER while gamelib.loop(fps=30): gamelib.draw_begin() dibujar_superficie(juego) dibujar_pieza(juego) dibujar_siguiente(juego, siguiente) gamelib.draw_end() for event in gamelib.get_events(): if not event: break if event.type == gamelib.EventType.KeyPress: tecla = event.key if tecla == lista_teclas[1]: juego = tetris.mover(juego, -1) if tecla == lista_teclas[3]: juego = tetris.mover(juego, 1) if tecla == lista_teclas[5]: juego = tetris.mover(juego, 2) if tecla == lista_teclas[0]: return if tecla == lista_teclas[6]: juego = tetris.rotar(juego) if tecla == lista_teclas[4]: guardar_partida(juego) if tecla == lista_teclas[2]: juego = recuperar_partida() # Actualizar el juego, según la tecla presionada timer_bajar -= 1 if timer_bajar == 0: timer_bajar = ESPERA_DESCENDER juego, siguiente_pieza = tetris.avanzar(juego, siguiente) if siguiente_pieza: siguiente = tetris.generar_pieza() if tetris.terminado(juego): gamelib.draw_image('img/perdiste.gif', 50, 200) t2 = time.time() tiempo_final = t2- t1 gamelib.draw_rectangle(0, 0, 595, 60, outline='white', fill='salmon') gamelib.draw_text('Tu tiempo fue de {} segundos'.format(tiempo_final), 10, 17, fill='#000', size=18, anchor='nw') puntuaciones(tiempo_final) break while gamelib.is_alive(): ordenar_puntuaciones() event = gamelib.wait(gamelib.EventType.KeyPress)
def main(): gamelib.title("Chase") gamelib.resize(600, 400) while gamelib.is_alive(): n = 0 juego = chase.Juego(n) while not juego.terminado(): juego = juego.inicializar_siguiente_nivel(n + 1) while not juego.nivel_terminado(): gamelib.draw_begin() mostrar_estado_juego(juego) gamelib.draw_end() # Terminamos de dibujar la ventana, ahora procesamos los eventos (si el # usuario presionó una tecla o un botón del mouse, etc). # Esperamos hasta que ocurra un evento ev = gamelib.wait() if not ev: # El usuario cerró la ventana. break if ev.type == gamelib.EventType.KeyPress: tecla = ev.key if tecla in TECLAS: juego.avanzar_un_step(tecla) if juego.nivel_perdido(): gamelib.say('Te atrapo un robot, ¡Perdiste el juego!') return juego.mover_robots() if juego.nivel_perdido(): gamelib.say('Te atrapo un robot, ¡Perdiste el juego!') return if juego.nivel_terminado(): gamelib.say('Felicidades, pasaste al siguiente nivel') n+=1 break gamelib.say('Felicidades, GANASTE EL JUEGO') return
def error_archivo(archivo): '''Recibe como parametro un string. Muestra en pantalla un error de archivo''' gl.resize(500, 300) error = "Hubo un error con el archivo: " + archivo + "\nSi modificó el archivo, regrese a su archivo original.\nSi no lo modificó, reinstale el juego." gl.draw_begin() gl.draw_text(error, 250, 150, justify="center", fill="red") gl.draw_text("Presiona una tecla para salir del juego", 250, 285, 7) gl.draw_end()
def draw(life): gamelib.draw_begin() for y, row in enumerate(life): for x, cell in enumerate(row): if cell: gamelib.draw_rectangle( x * CELL_SIZE, y * CELL_SIZE, x * CELL_SIZE + CELL_SIZE, y * CELL_SIZE + CELL_SIZE, fill='white', ) gamelib.draw_end()
def error_backtracking(): '''Muestra en pantalla que el backtracing no pudo realizarse''' gl.resize(500, 300) error = "No se pudo resolver el nivel." gl.draw_begin() gl.draw_text(error, 250, 150, justify="center", fill="red") gl.draw_text("Presiona una tecla para continuar", 250, 285, 7) gl.draw_end()
def main(): niveles = cargar_niveles() nivel = 1 teclas = cargar_teclas() juego = setear_juego(niveles, nivel) movimientos = Pila() soluciones = Pila() mensaje = "" while gamelib.is_alive(): gamelib.draw_begin() dibujar(juego) gamelib.draw_end() gamelib.draw_text(mensaje,15,15,anchor="w") ev = gamelib.wait(gamelib.EventType.KeyPress) if not ev: break tecla = ev.key if tecla in teclas: if teclas[tecla] == "REINICIAR": juego = reiniciar(juego, niveles, nivel, soluciones) elif teclas[tecla] == "SALIR": break elif teclas[tecla] == "DESHACER": if movimientos.tope: juego = deshacer(movimientos, juego) elif teclas[tecla] == "AYUDA": if soluciones.esta_vacia(): gamelib.draw_text("Pensando...", 15, 15, anchor="w") gamelib.get_events() #Utilizo .get_events() como una especie de mutex para evitar que el usuario interactúe solucion_encontrada, soluciones = solver.buscar_solucion(juego, DIRECCIONES) gamelib.get_events() if solucion_encontrada: mensaje = "Hay pista disponible" else: mensaje = "No hay chance" else: movimientos.apilar(juego) juego = soko.mover(juego, soluciones.desapilar()) else: movimientos.apilar(juego) juego = soko.mover(juego, DIRECCIONES[teclas[tecla]]) if tecla and not teclas[tecla] == "AYUDA": soluciones = Pila() mensaje = "" if soko.juego_ganado(juego): nivel = nivel + 1 juego = setear_juego(niveles, nivel) movimientos = Pila()
def titulo(title, tamanio): '''Recibe un string, y un array o lista con el tamaño de la ventana actual. Dibuja en pantalla el titulo pasado por parametro. ''' x, y = tamanio x /= 2 y /= 2 gl.draw_begin() gl.draw_text(title, x, y, 30) gl.draw_end()
def buscar_pistas(pistas, grilla): '''Busca las pistas del backtracking, y las devuelve en una pila''' gamelib.draw_begin() mostrar_interfaz(grilla) gamelib.draw_text('Buscando pista', PIXELES_GIF, PIXELES_GIF // 2, size=12, fill='#00FF00') gamelib.draw_end() pistas = pista.movimientos_pista(grilla) if pistas.esta_vacia(): pistas = None gamelib.say('No hay pistas') return pistas
def dibujar_juego(numero, juego, opcion): ''' Recibe el nivel del juego, el estado del juego y un numero (1,2,3 o 4) y dibuja de acuerdo al número pasado por parámetro. ''' opciones = { 1: '', 2: 'Pista Disponible', 3: 'Pensando....', 4: 'Pista No Disponible' } gamelib.draw_begin() gamelib.title(f'SOKOBAN Level : {numero}') juego_mostrar(juego) #muestra el juego en la ventana gamelib.draw_text(opciones[opcion], 10, 10, fill='yellow', anchor='nw') gamelib.draw_end()
def main(): # Inicializar el estado del juego niveles = archivos.cargar_niveles('niveles.txt') acciones = archivos.cargar_accion_de_tecla('teclas.txt') estados = Pila() pistas = None grilla, nivel = juego_inicializar(niveles) x, y = soko.dimensiones(grilla) gamelib.resize(x * PIXELES_GIF, y * PIXELES_GIF) while gamelib.is_alive(): gamelib.draw_begin() mostrar_interfaz(grilla) if pistas != None: gamelib.draw_text('Pista encontrada', PIXELES_GIF, PIXELES_GIF // 2, size=12, fill='#00FF00') gamelib.draw_end() ev = gamelib.wait(gamelib.EventType.KeyPress) if not ev: break tecla = ev.key accion = procesar_tecla_presionada(tecla, acciones) grilla, estados, pistas = juego_actualizar(grilla, nivel, niveles, accion, estados, pistas) if not grilla: break if soko.juego_ganado(grilla): while not estados.esta_vacia(): estados.desapilar() pistas = None nivel, grilla = juego_pasar_nivel(nivel, niveles) if not grilla: break
def final(tamanio, tiempo): '''Recibe un array o lista con el tamaño de la ventana actual, y un string. Dibuja en pantalla el mensaje final para mostrar al jugador, junto con el tiempo que se pase como parametro ''' x = tamanio[0] / 2 y = tamanio[1] / 2 gl.draw_begin() gl.draw_text("Felicidades!\nPasaste todos los niveles disponibles.", x, y + 20, justify="center") gl.draw_text("GAME OVER", x, y - 50, 40) gl.draw_text(str(tiempo), x, y + 90) gl.draw_text("Presiona una tecla para salir del juego", x, (y * 2) - 15, 7) gl.draw_end()
def main(): gamelib.resize(300, 300) x, y = 150, 80 dx, dy = 5, 5 while gamelib.loop(): for event in gamelib.get_events(): if event.type == gamelib.EventType.KeyPress and event.key == 'q': return gamelib.draw_begin() gamelib.draw_rectangle(x - 10, y - 10, x + 10, y + 10, fill='red') gamelib.draw_end() x += dx y += dy if x > 300 or x < 0: dx *= -1 if y > 300 or y < 0: dy *= -1
def main(): juego = juego_crear() contador = 0 gamelib.resize(300, 350) while gamelib.is_alive(): gamelib.draw_begin() juego_mostrar(juego, contador) gamelib.draw_end() ev = gamelib.wait() if not ev: break if ev.type == gamelib.EventType.KeyPress and ev.key == 'Escape': break if ev.type == gamelib.EventType.ButtonPress: x, y = ev.x, ev.y juego, contador = juego_actualizar(juego, x, y, contador)
def main(): gamelib.title("Pong") W, H = SIZE gamelib.resize(W, H) state = State( paddles=(H / 2, H / 2), ball_pos=(W / 2, H / 2), ball_vel=random_ball_velocity(), score=(0, 0), ) key_pressed = {} while gamelib.loop(): gamelib.draw_begin() draw_paddle(state, PADDLE1) draw_paddle(state, PADDLE2) draw_ball(state) draw_score(state) gamelib.draw_end() for event in gamelib.get_events(): if event.type == gamelib.EventType.KeyPress: key_pressed[event.key] = True if event.type == gamelib.EventType.KeyRelease: key_pressed[event.key] = False if key_pressed.get('q', False): state = move_paddle(state, PADDLE1, -1) if key_pressed.get('a', False): state = move_paddle(state, PADDLE1, +1) if key_pressed.get('Up', False): state = move_paddle(state, PADDLE2, -1) if key_pressed.get('Down', False): state = move_paddle(state, PADDLE2, +1) state = move_ball(state) state = check_goal(state)
def main(): gamelib.resize(chase.ANCHO_INTERFAZ, chase.ALTO_INTERFAZ) gamelib.title("Chase") while gamelib.is_alive(): #Dibujo pantalla de inicio gamelib.draw_begin() chase.dibujar_pantalla_de_inicio() gamelib.draw_end() # Esperamos hasta que ocurra un evento ev = gamelib.wait() if not ev: #El usuario cerró la ventana. break if ev.type == gamelib.EventType.KeyPress and ev.key == 'Escape': # El usuario presionó la tecla Escape, cerrar la aplicación. break if ev.type == gamelib.EventType.ButtonPress: # El usuario presionó un botón del mouse x, y = ev.x, ev.y # averiguamos la posición donde se hizo click if (x >= ((ANCHO_INTERFAZ//2)-150) and x <= (((ANCHO_INTERFAZ//2)-MARGEN_SUPERIOR)+MARGEN_SUPERIOR*2)) and (y >= (ALTO_INTERFAZ - ALTO_INTERFAZ//5) and y <= ((ALTO_INTERFAZ - ALTO_INTERFAZ//5)+100)): #Creo un un nuevo juego. juego = chase.crear_juego() chase.agregar_robots(juego) while gamelib.loop(fps=30): for event in gamelib.get_events(): if not chase.terminado(juego): ev = gamelib.wait() if ev.type == gamelib.EventType.ButtonPress: x, y = ev.x, ev.y if (x >= 0 and x <= ANCHO_INTERFAZ) and (y >= MARGEN_SUPERIOR and y <= ALTO_INTERFAZ): jugador, robots, tablero, puntaje = juego juego = chase.trasladar_jugador(juego, x, y) juego = chase.avanzar(juego) elif (x >= 100 and x <= 2 * MARGEN_SUPERIOR) and (y >= ((MARGEN_SUPERIOR/2)/2) and y <= (MARGEN_SUPERIOR/2)/2+75): juego = chase.teletransportar_jugador(juego) gamelib.draw_begin() chase.dibujar_juego(juego) gamelib.draw_end() if chase.terminado(juego): gamelib.draw_begin() chase.dibujar_game_over() gamelib.draw_end() ev = gamelib.wait() if ev.type == gamelib.EventType.ButtonPress: # El usuario presionó un botón del mouse x, y = ev.x, ev.y #Verifico si el usuario quiere volver a jugar if (x >= (ANCHO_INTERFAZ//2-150) and x <= ((ANCHO_INTERFAZ//2-150)+200)) and (y >= (ALTO_INTERFAZ//2+50) and y <= ((ALTO_INTERFAZ//2+50)+75)): juego = chase.crear_juego() chase.agregar_robots(juego)
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 main(): # Inicializar el estado del juego gamelib.resize(400, 450) pieza = tetris.generar_pieza() juego = tetris.crear_juego(pieza) pieza_i = tetris.generar_pieza() timer_bajar = ESPERA_DESCENDER while gamelib.loop(fps=10): gamelib.draw_begin() gamelib.draw_text("SIGUIENTE PIEZA: ", 300, 20) gamelib.draw_text("PUNTAJE:", 275, 300) #lineas verticales for i in range(1, 10): gamelib.draw_line(TAMANOCELDA * i, 0, TAMANOCELDA * i, ALTOTABLERO) #lineas horizontales for i in range(1, tetris.ALTO_JUEGO): gamelib.draw_line(0, TAMANOCELDA * i, ANCHOTABLERO, TAMANOCELDA * i) # Dibujar la pantalla gamelib.draw_end() for event in gamelib.get_events(): if not event: break if event.type == gamelib.EventType.KeyPress: tecla = event.key dicteclas = tetris.pasar_a_diccionario("teclas.txt") a = dicteclas.get(tecla, None) if a == "ROTAR": juego = tetris.rotar(juego) if a == "DESCENDER": juego, _ = tetris.avanzar(juego, pieza_i) if _: pieza_i = tetris.generar_pieza() if a == "IZQUIERDA": juego = tetris.mover(juego, tetris.IZQUIERDA) if a == "DERECHA": juego = tetris.mover(juego, tetris.DERECHA) if a == "GUARDAR": juego = tetris.guardar_partida(juego, "partida.txt") if a == "CARGAR": juego = tetris.cargar_partida("partida.txt") if a == "SALIR": return # Actualizar el juego, según la tecla presionada timer_bajar -= 1 if timer_bajar == 0: juego, _ = tetris.avanzar(juego, pieza_i) if _: pieza_i = tetris.generar_pieza() timer_bajar = ESPERA_DESCENDER # Descender la pieza automáticamente if tetris.terminado(juego): pieza, superficie, puntuacion = juego gamelib.draw_text("PERDISTE", 175, 80, size=40) nombre = gamelib.input("ingrese su nombre") listapuntuaciones = procesarpuntuaciones("puntuaciones.txt") listapuntuaciones.append((nombre, int(puntuacion))) lista = ordenarseleccionpuntuaciones(listapuntuaciones) lista.reverse( ) #la damos vuelta porque esta ordenada de menor a mayor y queremos que el archivo empieze leyendo de mayor a menor if len(lista) > 10: lista = lista[:10] subirpuntuaciones("puntuaciones.txt", lista) break mostrar_juego(juego) dibujar_siguiente(pieza_i)
def main(): # Inicializar el estado del juego nivel_inicial = 1 dic_niveles_grilla = leer_niveles("niveles.txt") grilla = dic_niveles_grilla[nivel_inicial] tablero_mov = PilaMovimiento() cola_pista = ColaPista() tamaño = cargar_tamaño(grilla) x, y = tamaño cont_indices = 0 if x > 300 or y > 300: gamelib.resize( x * 5, y * 5 ) # Agrando la pantalla en base a gamelib(300 px) dividido la cant de px que tengo por celda (60px) = 5 else: gamelib.resize(300, 300) while gamelib.is_alive(): gamelib.draw_begin() # Dibujar la pantalla dibujo_juego(grilla) gamelib.draw_end() ev = gamelib.wait(gamelib.EventType.KeyPress) if not ev: break tecla = ev.key # Actualizar el estado del juego, según la `tecla` presionada if ev.type == gamelib.EventType.KeyPress and tecla == 'Escape': # El usuario presionó la tecla Escape, cerrar la aplicación. break if ev.type == gamelib.EventType.KeyPress and tecla == 'w': # El usuario presiono la tecla w, mover hacia arriba. grilla = soko.mover(grilla, coordenadas_teclas('w', grilla)) grilla, nivel_inicial = pasar_nivel(grilla, dic_niveles_grilla, nivel_inicial) tablero_mov.apilar(grilla) if ev.type == gamelib.EventType.KeyPress and tecla == 's': # El usuario presiono la tecla s, mover hacia abajo grilla = soko.mover(grilla, coordenadas_teclas('s', grilla)) grilla, nivel_inicial = pasar_nivel(grilla, dic_niveles_grilla, nivel_inicial) tablero_mov.apilar(grilla) if ev.type == gamelib.EventType.KeyPress and tecla == 'd': # El usuario presiono la tecla d, mover hacia la derecha grilla = soko.mover(grilla, coordenadas_teclas('d', grilla)) grilla, nivel_inicial = pasar_nivel(grilla, dic_niveles_grilla, nivel_inicial) tablero_mov.apilar(grilla) if ev.type == gamelib.EventType.KeyPress and tecla == 'a': #El usuario presiono la tecla a, mover hacia la izquierda grilla = soko.mover(grilla, coordenadas_teclas('a', grilla)) grilla, nivel_inicial = pasar_nivel(grilla, dic_niveles_grilla, nivel_inicial) tablero_mov.apilar(grilla) if ev.type == gamelib.EventType.KeyPress and tecla == 'r': #El usuario presiono la tecla r, reiniciar la posicion grilla = dic_niveles_grilla[nivel_inicial] tablero_mov.apilar(grilla) if ev.type == gamelib.EventType.KeyPress and tecla == 'u': #El usuario presiono la tecla u, deshacer la posicion if tablero_mov.esta_vacia(): grilla = dic_niveles_grilla[nivel_inicial] else: grilla = tablero_mov.desapilar() if ev.type == gamelib.EventType.KeyPress and tecla == 'c': #El usuario presiono la tecla c, dar pista if not cola_pista.esta_vacia(): mov = cola_pista.desencolar() grilla = soko.mover(grilla, mov) grilla, nivel_inicial = pasar_nivel(grilla, dic_niveles_grilla, nivel_inicial) else: pista, movs = buscar_solucion( dic_niveles_grilla[nivel_inicial], nivel_inicial) for mov in movs[::-1]: cola_pista.encolar(mov)
def main(): # Inicializar el estado del juego gamelib.resize(RES, RES) teclas = tetris.cargar_teclas(RUTA_TECLAS_CONFIG) piezas = tetris.cargar_piezas(RUTA_PIEZAS) siguiente_pieza = tetris.generar_pieza(piezas) juego = tetris.crear_juego(tetris.generar_pieza(piezas)) tabla_record = tetris.mostrar_tabla_records(RUTA_PUNTUAJES) juego_terminado = False puntuaje = 0 salir = False timer_bajar = ESPERA_DESCENDER while gamelib.loop(fps=30) and not salir: gamelib.draw_begin() # Dibujar la pantalla dibujar_grilla(juego) dibujar_pieza(juego) dibujar_siguiente(juego, siguiente_pieza) dibujar_superficie(juego) dibujar_puntuaje(juego, puntuaje) if juego_terminado: dibujar_game_over(tabla_record) anotar = tetris.es_record(puntuaje, tabla_record) if anotar: nombre = gamelib.input("Ingresar nombre: ") tetris.guardar_puntuaje(RUTA_PUNTUAJES, nombre, int(puntuaje)) dibujar_game_over(tabla_record) break gamelib.draw_end() for event in gamelib.get_events(): if not event: break if event.type == gamelib.EventType.KeyPress: tecla = event.key # Actualizar el juego, según la tecla presionada if tecla in teclas: if teclas[tecla] == "IZQUIERDA": juego = tetris.mover(juego, -1) elif teclas[tecla] == "DERECHA": juego = tetris.mover(juego, 1) elif teclas[tecla] == "DESCENDER": timer_bajar = 1 elif teclas[tecla] == "SALIR": salir = True elif teclas[tecla] == "ROTAR": juego = tetris.rotar(juego, piezas) elif teclas[tecla] == "GUARDAR": tetris.guardar_partida( RUTA_PARTIDA, juego, puntuaje, siguiente_pieza ) elif teclas[tecla] == "CARGAR": partida = tetris.cargar_partida(RUTA_PARTIDA) juego = partida["juego"] siguiente_pieza = partida["siguiente_pieza"] puntuaje = partida["puntuaje"] if not tetris.terminado(juego) and not juego_terminado: timer_bajar -= 1 if timer_bajar == 0: timer_bajar = ESPERA_DESCENDER puntuaje += 0.3 # Descender la pieza automáticamente juego, prox = tetris.avanzar(juego, siguiente_pieza) if prox: siguiente_pieza = tetris.generar_pieza(piezas) else: juego_terminado = True
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(): ''' Funcion principal del juego. Mantiene la interfaz grafica y evalua las teclas recibidas y si el juego esta terminado ''' # Inicializar el estado del juego tetris.importar_piezas(tetris.RUTA_PIEZAS) juego = tetris.crear_juego(tetris.generar_pieza()) salir = False puntaje_juego = 0 ingreso_puntaje = False cambiar_ficha = False siguiente_ficha = tetris.generar_pieza() gamelib.resize(grafico.ANCHO_PANT, grafico.ALTO_PANT) gamelib.play_sound("sound/bradinsky.wav") teclas = importar_teclas(tetris.RUTA_TECLAS) timer_bajar = ESPERA_DESCENDER while gamelib.loop(fps=30): gamelib.draw_begin() gamelib.title("TETRIS") # Dibujar la pantalla grafico.tablero(puntaje_juego) grafico.piezas(juego, siguiente_ficha) if salir: break if tetris.terminado(juego): grafico.terminado() if not ingreso_puntaje: leaderboard = tetris.cargar_leaderboard() leaderboard, ingreso_puntaje = grafico.top_puntajes( leaderboard, puntaje_juego) grafico.imprimir_puntajes(leaderboard) gamelib.draw_end() for event in gamelib.get_events(): if not event: break if event.type == gamelib.EventType.KeyPress: tecla = event.key # Actualizar el juego, según la tecla presionada ( ROTAR ( w) , MOVER izq der abajo, guardar, cargar ) juego = actualizar_movimiento(juego, tecla, teclas) if tecla in teclas["GUARDAR"]: tetris.guardar_partida(juego, siguiente_ficha, puntaje_juego) if tecla in teclas["CARGAR"]: juego, siguiente_ficha, puntaje_juego = tetris.cargar_partida( ) if tecla in teclas["DESCENDER"]: juego, cambiar_ficha = tetris.avanzar( juego, siguiente_ficha) puntaje_juego += 1 continue if tecla in teclas["SALIR"]: salir = True timer_bajar -= 1 if timer_bajar == 0: timer_bajar = ESPERA_DESCENDER # Descender la pieza automáticamente if cambiar_ficha == True: siguiente_ficha = tetris.generar_pieza() juego, cambiar_ficha = tetris.avanzar(juego, siguiente_ficha) if not tetris.terminado(juego): puntaje_juego += 1