为什么我会收到 'Index out of range error'?

Why do I receive an 'Index out of range error'?

当我 运行 Processing.py 中的以下代码时,出现索引超出范围错误,我无法弄清楚原因。感谢所有帮助。

x = 0
y = 0
rand = random(255)

def setup():
   size(200, 200)


def draw():
    global x, y, rand
    loadPixels()
    for i in range(0, width):
        x += 1
        for j in range(0, height):
            y += 1
            index = (x + y*width)*4
            pixels[index + 0] = color(rand)
            pixels[index + 1] = color(rand)
            pixels[index + 2] = color(rand)
            pixels[index + 3] = color(rand)
    updatePixels()

您会收到超出范围的错误,因为 xy 永远不会重置为 0,并且在每个像素的 pixels[] there is not one element for each color channel, there is one color() 元素字段中:

index = x + y*width
pixels[index] = color(rand, rand, rand)

你必须在相应的循环之前设置 x=0y=0 并且你必须在循环结束时增加 xy:

def draw():
    global x, y, rand
    loadPixels()
    x = 0 
    for i in range(0, width):
        y = 0
        for j in range(0, height):
            index = x + y*width
            pixels[index] = color(rand, rand, rand)
            y += 1
        x += 1
    updatePixels()

如果要为每个像素生成随机颜色,则必须为每个像素的每个颜色通道生成一个随机值:

pixels[index] = color(random(255), random(255), random(255))

pixels[index] = color(*(random(255) for _ in range(3)))

您还可以进一步简化代码。您可以直接使用 xy 而不是 ij。例如:

def draw():
    loadPixels()
    for x in range(width):
        for y in range(height):
            pixels[y*width + x] = color(random(255), random(255), random(255))
    updatePixels()