我需要一个 for 循环来在给定范围(1 到 5)之间随机增加。 我已经尝试了以下一组代码,但它似乎不起作用。该代码是为基于Java的Processing编写的。我的目的是创建一个 Canvas ,其中具有与背景不同颜色的随机点,以获得类似纸张的纹理。
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);
}
}
最佳答案
如果你想以随机值前进,那么你必须随机增加控制变量x
和y
:
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));
}
当然,有些可能必须具有相同的坐标,但对于这么多的点来说,这应该不会引起注意。
关于java - 有没有办法使for循环中的循环增加随机化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60107689/