从数组中选择一个不等于当前值的随机值

时间:2016-09-20 04:52:47

标签: arrays logic processing

如何将变量的值与处理中的数组内容进行比较?基本上我有一系列颜色值。我有一个变量,是当前的颜色。我怎么说:"在这个键上按下:浏览这个颜色值数组,并选择一个不等于当前颜色的随机值。将该值指定为新的当前颜色?"

 
color[] colorArray  = {#000000,#FFC000,#E0FF00,#7EFF00};
color currentColor;
color randomColor;

void setup(){
    size(640,480);
    smooth();
    noStroke();
    currentColor = colorArray[0];
}

void draw(){
    background(currentColor);

}

void keyReleased(){
    if(key == 's'){
    println("currentColor: "+currentColor);
    for(int i =0; i < colorArray.length; i++){
      //println(colorArray[i]);
      if(currentColor != colorArray[i]){
        println(colorArray[i]);
        // what do i do here? Append to another array and loop through again?    
      }
    }
  }
}

2 个答案:

答案 0 :(得分:0)

也许索引颜色,只需更改为不同的索引。尝试以下代码,它在Processing中非常有效:

color[] colorArray  = {#000000,#FFC000,#E0FF00,#7EFF00};
int currentColor;

void setup(){
    size(640,480);
    smooth();
    noStroke();
    currentColor = 0;
}
void draw(){
    background(colorArray[currentColor]);
}
void keyReleased(){
    if(key == 's'){
    println("currentColor: "+currentColor);
    int newColor = currentColor;
    while (newColor == currentColor)
      newColor=(int) random(colorArray.length);
    currentColor = newColor;
  }
}

答案 1 :(得分:0)

我喜欢James Dunn的答案,但只是补充一点:这正是做什么循环的设计类型。

do-while至少执行一次代码,然后在条件为真时继续执行该代码。在您的情况下,您可以选择随机颜色,然后在新颜色与旧颜色相同时继续重复该操作。

这是一个小例子:

 
cts:near-query