コード例 #1
0
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()
コード例 #2
0
ファイル: main.py プロジェクト: DarthValar19/Tetris
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
コード例 #3
0
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)
コード例 #4
0
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
コード例 #5
0
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)
コード例 #6
0
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
コード例 #7
0
ファイル: main.py プロジェクト: juanpescie/tetris-sencillo
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)
コード例 #8
0
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)
コード例 #9
0
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
コード例 #10
0
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