在Pygame中点击条件下显示矩形

问题描述

嗨,我在pygame中写国际象棋游戏。我遇到的问题是,当我想突出显示(用红色矩形)单击图形时,图形只会出现一会儿,即单击鼠标时。然后刷新发生,红色矩形消失。负责的代码是:

def window_redrawing():
    # Drawing the background and chess board
    win.fill(bg_col)
    win.blit(chess_board,(53,50))
    initial_positions()

    mouse_x,mouse_y = pygame.mouse.get_pos()

    for objPawn in pawn_list:
        if objPawn.start_x <= mouse_x <= objPawn.start_x + 86 and objPawn.start_y + 84 >= mouse_y >= objPawn.start_y:
            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                    b = pygame.draw.rect(win,(255,0),objPawn.clickBox,2)
                    pygame.display.update(b)

    pygame.display.update()

我的问题:单击鼠标时如何绘制矩形,使其停留更长的时间? (假设直到再次单击鼠标为止)

我还尝试了其他一些方法,例如win.blit(),如下所示:

def window_redrawing():
    # Drawing the background and chess board
    win.fill(bg_col)
    win.blit(chess_board,50))
    initial_positions()


    mouse_x,mouse_y = pygame.mouse.get_pos()

    for objPawn in pawn_list:
        if objPawn.start_x <= mouse_x <= objPawn.start_x + 86 and objPawn.start_y + 84 >= mouse_y >= objPawn.start_y:
            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                    win.blit(objPawn.clickBox,(objPawn.start_x,objPawn.start_y))

但是随后出现以下错误TypeError: argument 1 must be pygame.Surface,not tuple

感谢所有帮助,谢谢!!!

解决方法

clicked中实例的类添加属性pawn_list(我不知道实际的名字)

class Pawn: # I don't kow the actual name
    def __init__(self)_
        # [...]

        self.clicked = False

设置单击对象时的状态(objPawn.clicked = True)。如果设置了状态clicked,则遍历列表中的对象并绘制矩形:

def window_redrawing():
        
    mouse_x,mouse_y = pygame.mouse.get_pos()
    for objPawn in pawn_list:
        if objPawn.start_x <= mouse_x <= objPawn.start_x + 86 and objPawn.start_y + 84 >= mouse_y >= objPawn.start_y:
            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                    
                    objPawn.clicked = True

    # Drawing the background and chess board
    win.fill(bg_col)
    win.blit(chess_board,(53,50))

    for objPawn in pawn_list:
        if objPawn.clicked:
            pygame.draw.rect(win,(255,0),objPawn.clickbox,2)
    
    pygame.display.update()