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 saying:
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 that 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
The cause of the error is because you don't have the necessary namespace added to use the key constants. These constants (and others used by PyGame) are automatically exposed in the namespace
pygame
, i.e. if you import viaimport pygame
you should do:Another option is to use the module
pygame.locals
:An example based on your code would be: