Home > Net >  changing color of squares in pygame
changing color of squares in pygame

Time:12-22

I want to make simple program in which you can press squares on screen and they will change color, but i can't find in documentation how to do it with pygame.draw.rect.

import pygame
pygame.init()


screen = pygame.display.set_mode([501, 501])

siatka = [[[0] for i in range(10) ]for i in range(10)]

def rysowanie():
    for i,el in enumerate(siatka):
        for j,ele in enumerate(el):
            pygame.draw.rect(screen,(0,0,0),pygame.Rect(50*j  1,50*i 1,49,49))

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

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

    rysowanie()

    pygame.display.flip()
    
pygame.quit()

I don't even have an idea what is the name of the thing i want to do, so if this is very easy I'am sorry.

CodePudding user response:

Make your siatka a matrix of colors, and for each square, draw its corresponding color. When the screen is clicked, change the color in siatka for that mouse position.

import pygame

pygame.init()
screen = pygame.display.set_mode([501, 501])
siatka = [[(0, 0, 0) for i in range(10)] for i in range(10)]

def rysowanie():
    for i, el in enumerate(siatka):
        for j, ele in enumerate(el):
            pygame.draw.rect(screen, ele, pygame.Rect(50 * j   1, 50 * i   1, 49, 49))

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            siatka[event.pos[1] // 50][event.pos[0] // 50] = (255, 0, 0)
    screen.fill((0, 255, 0))
    rysowanie()
    pygame.display.flip()
pygame.quit()
  • Related