ROBlackSnail
ROBlackSnail

Reputation: 109

Python 3.5.2: Pygame hightlight rectangle if mouse on it

Using the pygame module, I drew a black rectangle on the screen. I write a code that "highlights" me the rectangle by drawing another (green) rectangle around it ( which has the width = 4 ) when I mouse over it. It works, but only if the mouse is moving over it . If it is stationary on the surface of the black rectangle, the green rectangle does not appear . Here is my code :

import random, pygame, sys
from pygame.locals import *

pygame.init()
done = False
clock = pygame.time.Clock()
white = (255,255,255) # COLLORS
black = (0,0,0)
red = (255,0,0)
green = (0,100,0)
display_width = 800 # SCREEN DIMMENSION
display_height = 600
game_display = pygame.display.set_mode((display_width,display_height)) # SCREEN

def draw_rect(x,y):
    rect = pygame.Rect(x, y, 40, 40)
    pygame.draw.rect(game_display, black, rect)
    if rect.collidepoint(mousex,mousey):
           box_hightlight(x,y)
def box_hightlight(x,y):
    pygame.draw.rect(game_display,green,(x-5,y-5,50,50),4)

while done != True:

    x = (display_width - 40) / 2
    y = (display_height - 40) / 2

    mousex = 0  # used to store x coordinate of mouse event
    mousey = 0 # used to store y coordinate of mouse event

    for event in pygame.event.get():  # PRESSED KEYS EFFECTS
        if event.type == pygame.QUIT:
            done = True
        elif event.type == MOUSEMOTION :
            mousex, mousey = event.pos
        elif event.type == MOUSEBUTTONUP:
            mousex, mousey = event.pos
            mouseClicked = True

    game_display.fill(white)
    draw_rect(x,y)
    pygame.display.update()
    clock.tick(60)

What did I missed ?

Upvotes: 1

Views: 451

Answers (1)

sloth
sloth

Reputation: 101042

In draw_rect, you check if the position mousex, mousey is inside rect.

But in your mainloop, you set mousex, mousey to 0, 0, and set it to the mouse position only when a MOUSEMOTION (or MOUSEBUTTONUP) event occurs.

This explains your It works, but only if the mouse is moving over it question.

Don't use the events and simply use pygame.mouse.get_pos to get the mouse postion.

Upvotes: 1

Related Questions