1

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

2 Answers 2

2

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) 
Sign up to request clarification or add additional context in comments.

7 Comments

I used a variable called selected_rect instead, and used your idea. Works perfectly, thanks!
This would only work if @Theo is storing the rectangles in a list. He (sorry if wrong pronoun) has already stated that the only info being stored is list_of_rect, which contains coordinates, not rectangle objects
@PMARINA assuming that list_of_rect stores its data like [[x, y, width, height], [x2, y2, width2, height2],...[xn, yn, widthn, heightn]] the rects_clicked does not need to keep track of the rectangle objects but instead checks if the sublist is in rects_clicked. So rects_clicked might look like [[x, y, width, height], [x3, y3, width3, height3]] which is fine for the OP's requirements
@PMARINA essentially each group of coordinates can be treated as an object
@PMARINA that's true but Theo isn't using objects and it probably won't matter that much. I could add a basic class if you really want me to.
|
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.