Reputation: 344
code:
import pygame
def enemie():
global speed_x
ball.y += speed_x
if ball.colliderect(player):
groups.kill()
pygame.init()
running = True
clock = pygame.time.Clock()
speed_x = 10
ball = pygame.Rect(250, 0 ,20,20)
player = pygame.Rect(250, 450, 50, 50)
screen = pygame.display.set_mode((500, 500))
Groups = pygame.sprite.Group()
Groups.add(ball)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
enemie()
screen.fill((255, 255, 255)) #color
pygame.draw.ellipse(screen, [0, 0, 255], player)
pygame.draw.ellipse(screen, [255, 0, 0], ball)
pygame.display.flip()
clock.tick(30)
pygame.quit()
error:
TypeError: pygame.sprite.AbstractGroup.add() argument after * must be an iterable, not int
During handling of the above exception, another exception occurred:
AttributeError: 'int' object has no attribute 'add_internal'
During handling of the above exception, another exception occurred:
TypeError: unhashable type: 'pygame.Rect'
First of all, I have never seen such a huge error before. I am trying to create a game where you have a ball coming from above and when it touches your blue character, The red ball is deleted. I got everything good until I tried to remove the ball when touched. I used a sprite group so I could 'kill' the group. What did I do wrong here?
Upvotes: 2
Views: 964
Reputation: 211106
You cannot kill a sprite Group, but you can kill a Sprite. kill
removes a sprite from all groups. You just can a pygame.sprite.Sprite
objects to a pygame.sprite.Group
. ball
is just a pygame.Rect
object. Therefore it cannot be add to a Group.
Working example:
import pygame
def enemie():
global speed_x
ball.rect.y += speed_x
if ball.rect.colliderect(player.rect):
player.kill()
pygame.init()
screen = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()
# ball sprite
ball = pygame.sprite.Sprite()
ball.rect = pygame.Rect(250, 0, 20, 20)
ball.image = pygame.Surface((20, 20), pygame.SRCALPHA)
pygame.draw.circle(ball.image, (255, 0, 0), (10, 10), 10)
speed_x = 10
# player sprite
player = pygame.sprite.Sprite()
player.rect = pygame.Rect(250, 450, 50, 50)
player.image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(player.image, (0, 0, 255), (25, 25), 25)
# group with all sprites
group = pygame.sprite.Group()
group.add(ball)
group.add(player)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
enemie()
screen.fill((255, 255, 255)) #color
group.draw(screen)
pygame.display.flip()
clock.tick(30)
pygame.quit()
Upvotes: 2