-1

I have been coding a simple game. I am trying to make one of my sprites clickable, and execute loaddeath() when clicked.

I have been running into several errors though.

screen.blit(chinese, (randomx1, randomy1))
screen.blit(green, (randomx2, randomy2))
screen.blit(eden, (randomx3, randomy3))

screen.blit(obama, (randomx5, randomy5))
screen.blit(blue, (randomx6, randomy6))

#I want this object to be clickable
screen.blit(kevin, (randomx8, randomy8))
screen.blit(hud, (0, 0))

My event Loop:

for event in pygame.event.get():
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

What do I need to add?

Morten Kristensen
  • 7,412
  • 4
  • 32
  • 52
Eden Pigram
  • 349
  • 1
  • 3
  • 7

1 Answers1

1

To detect the mouse click you need to use pygame.mouse.get_pressed()

and you also need to make a rect for the object you want to make clickable.

Then, write an if statement using collidepoint(). This will tell you if a point is in a rect.

So, do this:

if pygame.mouse.get_pressed()[0] and sprite_rect.collidepoint(mouse_pos):
    #do action

This is basically saying if the mouse button is clicked and the mouse and rect are touching do something, where sprite_rect is the rect you made for the object you want clickable and mouse_pos is the mouse's current position.

(to get the mouse's position use pygame.mouse.get_pos() in your loop)

For more info on all these methods look here.

Community
  • 1
  • 1
Serial
  • 7,925
  • 13
  • 52
  • 71