Home > Back-end >  How to fix Error with pygame "object is not iterable"
How to fix Error with pygame "object is not iterable"

Time:12-20

Here is my code



import pygame as pg



RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
WIDTH = 1920
HEIGHT = 1080
pg.init()
FPS = 50
fpsClock = pg.time.Clock()
screen = pg.display.set_mode((WIDTH, HEIGHT), 0, 32)
ball1Img = pg.image.load('test/sferoid.png')
x1 = y1 = 200  # координаты
xv1 = yv1 = 4  # скорость
check = parity = False


class Ball(pg.sprite.Sprite):
    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.image.load('test/sferoid.png')
        self.rect = self.image.get_rect(centerx=200, bottom=200)

    def update(self) -> None:
        global xv1
        global yv1
        xv1 = -xv1 if (self.rect.x > 1920 - 49 or self.rect.x < 0) else xv1  # отскок
        yv1 = -yv1 if (self.rect.y > 1080 - 49 or self.rect.y < 0) else yv1  # от стенок
        self.rect.x  = xv1
        self.rect.y  = yv1


class Basket(pg.sprite.Sprite):
    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        # self.image = pg.image.load('test/desk.png')\
        self.image = pg.image.load('test/desk.png')
        self.image = pg.transform.scale(self.image, (100, 25))
        self.rect = self.image.get_rect(centerx=WIDTH // 2, bottom=HEIGHT - 50)

    def update(self) -> None:
        klavisha = pg.key.get_pressed()
        if klavisha[pg.K_a] and self.rect.x >= 0:
            self.rect.x -= 20
        if klavisha[pg.K_d] and self.rect.right <= WIDTH:
            self.rect.x  = 20


basket = Basket()
ball = Ball()
while True:
    fpsClock.tick(FPS)
    screen.fill(BLACK)
    basket.update()
    ball.update()
    screen.blit(basket.image, basket.rect)
    screen.blit(ball.image, ball.rect)
    pg.display.update()
    if pg.sprite.spritecollide(basket, ball, dokill=False):
        xv1 = -xv1
        yv1 = -yv1
    for event in pg.event.get():
        if event.type == pg.QUIT:
            pg.quit()

I apologize for such a crooked code, but please understand and forgive. sferoid desk

When I try to run the program, I get a TypeError: 'Ball' object is not iterable at the line:

if pg.sprite.spritecollide(basket, ball, dokill=False):
    xv1 = -xv1
    yv1 = -yv1

But if you remove this line, then the code will work.

I don't get why is is doing this but if someone can help me that would be greatly appreciated.

CodePudding user response:

pypame.sprite.spritecollide is used to detect the collision between a pygame.sprite.Sprite and the sprites in a pygame.sprite.Group. However, basket and ball are both pygame.sprite.Sprite objects. You have to use pygame.sprite.collide_rect:

if pg.sprite.spritecollide(basket, ball, dokill=False):

if pygame.sprite.collide_rect(basket, ball):
  • Related