2017-07-25 57 views
1

我已经编写了一个网格,但现在我想更改网格中单个矩形的颜色。如何更改网格中单个矩形的颜色?

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() 

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

回答

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() 
+0

我试过这段代码,它的工作原理,但如果我点击一个矩形,它只会改变颜色一秒或更少。它并不总是有效。 – AV13

+0

添加您的更新代码到您的文章,我会看看它。 – skrx

+0

我刚刚解决了这个问题 – AV13

相关问题