ZamaaN
ZamaaN

Reputation: 63

AttributeError: 'pygame.math.Vector2' object has no attribute

Cannot draw the food because of pygame error "AttributeError: 'pygame.math.Vector2' object has no attribute". Can't figure out what did I miss... help me get rid of it. My code is here:

import pygame, sys
from pygame.locals import *
from pygame.math import Vector2

class Food:
    def __init__(self):
        self.food_x = 5
        self.food_y = 4
        self.position = Vector2(self.food_x, self.food_y)

    def draw_food(self):
        food_shape = pygame.Rect(self.position.food_x, self.position.food_y, cell_size, cell_size)
        pygame.draw.rect(screen, screen_surface_color, food_shape)

cell_size = 40
cell_number = 19
screen_color = (175, 215, 70)
screen_surface_color = (70, 70, 214)

pygame.init()
screen = pygame.display.set_mode((cell_number * cell_size, cell_number * cell_size))
clock = pygame.time.Clock()

food = Food()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()
    
        elif event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    screen.fill(screen_color)
    food.draw_food()
    pygame.display.update()
    clock.tick(60)

I'm getting this error:

Traceback (most recent call last):
File "e:\archive_root\CSE\Python\portfolio_py\projects_py\games_py\snake2_py\snake_game2.py", line 39, in <module>
food.draw_food()
File "e:\archive_root\CSE\Python\portfolio_py\projects_py\games_py\snake2_py\snake_game2.py", line 12, in draw_food
food_shape = pygame.Rect(self.position.food_x, self.position.food_y, cell_size, cell_size)
AttributeError: 'pygame.math.Vector2' object has no attribute 'food_x'

Upvotes: 2

Views: 1258

Answers (2)

Rabbid76
Rabbid76

Reputation: 211135

Food has the attributes food_x and food_y, but the vector object position has the attributes x and y:

food_shape = pygame.Rect(self.position.food_x, self.position.food_y, cell_size, cell_size)

food_shape = pygame.Rect(self.position.x, self.position.y, cell_size, cell_size)

Upvotes: 1

Eno Gerguri
Eno Gerguri

Reputation: 687

pygame.math.Vector2 does not have a flood_x attribute, I think you are referring to the x and y attribute it has:

class Food:
    def __init__(self):
        self.food_x = 5
        self.food_y = 4
        self.position = Vector2(self.food_x, self.food_y)

    def draw_food(self):
        food_shape = pygame.Rect(self.position.x, self.position.y, cell_size, cell_size)  # position.x not position.flood_x
        pygame.draw.rect(screen, screen_surface_color, food_shape)

see Pygame Docs for Vector2 here

Upvotes: 1

Related Questions