pygame中Rect类的属性错误

问题描述

我刚开始使用 pygame 和 python,所以没有判断 (谢谢:)) 但我一直在尝试使用 colliderect() 来检查两个 rect 的碰撞(蛇,食物;我想)。我不断收到此错误AttributeError: 'Food' 对象没有属性 'colliderect' 我做错了什么?

# main function
def main():
    clock = pygame.time.Clock()
    FPS = 17
    run = True
    snake = Snake(random.randint(0,400),random.randint(0,10,10)
    food = Food(random.randint(0,10)
    snakeVeLocity_X = 0
    snakeVeLocity_Y = 0
    lost = False
# snake object
# Rect object: Rect(x,y,width,height)
class Snake():
    def __init__(self,x,height):
        self.x = x 
        self.y = y
        self.width = width
        self.height = height

    def draw(self,gameScreen):
        pygame.draw.rect(gameScreen,colors.BLACK,(self.x,self.y,self.width,self.height))

    # def get_head_position(self):
    #   return self.x,self.height

# food object
class Food():
    def __init__(self,height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.collide = False

    def draw(self,colors.YELLOW,self.height))
# check for collision
        if food.colliderect(snake):
            print("collision")

以上是我认为足以说明我的观点的代码

附言。我也是 stackoverflow 的新手。

解决方法

colliderectpygame.Rect 的一个方法。但是 Food 不是 pygame.Rect 对象。

删除属性 xywidthheight,but add a rect` 属性:

class Food():
    def __init__(self,x,y,width,height):
        self.rect = pygame.Rect(x,height)
        self.collide = False

    def draw(self,gameScreen):
        pygame.draw.rect(gameScreen,colors.YELLOW,self.rect)

现在您可以将方法 colliderectfood.rect 一起使用:

if food.rect.colliderect(snake):
    print("collision")