Search code examples
pythonimagepygameattributesattributeerror

Getting error when trying to add a image to my snake game


I have an error in my code, the error message is:

line 195 line 127 'str' object has no attribute ' get_rect'

but I can't see what's wrong.


img = 'banana-hi.png'

class Snake():
    def __init__(self):
        self.alive = True
        self.length = 1
        self.tail = []
        self.x = 0
        self.y = 0
        self.xV = 0
        self.yV = 1
        self.tick = 0
    
    def draw(self):
        for section in self.tail:
            pygame.draw.rect(screen,WHITE,(((section[0]) * scale),((section[1]) * scale) + 100,scale,scale))
    
    def update(self):
        if self.alive == True:
            if self.tick == 10:
                self.x += self.xV
                self.y += self.yV
                for segment in self.tail:
                    if segment[0] == self.x and segment[1] == self.y:
                        self.alive = False
                self.tick = 0
                self.tail.append((self.x,self.y))
            else:
                self.tick += 1
            while len(self.tail) > self.length:
                self.tail.pop(0)
        if self.x == -1:
            self.alive = False
            self.x = 0
        if self.x == (size[0] / scale):
            self.alive = False
            self.x = (size[0] / scale) - 1
        if self.y == -1:
            self.alive = False
            self.y = 0
        if self.y == (size[1] - 100) / scale:
            self.alive = False
            self.y = ((size[1] - 100) / scale) - 1
    
    def reset(self):
        self.alive = True
        self.length = 1
        self.tail.clear()
        self.x = 0
        self.y = 0
        self.xV = 0
        self.yV = 1
        self.tick = 0

class Food(pygame.sprite.Sprite):
    def __init__(self,img):
        pygame.sprite.Sprite.__init__(self)
        self.image = img
        self.rect = self.image.get_rect()
        self.x = random.randrange((size[0] / scale) - 1)
        self.y = random.randrange(((size[1] - 100) / scale) - 1)
        
    
    def draw(self):
        pygame.draw.self.rect(screen,GREEN,((self.x * scale),(self.y * scale) + 100,scale,scale))
    
    def update(self):
        if snake.x == self.x and snake.y == self.y:
            self.reset()
            snake.length += 1
    
    def reset(self):
        self.x = random.randrange((size[0] / scale) - 1)
        self.y = random.randrange(((size[1] - 100) / scale) - 1)

Solution

  • img is the name of the image file. Load the file and create a pygame.Surface object using pygame.image.load:

    self.image = img

    self.image = pygame.image.load(img)