首页 > 解决方案 > 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, 400), 10, 10)
    food = Food(random.randint(0, 400), random.randint(0, 400), 10, 10)
    snakeVelocity_X = 0
    snakeVelocity_Y = 0
    lost = False
# snake object
# Rect object: Rect(x, y, width, height)
class Snake():
    def __init__(self, x, y, width, 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.y, self.width, self.height

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

    def draw(self, gameScreen):
        pygame.draw.rect(gameScreen, colors.YELLOW, (self.x, self.y, self.width, self.height))
# check for collision
        if food.colliderect(snake):
            print("collision")

以上是我认为足以表达我的观点的代码。

附言。我也是stackoverflow的新手,任何做/不做的事情。

标签: pythonpygame

解决方案


colliderect是一种方法pygame.Rect。然而Food不是一个pygame.Rect对象。

删除 attributes xywidthrect`height, but add a 属性:

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

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

现在您可以使用该colliderect方法food.rect

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

推荐阅读