1

lo que pasa es que vi este codigo y le estuve trabajando un tiempo ,pero cuando intento cambiar KEYDOWN A K_o me sale un error de que que key no esta definido me pueden decir porque no lo puedo cambiar o como lo cambio?

import os
import pygame, random, sys
from pygame.locals import *

ANCHOVENTANA =800
ALTOVENTANA = 600
COLORVENTANA = (255,255,255)
COLORFONDO2 = (255,255,255)
COLORFONDO = pygame.image.load('COLORFONDO1.png')
COLORFONDO22 = pygame.image.load('COLORFONDO2.PNG')
COLORFONDO3 = pygame.image.load('COLORFONDO3.PNG')
COLORFONDO4 = pygame.image.load('COLORFONDO4.PNG')
COLORFONDO5 = pygame.image.load('COLORFONDO5.PNG')
COLORFONDO6 = pygame.image.load('COLORFONDO6.PNG')

FPS = 120
TAMAÑOMINVILLANO = 20
TAMAÑOMAXVILLANO = 40
VELOCIDADMINVILLANO = 1
VELOCIDADMAXVILLANO = 8
TASANUEVOVILLANO = 10
#segunda lista ded villanos
TAMAÑOMINVILLANO2 = 20
TAMAÑOMAXVILLANO2 = 40
VELOCIDADMINVILLANO2 = 1
VELOCIDADMAXVILLANO2 = 8
TASANUEVOVILLANO2 = 10

TASAMOVIMIENTOJUGADOR = 10
pantalla=pygame.display.set_mode((800,600))

def terminar():
    pygame.quit()
    sys.exit()

def esperarTeclaJugador():
    while True:
        for evento in pygame.event.get():
            if evento.type == QUIT:
                terminar()
            if evento.type == KEYDOWN:####################################
                if evento.key == K_ESCAPE: # Sale del juego al presionar ESCAPE
                    terminar()
                return

def jugadorGolpeaVillano(rectanguloJugador, villanos):
    for v in villanos:
        if rectanguloJugador.colliderect(v['rect']):
            return True
    return False
def jugadorGolpeaVillano(rectanguloJugador, villanos2):
    for v in villanos2:
        if rectanguloJugador.colliderect(v['rect']):
            return True
    return False


def dibujarTexto(texto, fuente, superficie, x, y):
    objetotexto = fuente.render(texto, 1, COLORVENTANA)
    rectangulotexto = objetotexto .get_rect()
    rectangulotexto.topleft = (x, y)
    superficie.blit(objetotexto, rectangulotexto)

 # establece un pygame, la ventana y el cursor del ratón
pygame.init()
relojPrincipal = pygame.time.Clock()
superficieVentana = pygame.display.set_mode((ANCHOVENTANA, ALTOVENTANA))
pygame.display.set_caption('ARHRI')
pygame.mouse.set_visible(False)
 #pongo un icono
icono = pygame.image.load("icono.png")
pygame.display.set_icon(icono)
 # establece las fuentes
fuente = pygame.font.SysFont(None, 48)

# establece los sonidos
sonidoJuegoTerminado = pygame.mixer.Sound('sonido.wav')
pygame.mixer.music.load('sonidofondo.wav')

 # establece las imagenes
imagenJugador = pygame.image.load('nave.png')

rectanguloJugador = imagenJugador.get_rect()
imagenJugador2 = pygame.image.load('nave.png')

rectanguloJugador2 = imagenJugador.get_rect()

imagenVillano = pygame.image.load('asteroide2.png')
imagenVillano2 = pygame.image.load('asteroide1.png')

 # Muestra la pantalla inicial

