pythonpygamepygame2

My pygame program doesn't want to change y axis


The goal is to make squares with random shade of green on screen, but i y axis doesn't want to change

import pygame
from random import randint

#activate pygame
pygame.init()

#screen (x,y)
screen = pygame.display.set_mode([500, 500])

#bool - if game is running
running = True

tablica = [[randint(1,255) for i in range(10)] for i in range(10)]

print(tablica)

#while game is running
while running:

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

    #fill screen with (r,g,b)
    screen.fill((255,255,255))

    x = 0
    for i, e in enumerate(tablica):
        for j in e:
            pygame.draw.rect(screen,(j,j,0),(x,50*i,50,50))
            x += 50

    #update screen
    pygame.display.flip()

#turn off game
pygame.quit()

but instead of drawing 100 squares all over the screen, it only makes 10 on the same x axis. Thanks in advance!


Solution

  • x grows continuously and is never placed at the beginning of the line after the first line. You have to reset x in the outer loop:

    while running:
        # [...]
    
        # x = 0                                <-- DELETE
    
        for i, e in enumerate(tablica):
            x = 0                            # <-- INSERT
            for j in e:
                pygame.draw.rect(screen,(j,j,0),(x,50*i,50,50))
                x += 50
    

    However, you do not need the variable x at all:

    while running:
        # [...]
    
        for i, e in enumerate(tablica):
            for k, j in enumerate(e):
                pygame.draw.rect(screen,(j,j,0),(k*50,50*i,50,50))