So, now that our image can animate and wrap around the screen, let’s try to click on it!
First, though we should just take moment to learn about how the mouse itself works in pygame.
The important new lines which are now part of our game loop is to constantly look to see if the mouse click event is fired (line 21) and then, if so, to see if the x,y coordinates of the mouse are inside the rectangle (line 24)
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import pygame pygame.init() width=350; height=400 screen = pygame.display.set_mode( (width, height ) ) pygame.display.set_caption('clicked on image') redSquare = pygame.image.load("images/red-square.png").convert() x = 20; # x coordnate of image y = 30; # y coordinate of image screen.blit(redSquare , ( x,y)) # paint to screen pygame.display.flip() # paint screen one time running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEBUTTONDOWN: # Set the x, y postions of the mouse click x, y = event.pos if redSquare.get_rect().collidepoint(x, y): print('clicked on image') #loop over, quite pygame pygame.quit() |