You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pygame绘制食物时触发AttributeError: 'pygame.math.Vector2' object has no attribute 'food_x'错误求助

解决Pygame绘制食物时的AttributeError问题

嘿,这个错误很好解决——你只是搞混了Vector2对象的属性访问方式而已!

错误原因分析

你在Food类里创建了Vector2类型的position属性,但在draw_food方法里,错误地尝试用self.position.food_x和self.position.food_y来获取坐标。实际上,pygame.math.Vector2对象的坐标是通过内置的.x和.y属性访问的,它根本没有food_x、food_y这些自定义属性,这就是触发AttributeError的核心原因。

修正方案

只需要修改draw_food方法里的坐标获取逻辑就行,另外还可以简化Food类的代码(去掉多余的food_x和food_y变量):

修正后的完整代码

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

class Food:
    def __init__(self):
        # 直接初始化Vector2,无需单独存储food_x和food_y
        self.position = Vector2(5, 4)

    def draw_food(self):
        # 使用Vector2内置的.x和.y属性获取坐标
        food_shape = pygame.Rect(self.position.x, self.position.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)

额外可选方案

如果你确实想保留food_x和food_y作为类属性,也可以直接跳过position属性,在绘制时使用自定义属性:

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

不过既然已经用了Vector2来管理位置,直接用它的.x和.y会更符合Pygame的向量使用习惯。

现在运行代码,应该就能正常绘制食物啦!

内容的提问来源于stack exchange,提问作者ZamaaN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 15:47:36