Java 在加工过程中生成随机矩形
我想在处理过程中随机生成矩形。到目前为止,我使用循环来创建窗口大小的矩形,但我不知道如何随机创建10个矩形。以下是我为您提供的示例代码:Java 在加工过程中生成随机矩形,java,for-loop,processing,Java,For Loop,Processing,我想在处理过程中随机生成矩形。到目前为止,我使用循环来创建窗口大小的矩形,但我不知道如何随机创建10个矩形。以下是我为您提供的示例代码: void setup() { size(400, 400); } void draw() { background(0); // Black Background stroke(255); // White lines for (int j = 0; j <= height; j += 40) { for (int i
void setup()
{
size(400, 400);
}
void draw()
{
background(0); // Black Background
stroke(255); // White lines
for (int j = 0; j <= height; j += 40)
{
for (int i = 0; i < width; i += 40)
{
fill(0);
rect(i, j, 40, 40);
}
}
}
void setup()
{
尺寸(400400);
}
作废提款()
{
背景(0);//黑色背景
笔划(255);//白线
对于(int j=0;j有多种方法来解决这个有趣的家庭作业/练习
第一件事是为每列绘制正确数量的框:
void setup()
{
size(400, 400);
background(0); // Black Background
fill(0);
stroke(255); // White lines
int boxSize = 40;
int maxBoxes = 1;
for (int j = 0; j <= height; j += boxSize)
{
// box count per row
int boxCount = 0;
for (int i = 0; i < width; i += boxSize)
{
// only draw the max number of boxes
if(boxCount < maxBoxes){
rect(i, j, 40, 40);
// increment per row box count
boxCount++;
}
}
// increment max boxes per box
maxBoxes++;
}
}
我不是100%清楚您在这里尝试的是什么,但我认为在进入内部循环的100次中,您只想创建一个矩形10次。在决定是否创建矩形之前,在if子句中使用Math.random可以获得最大10次,例如if(Math.random()*10==1)然后保留一个计数器,在if子句中检查以避免>10。但是随机数可能不会得到10,可能是9,甚至更少。因此最好将此循环一次-迭代10次,每次使用随机数乘以400以获得坐标,但也要跟踪矩形的放置位置,以便在随机数大于400时重试坐标将与现有矩形重叠有点复杂但有趣,最好将现有矩形坐标列表提取到一个单独的类中,这样您就可以使用类似willOverlap(x,y,width,height)的方法你每次出来时都会打电话给潜在的协调人Hello@Chris谢谢你的全力回答,但数学方法在处理过程中不可用,willOverlap方法也不可用:/
void setup()
{
size(400, 400);
background(0); // Black Background
fill(0);
stroke(255); // White lines
int boxSize = 40;
int maxBoxes = 1;
int totalBoxes = width / boxSize;
for (int j = 0; j <= height; j += boxSize)
{
// box count per row
int boxCount = 0;
// a list of box indices of where to draw a box (as opposed
int[] randomXIndices = new int[maxBoxes];
// how many index ranges to span per row
int indexRangePerBox = totalBoxes / maxBoxes;
// for each random index
for(int k = 0 ; k < maxBoxes; k++)
{
// pre-calculate which random index to select
// using separate ranges per box to avoid overlaps
randomXIndices[k] = (int)random(indexRangePerBox * k, indexRangePerBox * (k + 1));
}
for (int i = 0; i < width; i += boxSize)
{
// only draw the max number of boxes
if(boxCount < maxBoxes)
{
int randomX = randomXIndices[boxCount] * boxSize;
rect(randomX, j, 40, 40);
// increment per row box count
boxCount++;
}
}
// increment max boxes per box
maxBoxes++;
}
}
void draw(){
}
void mousePressed(){
setup();
}