开发者社区 问答 正文

为什么收到“索引超出范围错误”?

当我在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()

展开
收起
游客6qcs5bpxssri2 2019-08-27 23:04:15 991 分享 版权
1 条回答
写回答
取消 提交回答
  • 你得到超出范围的错误,因为x并且y永远不会重置为0,并且在pixels[]每个颜色通道没有一个color()元素的字段中,每个像素有一个元素:

    index = x + y*width pixels[index] = color(rand, rand, rand) 您对设置x=0和y=0相应的循环之前,你已经递增x,并y在循环的结尾:

    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))) 您还可以简化代码。相反的i,并j可以使用x和y直接。例如:

    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()

    2019-08-27 23:06:48
    赞同 展开评论
问答分类:
问答地址: