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

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

无法绘制食物,因为 pygame 错误“AttributeError:'pygame.math.Vector2' 对象没有属性”。无法弄清楚我错过了什么...帮我摆脱它。 我的代码在这里:

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)

我收到这个错误:

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'

pygame.math.Vector2 没有 flood_x 属性,我认为您指的是它具有的 xy 属性:

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)

Pygame Docs for Vector2 here

食物具有 food_xfood_y 属性,但矢量对象 position 具有 xy 属性:

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)