I'm sorry if this question is a duplicate, but I've followed numerous pages on this site trying to find an answer, and I haven't been able to get one to work yet. Some of the pages I've used are:
Pygame mouse clicking detection
how does collide.rect work in pygame
It may be my lack of coding comprehension, and I apologize if that's the case. However, I found the most "helpful" page to be the first link. Using Sloth's first answer, it seemed very simple and something I would be able to do. Once his method did not work, I tried searching around even more for on YouTube and other sites. I also couldn't find an answer.
All I want to do is simply print "clicked" when a sprite is clicked. Here is my code.
import pygame
size = (700,500)
screen = pygame.display.set_mode(size)
done = False
clock = pygame.time.Clock()
itunes = pygame.image.load('itunes.png')
screen.blit(itunes,(200,200))
sprites = [itunes]
while not done:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
clicked_sprites = [s for s in sprites if s.rect.collidepoint(pos)]
for i in clicked_sprites:
print('clicked sprite')
pygame.display.flip()
clock.tick(60)
I've learned very little of the Python language, but I found myself getting bored making the same text-based programs and would like to move on.
EDIT: I'm sorry, I should have stated what error I was getting. I'm getting: AttributeError: 'pygame.Surface' object has no attribute 'rect'
EDIT: Having trouble drawing the image on the screen
import pygame
size = (700,500)
screen = pygame.display.set_mode(size)
done = False
clock = pygame.time.Clock()
white = (0,0,0)
image = 'itunes.png'
class Thing(pygame.sprite.Sprite):
def __init__(self, image, x, y):
self.image = pygame.image.load('itunes.png')
self.x = x
self.y = y
@property
def rect(self):
return self.image.get_rect(topleft=(self.x, self.y))
itunes = Thing(image,200,200)
SpriteGroup = pygame.sprite.Group()
SpriteGroup.add(itunes)
while not done:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
clicked_sprites = [s for s in SpriteGroup if s.rect.collidepoint(pos)]
for i in clicked_sprites:
print('clicked sprite')
screen.fill((0, 0, 0))
SpriteGroup.draw(screen)
pygame.display.flip()
clock.tick(60)