1
votes

I'm trying to draw functions and graphs using generators in Python (2.7.9), and found a problem: I can't flush my generated pixel data (RGB tuples) into a Pygame Pixel array. Here's my code (which i tryied to run):

  1. using 2d arrays

    pixArr = pygame.PixelArray(surface) pixArr=[[(0,0,function(x,y)) for x in range(1,screenX)] for y in range(1,screeny)] del pixArr

Here i've realized that pixArr isn't a ordinary 2d list becouse of my failure to output it (print pixArr)

  1. Then i've tryied using range

    pixArr[0:screenX*screenY] = [(0,0,function(curPix%screenX, curPix//screenY)) for curPix in range(0,screenX*screenY)]

I've found something like this code on pygame website HERE, but it gives me error "ValueError: sequence size mismatch", after playing around with it became clear that it works only with a single color (for example pixArr[0:screenX*screenY]=(0,0,255) colors the whole screen blue)

TL;DR: How can I set each pixel without using loops

For y in range(0,1000):
    For x in range(0,1000):
        gfx.draw(surface,x,y,(0,0,function(a,b))) #or pixArr in this line
1

1 Answers

0
votes

I'm using pygame 1.9.1, but it seems PixelArrays changed a lot on 1.9.2 so beware.

I just tried this example and it works fine:

pixArr = pygame.PixelArray(surface)
def f(i):
    return i % 255
pixArr[:] = [(0, 0, f(i)) for i in range(0, len(pixArr))]

One thing to notice is that doing:

pixArr = [(0, 0, f(i)) for i in range(0, len(pixArr))]

does NOT work because it converts the PixelArray variable into a list (as in your first snippet of code).

On why you are getting a ValueError, I just did some checks, and curiosly (and surpsiringly enough), I noticed that len(pixArray) is not equal to pixArray.surface.get_width() * pixArray.surface.get_height(). I recomend you to do some checks on this before you go on.

--

EDIT:

I thought about sharing this new snippet I got to because it seems very interesting:

def f(i):
    return i % 255
length = len(pixArr)
length2 = len(pixArr[0])
print length, length2
for j in range(0, length):
    array = [(0, f(j), f(i)) for i in range(0, length2)]
    pixArr[j] = array