gpt4 book ai didi

python - AttributeError: 'pygame.math.Vector2' 对象没有属性

转载 作者:行者123 更新时间:2023-12-04 07:41:09 50 4
gpt4 key购买 nike

由于 pygame 错误“AttributeError: 'pygame.math.Vector2' object has no attribute”,无法绘制食物。不知道我错过了什么......帮我摆脱它。
我的代码在这里:

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

关于python - AttributeError: 'pygame.math.Vector2' 对象没有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67459471/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com