Python Forum

Full Version: Pygame Tutorials Part 3 Image Handling
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I've recently started the Tutorials and am picking up some great tips. However, I'm getting an error message with the keys event:

Error:
Traceback (most recent call last): File "/data/user/0/ru.iiec.pydroid3/files/temp_iiec_codefile.py", line 34, in <module> player.update(keys) ^^^^
NameError: name 'keys' is not defined

Can you advise how I fix this?

Full code:

import pygame as pg
   
pg.init()
   
class Player:
    def __init__(self, screen_rect):
        self.image = pg.image.load('spaceship.png').convert()
        self.image.set_colorkey((255,0,255))
        self.transformed_image = pg.transform.rotate(self.image, 180)
        self.rect = self.image.get_rect(center=screen_rect.center)
        self.speed = 5
          
    def update(self, keys):
        if keys[pg.K_LEFT]:
            self.rect.x -= self.speed
        elif keys[pg.K_RIGHT]:
            self.rect.x += self.speed
           
    def draw(self, surf):
        surf.blit(self.transformed_image, self.rect)
   
screen = pg.display.set_mode((800,600))
screen_rect = screen.get_rect()
player = Player(screen_rect)
clock = pg.time.Clock()
done = False
while not done:
    screen.fill((0,0,0))
    keys = pg.key.get_pressed()
    for event in pg.event.get(): 
        if event.type == pg.QUIT:
            done = True
    player.update(keys)
    player.draw(screen)
    pg.display.update()
    clock.tick(60)
Thanks and sorry if I've done anything wrong in this post.
Thanks Larz60 for doing that for me.

The full Traceback error was:

Error:
Traceback (most recent call last): File "/data/user/0/ru.iiec.pydroid3/files/temp_iiec_codefile.py", line 34, in <module> player.update(keys) ^^^^ NameError: name 'keys' is not defined
As I've recently started the tutorial this is the only error (so far!). No doubt I'll get more as I progress.
put a print statement after:
keys = pg.key.get_pressed()
print(f'keys: {keys}')
is keys populated?
Thanks again Larz60+

Error message has gone.