External Exam Download Resources Web Applications Games Recycle Bin

Detect mouse click on a square

mouse click on a square.py

import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
while not done:

  square = pygame.draw.rect( screen, (255, 255, 255), (5, 5, 50, 50) )
  
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      done = True

    if event.type == pygame.MOUSEBUTTONDOWN:
      mouse_pos = pygame.mouse.get_pos() #(x,y)
      if square.collidepoint(mouse_pos): #same as position_meeting() in gml
        print("you clicked on the square")

  pygame.display.flip()
pygame.quit()