I ran the code that you've pasted above and it works fine here, but I'm wondering if you have got the "update" method indented correctly within the spaceship class.
it should be:
#create spaceship class
class Spaceship(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("img/spaceship.png") # load image
self.rect = self.image.get_rect() # force image to rectangle
self.rect.center = [x, y]
def update(self):
# set movement speed
speed = 8
# get key press
key = pygame.key.get_pressed()
if key[pygame.K_LEFT] and self.rect.left > 0:
print('Move Left')
self.rect.x -= speed
if key[pygame.K_RIGHT] and self.rect.right < screen_width:
self.rect.x += speed
This ensures the update method is part of that class rather than a method on its own.
Also, if you want to troubleshoot and check whether something is working as it should, you can print it. In the code above I've put a print statement which will say 'Move Left' when the conditions are met. It's a quick way to see what's going on and where the problems might be. Of course you'll want to remove that once you get it working :)