dibujarTexto('ARHRI', fuente, superficieVentana, (ANCHOVENTANA / 3)+40, (ALTOVENTANA / 3))
dibujarTexto('Presione una tecla para comenzar.', fuente, superficieVentana, (ANCHOVENTANA / 3) - 180, (ALTOVENTANA / 3) + 50)
dibujarTexto('Presione "w" para moverce hacia arriba.', fuente, superficieVentana, (ANCHOVENTANA / 3) - 200, (ALTOVENTANA / 3) + 80)
dibujarTexto('Presione "S" para moverce hacia abajo.', fuente, superficieVentana, (ANCHOVENTANA / 3) - 200, (ALTOVENTANA / 3) + 110)
dibujarTexto('Presione "A" para moverce hacia la izquierda.', fuente, superficieVentana, (ANCHOVENTANA / 3) - 200, (ALTOVENTANA / 3) + 135)
dibujarTexto('Presione "D" para moverce hacia la derecha.', fuente, superficieVentana, (ANCHOVENTANA / 3) - 200, (ALTOVENTANA / 3) + 165)

pygame.display.update()
esperarTeclaJugador()#########################


puntajeMax = 0
while True:
     # establece el comienzo del juego
     villanos = []
     villanos2 = []
     puntaje = 0
     #pongo el disparo y no lo muestro
     imagenDisparo = pygame.image.load("disparo.png")    
     rectanguloDisparo = imagenDisparo.get_rect()        
     disparoActivo = False
     rectanguloVillano = imagenVillano.get_rect()
     asteroideVisible = True
     rectanguloVillano = imagenVillano2.get_rect()
     asteroideVisible2 = True
     rectanguloJugador.topleft = (ANCHOVENTANA / 2, ALTOVENTANA  -100)
     moverIzquierda = moverDerecha = moverArriba = moverAbajo = False
     trucoReversa = trucoLento = False
     contadorAgregarVillano = 0
     contadorAgregarVillano2 = 0
     pygame.mixer.music.play(-1, 0.0)
     while True: # el ciclo del juego se mantiene mientras se este jugando
         puntaje += 1 # incrementa el puntaje

         for evento in pygame.event.get():
             if evento.type == QUIT:
                 terminar()

             if evento.type == KEYDOWN:#########################
                 if evento.key == ord('z'):
                     trucoReversa = True
                     superficieVentana.blit(imagenJugador, rectanguloJugador)
                 if evento.key == ord('x'):
                     trucoLento = True
                 if evento.key == K_LEFT or evento.key == ord('a'):
                     moverDerecha = False
                     moverIzquierda = True
                     superficieVentana.blit(imagenJugador2, rectanguloJugador2)
                 if evento.key == K_RIGHT or evento.key == ord('d'):
                     moverIzquierda = False
                     moverDerecha = True
                 if evento.key == K_UP or evento.key == ord('w'):
                     moverAbajo = False
                     moverArriba = True
                 if evento.key == K_DOWN or evento.key == ord('s'):
                     moverArriba = False
                     moverAbajo = True
                    #disparos... 
                 keys = pygame.key.get_pressed()
                 if keys[K_LSUPER]  and not disparoActivo:         
                    disparoActivo = True                        
                    rectanguloDisparo.left = rectanguloJugador.left + 18  
                    rectanguloDisparo.top = rectanguloJugador.top  -25



             if evento.type == KEYUP:
                 if evento.key == ord('z'):
                     trucoReversa = False
                     puntaje = 0
                 if evento.key == ord('x'):
                     trucoLento = False
                     puntaje = 0
                 if evento.key == K_ESCAPE:
                    terminar()

                 if evento.key == K_LEFT or evento.key == ord('a'):
                     moverIzquierda = False
                 if evento.key == K_RIGHT or evento.key == ord('d'):
                     moverDerecha = False
                 if evento.key == K_UP or evento.key == ord('w'):
                     moverArriba = False
                 if evento.key == K_DOWN or evento.key == ord('s'):
                     moverAbajo = False




             if evento.type == MOUSEMOTION:
                 # Si se mueve el ratón, este se mueve al lugar donde esté el cursor.
                 rectanguloJugador.move_ip(evento.pos[0] - rectanguloJugador.centerx, evento.pos[1] - rectanguloJugador.centery)

         # Añade villanos en la parte superior de la pantalla, de ser necesarios.
         if not trucoReversa and not trucoLento:
             contadorAgregarVillano += 1



         if contadorAgregarVillano == TASANUEVOVILLANO:
             contadorAgregarVillano = 0
             tamañoVillano = random.randint(TAMAÑOMINVILLANO, TAMAÑOMAXVILLANO)

             nuevoVillano = {'rect': pygame.Rect(random.randint(0, ANCHOVENTANA-tamañoVillano), 0 - tamañoVillano, tamañoVillano, tamañoVillano),
                         'velocidad': random.randint(VELOCIDADMINVILLANO, VELOCIDADMAXVILLANO),
                         'superficie':pygame.transform.scale(imagenVillano, (tamañoVillano, tamañoVillano)),
                         }

             villanos.append(nuevoVillano)

         if not trucoReversa and not trucoLento:
             contadorAgregarVillano2 += 1

         if contadorAgregarVillano2 == TASANUEVOVILLANO2:
                 contadorAgregarVillano2 = 0
                 tamañoVillano2 = random.randint(TAMAÑOMINVILLANO2, TAMAÑOMAXVILLANO2)

                 nuevoVillano2 = {'rect': pygame.Rect(random.randint(0, ANCHOVENTANA-tamañoVillano2), 0 - tamañoVillano2, tamañoVillano2, tamañoVillano2),
                             'velocidad': random.randint(VELOCIDADMINVILLANO2, VELOCIDADMAXVILLANO2),
                             'superficie':pygame.transform.scale(imagenVillano2, (tamañoVillano2, tamañoVillano2)),
                             }

                 villanos2.append(nuevoVillano2)

         # Mueve el jugador.
         if moverIzquierda and rectanguloJugador.left > 0:
             rectanguloJugador.move_ip(-1 * TASAMOVIMIENTOJUGADOR, 0)
         if moverDerecha and rectanguloJugador.right < ANCHOVENTANA:
             rectanguloJugador.move_ip(TASAMOVIMIENTOJUGADOR, 0)
         if moverArriba and rectanguloJugador.top > 0:
             rectanguloJugador.move_ip(0, -1 * TASAMOVIMIENTOJUGADOR)
         if moverAbajo and rectanguloJugador.bottom < ALTOVENTANA:
             rectanguloJugador.move_ip(0, TASAMOVIMIENTOJUGADOR)


         # Mueve el cursor del ratón hacia el jugador.
         pygame.mouse.set_pos(rectanguloJugador.centerx, rectanguloJugador.centery)

         # Mueve los villanos hacia abajode 2 segunda lista.
         for v2 in villanos2:


             if not trucoReversa and not trucoLento:
                 v2['rect'].move_ip(-2, v2['velocidad'])
             elif trucoReversa:
                 v2['rect'].move_ip(0, 4)
             elif trucoLento:
                 v2['rect'].move_ip(0, 1)

         # Mueve los villanos hacia abajode l segunda lista.
         for v in villanos:


             if not trucoReversa and not trucoLento:
                 v['rect'].move_ip(0, v['velocidad'])
             elif trucoReversa:
                 v['rect'].move_ip(0, -5)
             elif trucoLento:
                 v['rect'].move_ip(0, 1)



             if puntaje >= 100:
                 v['rect'].move_ip(0, 1.5)
                 TASANUEVOVILLANO = 9
             elif trucoReversa:
                 v['rect'].move_ip(0, -5)
             elif trucoLento:
                 v['rect'].move_ip(0, 1)




             if puntaje >= 200:
                 v['rect'].move_ip(0, 3)
                 TASANUEVOVILLANO = 7
             elif trucoReversa:
                 v['rect'].move_ip(0, -5)
             elif trucoLento:
                 v['rect'].move_ip(0, 1)


             if puntaje >= 300:
                 v['rect'].move_ip(0, 4)
                 TASANUEVOVILLANO = 6
             elif trucoReversa:
                 v['rect'].move_ip(0, -5)
             elif trucoLento:
                 v['rect'].move_ip(0, 1)

             if puntaje >= 400:
                 v['rect'].move_ip(0, 5)
                 TASANUEVOVILLANO = 5

             elif trucoReversa:
                 v['rect'].move_ip(0, -5)
             elif trucoLento:
                 v['rect'].move_ip(0, 1)


             if puntaje >= 1000:
                 v['rect'].move_ip(-2, 4)
                 TASANUEVOVILLANO = 3

             elif trucoReversa:
                 v['rect'].move_ip(0, -5)
             elif trucoLento:
                 v['rect'].move_ip(0, 1)





         # Elimina los villanos que han caido por debajo.
         for v in villanos[:]:
             if v['rect'].top > ALTOVENTANA:
                 villanos.remove(v)
         for v in villanos2[:]:
             if v['rect'].top > ALTOVENTANA:
                 villanos2.remove(v)



         # Dibuja el mundo del juego en la ventana.


         pantalla.blit(COLORFONDO,(0,0))
         if puntaje >= 200 and puntaje <=401:
            pantalla.blit(COLORFONDO22,(0,0))





         if puntaje >= 400 and puntaje <=601:
            pantalla.blit(COLORFONDO3,(0,0))





         if puntaje >= 600 and puntaje <=801:
            pantalla.blit(COLORFONDO4,(0,0))



         if puntaje >= 800 and puntaje <=1001:
            pantalla.blit(COLORFONDO5,(0,0))

         if puntaje >= 1000:
            pantalla.blit(COLORFONDO6,(0,0))


         if disparoActivo:
            rectanguloDisparo.top -= 50
            if rectanguloDisparo.top <= 0:
                disparoActivo = False




         # Dibuja el puntaje y el puntaje máximo
         dibujarTexto('Puntaje: %s' % (puntaje), fuente, superficieVentana, 10, 0)
         dibujarTexto('Puntaje Máximo: %s' % (puntajeMax), fuente, superficieVentana, 10, 40)
         dibujarTexto('Esquiva los asteroides.', fuente, superficieVentana, (ANCHOVENTANA / 3) - 50, (ALTOVENTANA / 3) - 90)

         # Dibuja el rectángulo del jugador y los disparos



         for v in villanos:
             if disparoActivo:                                        
                if rectanguloDisparo.colliderect(v['rect']):       
                        asteroideVisible = False                      
                        villanos.remove(v)                         


         if  not asteroideVisible:            
            terminado = True

         for v in villanos2:
             if disparoActivo:                                        
                if rectanguloDisparo.colliderect(v['rect']):       
                        asteroideVisible2 = False                      
                        villanos2.remove(v)                         



         superficieVentana.blit(imagenJugador, rectanguloJugador)
         if disparoActivo == True:                      
             pantalla.blit(imagenDisparo, rectanguloDisparo)  

         # Dibuja cada villano y lo elimino si es nesesario
         for v in villanos:
             superficieVentana.blit(v['superficie'], v['rect'])
         for v in villanos:
             if asteroideVisible:
                 superficieVentana.blit(v['superficie'], v['rect'])
         pygame.display.update()
         for v in villanos2:
             superficieVentana.blit(v['superficie'], v['rect'])
         for v in villanos2:
             if asteroideVisible2:
                 superficieVentana.blit(v['superficie'], v['rect'])


         pygame.display.update()

         # Verifica si algún villano impactó en el jugador.
         if jugadorGolpeaVillano(rectanguloJugador, villanos):
             if puntaje > puntajeMax:
                 puntajeMax = puntaje # Establece nuevo puntaje máximo
             break
         if jugadorGolpeaVillano(rectanguloJugador, villanos2):
             if puntaje > puntajeMax:
                 puntajeMax = puntaje # Establece nuevo puntaje máximo
             break

         relojPrincipal.tick(FPS)

     # Detiene el juego y muestra "Juego Terminado"
     pygame.mixer.music.stop()
     sonidoJuegoTerminado.play()

     dibujarTexto('Juego Terminado', fuente, superficieVentana, (ANCHOVENTANA / 3), (ALTOVENTANA / 3))
     dibujarTexto('Presione una tecla jugar de nuevo.', fuente, superficieVentana, (ANCHOVENTANA / 3) - 80, (ALTOVENTANA / 3) + 50)
     dibujarTexto('o presione esc para salir.', fuente, superficieVentana, (ANCHOVENTANA / 3) - 80, (ALTOVENTANA / 3) + 80)
     pygame.display.update()
     esperarTeclaJugador()

     sonidoJuegoTerminado.stop()
