java - 有没有办法随机化 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);
}
}
解决方案
如果你想通过一个随机值前进,那么你必须增加控制变量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));
}
当然,有些可能必须具有相同的坐标,但是对于这么多的点,这不应该引起注意。
推荐阅读
- c++ - 为什么我们需要不同的#include 指令?
- javascript - Javascript滚动闪烁
- c - 在 C 中编写 bmp 文件时得到模糊的结果
- python - 如何在 Python matplotlib 中绘制实时移动圆
- electron - 在 Electron 中打开 sqlite3 数据库
- reactjs - 尝试渲染组件时类型无效
- python - 如何在 Python dash 的侧边栏中添加图标
- sockets - SNMP Passthru 问题看不到返回值
- laravel - laravel-inertia 中的 vue-moment 问题
- flutter - 掌握颤振包装布局