Search code examples
pythoncolorspygame

I need some help drawing coloured squares in a certain order with pygame for python 3.2


this is my first post here! I hope this question wasn't answered before, unfortunately I didn't really know what I should have searched for...

This is a university exercise where I'm asked to draw a series of squares with user-defined columns an rows and with the colour (blue) progressively becoming lighter. To complicate things further , the squares must be ordered from darker to lighter in even rows (row 0 included) and in the other direction in odd ones, with the darkest square of each row being lighter than the lightest of the previous row.

I'm using pygame 1.9 with python 3.2.

Here's what I tried so far:

import pygame
rows = int(input('Rows? '))
cols = int(input('Columns? '))
colourstepblue = 255/(cols*rows) #defines how much lighter the squares
                                 #become at each iteration
pygame.init()                   
screen = pygame.display.set_mode((640,480))
screen.fill((255,255,255))
count = 0
for i in range(0,rows):
    for a in range(0,cols):
        if i%2 == 0:
            pygame.draw.rect(screen, (0, 0, (colourstepblue*( (a) * (i+1)))), (a*30, i*30, 29, 29))    
        else:
            pygame.draw.rect(screen, (0, 0, 255 - (i)*colourstepblue*a), (a*30, i*30, 29, 29))
    count += cols
pygame.display.flip()

(sorry if it says html I don't know how to have it say python)

This produces the right amount of squares in the right format, however I can't manage to get the colouring right. I'd be grateful for any advice you can give on getting this to work properly (although again this is an excercise so I'd rather not be given the code outright, just a tip to set me in the right direction).

Thanks for any answer and sorry for the long question!


Solution

  • One way to get the colors right is to generate them first, instead of calculating them as you go. You can do this easily with a list comprehension.

    If you are in python 2, you need to be careful when you divide. Make sure one of the numbers is a float to prevent python from rounding them to int. Also, you can omit the first parameter in range. It will default to 0.

    colourstepblue = 255.0/(cols*rows)
    colours = [x*colourstepblue for x in range(cols*rows)]
    

    Then, you can slice the list of colours. In the odd rows, you can slice the list in reverse. Also, you should consider using more descriptive variable names.

    for row in range(rows):
        if row % 2 == 0:
            row_colours = colours[row*rows:(row+1)*rows]
        else 
            row_colours = colours[(row+1)*rows:row*rows:-1]
        for col in range(cols):
            # row_colours[col] contains the colour you want