K_UP is not defined

1

I have a problem with the following lines:

keys = pygame.key.get_pressed()

if keys[K_LEFT]:

When I run the code it gives me an error that says:

File "HardGame1.1.0.py", line 49, in <module>
    if evento_tecla[K_UP]:
NameError: name 'K_UP' is not defined

and I do not understand why it says it is not defined.

Here the code:

import pygame

pygame.init()

ventana = pygame.display.set_mode((640, 640))

class jugador(pygame.sprite.Sprite):

    def __init__(self):

        pygame.sprite.Sprite.__init__(self) 


        self.image = pygame.image.load('cuadradito.png')
        self.rect = self.image.get_rect()

        self.vel = 2




    def move(self):

        if self.rect.left <= 0:
            self.rect.left = 0

        elif self.rect.right >= 640:
            self.rect.right = 640                   


Player = jugador()

while True:

    Player.move()

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

    keys = pygame.key.get_pressed()

    if keys[K_LEFT]:
        Player.rect.top = Player.rect.top =- Player.vel
    
asked by ElAlien123 14.02.2018 в 02:02
source

1 answer

0

The cause of the error is because you do not have the necessary namespace added to use the key constants. These constants (and others used by PyGame) are automatically exposed in the namespace pygame , that is, if you import using import pygame you should do:

keys[pygame.K_UP]

Another option is to use the module pygame.locals :

from pygame.locals import *

keys[K_UP]

An example based on your code would be:

import sys
import pygame
from pygame.locals import *


class Jugador(pygame.sprite.Sprite):
    def __init__(self):
        super(Jugador, self).__init__() 
        self.image = pygame.image.load('cuadradito.png')
        self.rect = self.image.get_rect()
        self.vel = 2


    def update(self):
        keys = pygame.key.get_pressed() 

        if keys[K_LEFT]: 
           self.rect.x -= self.vel 
           if self.rect.left <= 0:
               self.rect.left = 0

        if keys[K_RIGHT]: 
           self.rect.x += self.vel 
           if self.rect.right >= 640:
               self.rect.right = 640

    def draw(self, screen):
        screen.blit(self.image, self.rect)

pygame.init()
ventana = pygame.display.set_mode((640, 640))
player = Jugador()
clock = pygame.time.Clock()


while True:
    for event in pygame.event.get():
        if event.type == QUIT:
           pygame.quit()
           sys.exit()

    player.update()
    ventana.fill((0,0,0))
    player.draw(ventana)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
    
answered by 16.02.2018 / 00:03
source