首页 > 解决方案 > 有没有办法随机化 for 循环中的循环增加?

问题描述

我需要一个 for 循环在给定范围(1 到 5)之间随机增加。我已经尝试了以下一组代码,但它似乎不起作用。此代码是为基于 Java 的处理编写的。我的目的是创建一个与背景不同颜色的随机点的画布,以获得类似纸的纹理。

float x = 0;
float y = 0;
float xRandom = x + random(1, 5);
float yRandom = y + random(1, 5);

void setup() {
  size(800, 800);
}

void draw() {
  background(#e8dacf);
  for(float x; x <= width; xRandom){
    for (float y ; y <= height; yRandom){
      fill(#f0e2d7);
      stroke(#f0e2d7);
      point(x, y);
    }
  }

标签: javaloopsprocessing

解决方案


如果你想通过一个随机值前进,那么你必须增加控制变量xy随机:

for (float x=0; x <= width; x += random(1, 5)){

    for (float y=0; y <= height; y += random(1, 5)){

        fill(#f0e2d7);
        stroke(#f0e2d7);
        point(x, y);
    }
}

请注意,在这种分布中,点与列对齐,因为 x 坐标在内部循环迭代时保持不变。
对于完全随机分布,您必须在单个循环中计算随机坐标。例如:

int noPts = width * height / 9;
for (int  i = 0; i < noPts; ++i ){

   fill(#f0e2d7);
   stroke(#f0e2d7);
   point(random(1, width-1), random(1, height-1));
}

当然,有些可能必须具有相同的坐标,但是对于这么多的点,这不应该引起注意。


推荐阅读