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 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(): # 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 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 juego_pasar_nivel(nivel, niveles): '''Prosigue al siguiente nivel, devulve None con respecto a la grilla si supera el ultimo nivel''' nivel += 1 if nivel == len(niveles): gamelib.say('Felicidades, compleataste todos los niveles') return nivel, None grilla = juego_crear(nivel, niveles) x, y = soko.dimensiones(grilla) gamelib.resize(x * PIXELES_GIF, y * PIXELES_GIF) return nivel, grilla
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 cambiar_tamanio_ventana(grilla): '''Recibe un nivel en forma de grilla (lista de listas) y ajusta el tamaño de la ventana, acorde a las dimensiones del nivel. Devuelve el tamaño de la ventana en pixeles (x, y)''' x, y = soko.dimensiones(grilla) x *= TAMANIO_CASILLA y *= TAMANIO_CASILLA gl.resize(x, y) return x, y
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 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(): gamelib.title("Game of life") life = life_create([ '..........', '..........', '..........', '.....#....', '......#...', '....###...', '..........', '..........', ]) gamelib.resize(len(life[0]) * CELL_SIZE, len(life) * CELL_SIZE) while gamelib.is_alive(): draw(life) gamelib.wait(gamelib.EventType.KeyPress) life = life_next(life)
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 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(): 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 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
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 resize(juego): ancho, largo = soko.dimensiones(juego) gamelib.resize(ancho*TAMAÑO_IMAGEN, largo*TAMAÑO_IMAGEN)
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(): # 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(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(): 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(): # 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 = []