2014-01-12 74 views
0

刚刚在pygame中发生了精灵碰撞。当这段代码运行时,会弹出一个AttributeError,说''Group'对象没有属性'rect''。我无法弄清楚为什么会出现这个错误。建议?具有基本精灵碰撞的AtrributeError

from random import randint 
import pygame 
pygame.init() 


white = [255,255,255] 
blue = [0,0,255] 
red = [255,0,0] 

size = (400,400) 
screen = pygame.display.set_mode(size) 
pygame.display.set_caption('Simple character') 

clock = pygame.time.Clock() 

class Ball(pygame.sprite.Sprite): 

    def __init__(self, xDelta, yDelta, color): 
     pygame.sprite.Sprite.__init__(self) 
     self.image = pygame.Surface([20,20]) 
     self.image.fill(white) 
     self.image.set_colorkey(white) 

     self.xDelta = xDelta 
     self.yDelta = yDelta 
     self.color = color 

     self.rect = self.image.get_rect() 

     pygame.draw.circle(self.image, self.color, 
          [(self.rect.x + 10), (self.rect.y + 10)], 10) 



    def update(self): 
     self.rect.x += self.xDelta 
     self.rect.y += self.yDelta 

     if self.rect.y <= 0 or self.rect.y >= 380: 
      self.yDelta *= -1  
     if self.rect.x >= 380 or self.rect.x <= 0: 
      self.xDelta *= -1 

allSprites = pygame.sprite.Group() 
blues = pygame.sprite.Group() 
reds = pygame.sprite.Group() 

for i in range(5): 
    circle = Ball(randint(1, 10), randint(1, 10), blue) 
    circle.rect.x = randint(0,380) 
    circle.rect.y = randint(0,380) 
    blues.add(circle) 
    allSprites.add(circle) 

    circle2 = Ball(randint(1, 10), randint(1, 10), red) 
    circle2.rect.x = randint(0,380) 
    circle2.rect.y = randint(0,380) 
    reds.add(circle2) 
    allSprites.add(circle2) 

play = True 

while play: 
    clock.tick(20) 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      play = False 

    allSprites.update() 

    collision = pygame.sprite.spritecollide(blues, reds, True) 
    for circle in collision: 
     circle.xDelta = circle.yDelta = 0 

    screen.fill(white) 

    allSprites.draw(screen) 

    pygame.display.flip() 

pygame.quit() 

回答

0

您正在对Group类的两个对象调用spritecollide。该函数接受一个Sprite和一个组。

spritecollide(sprite, group, dokill, collided = None) -> Sprite_list 

你可以做的是通过所有的blues精灵循环,并调用spritecollide一个蓝色小球。

for blueball in blues.sprites: 
    collision = pygame.sprite.spritecollide(blues, reds, True) 
     for circle in collision: 
      circle.xDelta = circle.yDelta = 0