简体   繁体   English

Pygame - 如何检查我的rect是否已被点击?

[英]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. list_of_rect是表示rect的位置和大小的坐标列表(x,y,width,height)。

render_display just shows the screen with text. render_display只显示带有文本的屏幕。

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 但我不确定如何实现这一点

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)

I would use a 2d list containing Booleans. 我会使用包含布尔值的2d列表。 When the rectangle is clicked, I would say list[xCoordOfRectangle][yCoordOfRectangle] = !list[xCoordOfRectangle][yCoordOfRectangle] . 单击矩形时,我会说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. 请注意,您需要初始化list以使每个矩形都为false。 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; 另请注意,如果矩形没有以矩形方式排列,则需要按以下方式使用数字:1分配,true; 2 is assigned, false; 分配2,假; 3 is unassigned (sort of like null). 3是未分配的(有点像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. 或者,或者你可以只有一维列表来存储布尔值,然后跟踪列表中的哪个元素是哪个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM