“ball”对象没有属性“top”

2024-06-16 09:13:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个乒乓球游戏,但由于某种原因我犯了一个错误 “ball”对象没有属性“top”

    ball1.x -= ball1.speed
    ball1.y += ball1.speed
    if ball1.top <= 0 or ball1.bottom >= 500:
        ball1.speed *= -1
    if ball1.left <= 0 or ball1.right >= 500:
        ball1.speed *= -1

舞会

# this is the moving ball
class ball:
    def __init__(self,x,y,height,width,color):
        self.x =x
        self.y = y
        self.height = height
        self.width  = width
        self.color = color
        self.speed = 5
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.circle(window, self.color, self.rect.center,10)
ball1 = ball(290,200,20,20,white)



Tags: orrectselfiftopdefwidthpygame
1条回答
网友
1楼 · 发布于 2024-06-16 09:13:18

你只需要将顶部、底部、左侧和右侧添加到你的类中。大概是这样的:

class ball:
    def __init__(self,x,y,height,width,color):
        self.x =x
        self.y = y
        self.height = height
        self.width  = width
        self.color = color
        self.speed = 5
        self.rect = pygame.Rect(x,y,height,width)
        self.top = self.y
        self.bottom = self.y + height
        self.left = self.x
        self.right = self.x + width

    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.circle(window, self.color, self.rect.center,10)

相关问题 更多 >