<p>首先,当为球创建<code>rect</code>属性时,它应该是<code>self.rect = pygame.Rect(x, y, width, height)</code>(假设您使用<code>import pygame</code>导入Pygame)。这应该可以处理你的<code>AttributeError</code>。你的<code>ballRect</code>,<code>ballRect = pygame.Rect(Ball.coordinateX, Ball.coordinateY, 10, 10)</code>也是如此</p>
<p>接下来,您使用了错误的rect碰撞检测功能<code>pygame.sprite</code>指的是Pygame中完全不同的东西(它的<code>Sprite</code>对象),并且您的<code>Ball</code>和<code>Paddle</code>类都不是您编写的代码中的Pygame精灵。因此,在这里调用<code>pygame.sprite.collide_rect()</code>没有任何意义</p>
<p>相反,您应该简单地使用<code>rect.colliderect</code>,如下所示:</p>
<pre><code>if rect.colliderect(other_rect):
# Colliding!
print("Stop touching me!")
</code></pre>
<p>或者在您的情况下:</p>
<pre><code>if player.rect.colliderect(ballRect):
bounce()
</code></pre>
<p>此外,您不需要将<code>rect</code>作为参数传递给<code>Paddle</code>初始化,因为它从未被使用过。对象的<code>rect</code>完全由其他参数生成</p>
<p>最后,您的<code>Ball</code>类和实例化代码似乎有点不对劲。您应该像对<code>Paddle</code>一样生成并初始化它</p>
<p><strong>编辑</strong>最后一件事。在pygame中,当您创建一个具有<code>rect</code>属性的对象时,您不再需要为该对象分配<code>x</code>和<code>y</code>值,因为无论何时需要它们,例如在<code>blit</code>中,您都可以直接传递<code>rect</code>(或者在某些边缘情况下,<code>rect.x</code>和<code>rect.y</code>作为位置参数,pygame将很好地处理其余的问题</p>
<p>下面是您的代码应该是什么样子(还有一些其他问题需要解决):</p>
<pre><code>class Paddle():
def __init__(self, x, y, width, height):
self.width = width
self.height = height
self.rect = pygame.Rect(x, y, width, height)
class Ball():
def __init__(self, x, y, width, height):
self.rect = pygame.Rect(x, y, width, height)
self.velocity = [random.randint(0,1),random.randint(-1,1)]
player = Paddle(1100, 300, 10, 30)
enemy = Paddle(100, 300, 10, 30)
ball = Ball(600, 300, 10, 10)
# Other stuff
# Collision checking
if player.rect.colliderect(ball.rect):
bounce()
</code></pre>