如何更改网格中单个矩形的颜色?

时间:2017-07-25 19:27:38

标签: python grid pygame

我已经编程了一个网格,但现在我想改变网格中单个矩形的颜色。

x = 5
y = 5

height = 30
width = 50
size = 20
color = (255,255,255)
new_color = (255,255,0)

screen.fill((0,0,0))

def draw_grid():
    for y in range(height):
        for x in range(width):
            rect = pygame.Rect(x * (size + 1),y * (size + 1),size,size)
            pygame.draw.rect(screen,color,rect)
            x += 20
            rects.append((rect,color))
        y += 20

rects = []
colored_rects = []

while 1:

    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()

    draw_grid()

    if pygame.mouse.get_pressed()[0]:
        mouse_pos = pygame.mouse.get_pos()
        for i,(rect,color) in enumerate(rects):
            if rect.collidepoint(mouse_pos):
                rects[i] = (rect,new_color)
                colored_rects.append((rect,new_color))


    for rect,color in rects:
        pygame.draw.rect(screen,color,rect)
    for rect,new_color in colored_rects:
        pygame.draw.rect(screen,new_color,rect)

    pygame.display.flip()
    clock.tick()

现在我只想在点击它时更改一个矩形,但稍后它们必须自动更改(例如,当有三个矩形接触相同颜色时,它们都必须变为白色)。我已经更新了一点,但仍然存在一些问题。例如:您必须单击矩形直到它改变颜色,并且需要花费很多时间来改变颜色。

1 个答案:

答案 0 :(得分:0)

一种解决方案是将rects与它们的颜色一起存储在元组中。如果按下鼠标按钮,则迭代rectangles列表,如果矩形与鼠标碰撞,则创建一个带有rect和新颜色的元组,并替换当前索引处的元组。

import sys
import pygame as pg


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()

    height = 30
    width = 50
    size = 20
    color = (255, 255, 255)
    new_color = (255, 255, 0)

    rectangles = []
    for y in range(height):
        for x in range(width):
            rect = pg.Rect(x * (size+1), y * (size+1), size, size)
            # The grid will be a list of (rect, color) tuples.
            rectangles.append((rect, color))

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        if pg.mouse.get_pressed()[0]:
            mouse_pos = pg.mouse.get_pos()
            # Enumerate creates tuples of a number (the index)
            # and the rect-color tuple, so it looks like:
            # (0, (<rect(0, 0, 20, 20)>, (255, 255, 255)))
            # You can unpack them directly in the head of the loop.
            for index, (rect, color) in enumerate(rectangles):
                if rect.collidepoint(mouse_pos):
                    # Create a tuple with the new color and assign it.
                    rectangles[index] = (rect, new_color)

        screen.fill((30, 30, 30))

        # Now draw the rects. You can unpack the tuples
        # again directly in the head of the for loop.
        for rect, color in rectangles:
            pg.draw.rect(screen, color, rect)

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
    sys.exit()