首页 > 解决方案 > Pygame点击改变多个矩形的颜色

问题描述

当我单击一个矩形时,颜色会发生变化。但我不能同时改变它周围的矩形。如何访问我单击的矩形周围的 x 和 y?

import pygame
import sys

width = 600
height = 600
size = 120
white = (255,255,255)

pygame.init()

screen = pygame.display.set_mode((width, height))

# create list with all rects
all_rects = []
for y in range(0, width, height):
    row = []
    for x in range(0, width, height):
        rect = pygame.Rect(x, y, size-1, size-1)
        row.append([rect, (0, 255, 0)])            
    all_rects.append(row)

while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # check which rect was clicked and change its color on list
            for row in all_rects:
                for item in row:
                    rect, color = item
                    if rect.collidepoint(event.pos):
                        if color == (0, 255, 0):
                            item[1] = (255, 0, 0)
                        else:
                            item[1] = (0, 255, 0)

    # draw all in every loop

    screen.fill(white)

    for row in all_rects:
        for item in row:
            rect, color = item
            pygame.draw.rect(screen, color, rect)

    pygame.display.flip()

标签: pythonpygame

解决方案


您应该像这样修改第 15、17 行;

for y in range(0, width, size):
    row = []
    for x in range(0, width, size):

在您当前的代码中, all_rects 仅包含 1 个矩形。

完整代码:

import pygame
import sys

width = 600
height = 600
size = 120
white = (255,255,255)

pygame.init()

screen = pygame.display.set_mode((width, height))

# create list with all rects
all_rects = []
for y in range(0, width, size):
    row = []
    for x in range(0, width, size):
        rect = pygame.Rect(x, y, size-1, size-1)
        row.append([rect, (0, 255, 0)])
    all_rects.append(row)

while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # check which rect was clicked and change its color on list
            for row in all_rects:
                for item in row:
                    rect, color = item
                    if rect.collidepoint(event.pos):
                        if color == (0, 255, 0):
                            item[1] = (255, 0, 0)
                        else:
                            item[1] = (0, 255, 0)

    # draw all in every loop

    screen.fill(white)

    for row in all_rects:
        for item in row:
            rect, color = item
            pygame.draw.rect(screen, color, rect)

    pygame.display.flip()

推荐阅读