首页 > 解决方案 > 在 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, 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, (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:
                    win.blit(objPawn.clickbox, (objPawn.start_x, objPawn.start_y))

但后来我收到以下错误:TypeError: argument 1 must be pygame.Surface, not tuple

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

标签: pythonpygame

解决方案


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, 0), objPawn.clickbox, 2)
    
    pygame.display.update()

推荐阅读