2017-07-25 79 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

相關問題