我怎样才能让我的代码工作,这样当我单击灰色方块时,它不会变成蓝色。它也不会删除网格上的蓝色方块?

问题描述 投票:0回答:1

基本上,我已经构建了一个带有正方形的网格,并且我想这样做,当我有灰色正方形时,我无法单击灰色并将其更改为蓝色(我已成功实现)。但是,当我单击灰色方块时,如果我在其他地方有一个蓝色方块(因为我一次只想在屏幕上显示一个蓝色方块),我不希望灰色方块将颜色更改为蓝色,并且我不希望已存在的蓝色方块将被删除。

我已经尝试过这个

if pygame.mouse.get_pressed()[0]:
        y,x = mouse_over_square()
        for square in grid:
            if square.y == y and square.x == x and square.colour != DARK_BLUE and square.colour != RED:
                square.colour = GREY
                grid_square = pygame.Rect(square.y, square.x, square_size, square_size)
                pygame.draw.rect(screen, square.colour, grid_square)
    elif pygame.mouse.get_pressed()[2]:
        y,x = mouse_over_square()
        for square in grid:
            if square.colour == DARK_BLUE:
                square.colour = CREAM
                grid_square = pygame.Rect(square.y, square.x, square_size, square_size)
                pygame.draw.rect(screen, square.colour, grid_square)
            elif square.y == y and square.x == x and square.colour != RED and square.colour != GREY:
                square.colour = DARK_BLUE
                grid_square = pygame.Rect(square.y, square.x, square_size, square_size)
                pygame.draw.rect(screen, square.colour, grid_square)

但是,这无法完成我想要的操作,而且方块会闪烁且滞后。

python pygame logic
1个回答
0
投票

定义更新方块颜色的函数

首先,定义一个函数来更新正方形的颜色并在屏幕上重新绘制它。这将有助于消除代码重复并使您的代码更易于维护。

def update_square_color(square, new_color):
    square.colour = new_color
    grid_square = pygame.Rect(square.y, square.x, square_size, square_size)
    pygame.draw.rect(screen, square.colour, grid_square)

优化代码流程

left_click, right_click = pygame.mouse.get_pressed()[:2]
y, x = mouse_over_square()

for square in grid:
    is_blue = square.colour == DARK_BLUE
    if left_click and square.y == y and square.x == x and square.colour not in {DARK_BLUE, RED}:
        if current_blue_square is None:
            update_square_color(square, BLUE)
            current_blue_square = square
    elif right_click and is_blue:
        update_square_color(square, CREAM)
    elif right_click and square.y == y and square.x == x and square.colour not in {RED, GREY}:
        update_square_color(square, DARK_BLUE)

重画网格

redraw_grid()

我无法测试它,但也许它有帮助

© www.soinside.com 2019 - 2024. All rights reserved.