8
  • Hola Andrés deberías explicar cual es la intención de hacer eso. K_o no es un evento, es una constante. KEYUP, KEYDOWN, etc si son tipos de eventos de teclado.... un evento de tipo KEYDOWN es lanzado cuando una tecla es pulsada, luego tu puedes ver si esa tecla es la o y actuar en consecuencia....
    – FJSevilla
    el 26 sep. 2017 a las 21:26
  • si,pero puedo cambiarlo para que solo funcione con la "o"? o otra letra pero solo esa letra? el 27 sep. 2017 a las 14:18
  • Andrés ¿te refieres a que cuando se pide presionar una tecla cualquiera para continuar o "esc" para salir solo responda a la "o". ¿Que solo se continue si se pulsa la "o" y se salga si se pulsa "Esc" y no responda a cualquier otra letra?
    – FJSevilla
    el 27 sep. 2017 a las 15:07
  • si,si segun la tecla que yo elija se ejecute el juego es ente caso la "o" el 28 sep. 2017 a las 11:37
  • en pocas palabras si, puedes ayudarme? el 28 sep. 2017 a las 13:30

1 respuesta 1

0

Si lo que deseas es que la función esperarTeclaJugador solo permita continuar cuando se pulse una tecla específica en vez de cualquier tecla tines que hacer que retorne solo cuando esa tecla es pulsada. Por ejemplo, para que solo se continua si se pulsa la "o" debes hacer algo así:

