data_pi
data_pi

Reputation: 821

Pygame - How do I check if my rect has already been clicked?

What I'm trying to do is if a rect has been clicked, it is selected and text will display, but if its clicked again, then it is de-seleced and the text goes away.

list_of_rect is a list of coordinates (x, y, width, height) representing the position and size of the rect.

render_display just shows the screen with text.

if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
    x, y = event.pos
    for i in range(len(list_of_rect)):
        j = list_of_rect[i]
        if j[0][0] <= x <= (j[0][0] + j[0][2]) and j[0][1] <= y <= \
                (j[0][1] + j[0][3]):
                render_display(screen, text)

EDIT: One idea I was thinking was to keep track of the rectangle that has been clicked on. But I'm not sure how to implement this

Upvotes: 1

Views: 377

Answers (2)

rassar
rassar

Reputation: 5660

Try having a list, like this:

rects_clicked = []

Then, in your event code:

if j not in rects_clicked:
    #undisplay text
    rects_clicked.append(j)
else:
    #display text
    rects_clicked.remove(j)

Upvotes: 2

PMARINA
PMARINA

Reputation: 304

I would use a 2d list containing Booleans. When the rectangle is clicked, I would say list[xCoordOfRectangle][yCoordOfRectangle] = !list[xCoordOfRectangle][yCoordOfRectangle]. Then, in the drawing method, I would say:

for i in list:
    for j in i: 
        if(j): 
            #information drawing function goes here
        else:
            #Solid/Empty Rectangle drawing function goes here

Note that you would need to initialize list to have false for every rectangle. Also note that if the rectangles are not arranged in a rectangular fashion, you would need to use numbers in the following way: 1 is assigned, true; 2 is assigned, false; 3 is unassigned (sort of like null). Either that, or you could just have a one-dimensional list to store the Booleans and then keep track of which element in the list is which element.

Upvotes: 1

Related Questions