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:
Can you advise how I fix this?
Full code:
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 definedCan 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.
Larz60+ write Apr-07-2025, 08:17 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Tags have been added for you this time. Please use BBCode tags on future posts.
Also when posting traceback, be sure to include entire, unaltered traceback as it contains useful debugging info.
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Tags have been added for you this time. Please use BBCode tags on future posts.
Also when posting traceback, be sure to include entire, unaltered traceback as it contains useful debugging info.