def esperarTeclaJugador():
    while True:
        for evento in pygame.event.get():
            if evento.type == QUIT:
                terminar()
            if evento.type == KEYDOWN:####################################
                if evento.key == K_ESCAPE: # Sale del juego al presionar ESCAPE
                    terminar()
                elif evento.key == K_o:  # Si la tecla pulsada es la "o"
                    return               # La función retorna dejando de bloquear la ejecución.

Un ejemplo reproducirble simple sería el siguiente:

import sys
import pygame
from pygame.locals import *

def terminar():
    pygame.quit()
    sys.exit()

def esperarTeclaJugador():
    while True:
        for evento in pygame.event.get():
            if evento.type == QUIT:
                terminar()
            if evento.type == KEYDOWN:####################################
                if evento.key == K_ESCAPE: # Sale del juego al presionar ESCAPE
                    terminar()
                elif evento.key == K_o:
                    return

pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
font = pygame.font.SysFont("comicsansms", 50)
text = font.render("Pulse < o > para iniciar o Esc para salir", True, (0, 128, 0))
screen.fill((255, 255, 255))
screen.blit(text, (320 - text.get_width() // 2, 240 - text.get_height() // 2))
pygame.display.update()
esperarTeclaJugador()

done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYDOWN and event.key == pygame.K_e:
            done = True

    text = font.render("Juego iniciado... pulse < e > para salir", True, (255, 255, 0))
    screen.fill((0, 0, 0))
    screen.blit(text, (320 - text.get_width() // 2, 240 - text.get_height() // 2))
    pygame.display.flip()
    clock.tick(60)
1
  • gracias ,me sirvió el 29 sep. 2017 a las 11:56

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.