how to check if mouse is over a rect in pygame

Solutions on MaxInterview for how to check if mouse is over a rect in pygame by the best coders in the world

showing results for - "how to check if mouse is over a rect in pygame"
Jules
12 Jan 2017
1rectangle = pygame.Rect(5, 5, 20, 20) # x, y, width, height
2
3def is_over(rect, pos):
4    # function takes a tuple of (x, y) coords and a pygame.Rect object
5    # returns True if the given rect overlaps the given coords
6    # else it returns False
7    return True if rect.collidepoint(pos[0], pos[1]) else False
8
9pos = pygame.mouse.get_pos() # gets the current mouse coords
10if is_over(rectangle, pos): # pass in the pygame.Rect and the mouse coords
11    print('The mouse is over the rectangle')
12else:
13    print('The mouse is not over the rectangle')