for循环中随机数不改变

Random Number doesn't change in for loop

我有一个 for 循环,可以在特定方向绘制线条。在 for 循环中,我想使用随机数更改线条的颜色。但由于某种原因,它不起作用。

代码如下:

for (var i = 0; i < 11; i++) {
  random1 = randomNumber(0, 255);
  random2 = randomNumber(0, 255);
  random3 = randomNumber(0, 255);
  
  stroke(rgb(random1, random2, random3));
  liftUp();
  backward(100);
  turnLeft(45);
  forward(200);
  random1 = randomNumber(0, 255);
  random2 = randomNumber(0, 255);
  random3 = randomNumber(0, 255);
  
  stroke(rgb(random1, random2, random3));
  liftDown();
  backward(150);
  turnRight(45);
  forward(150);
  turnRight(135);
  forward(150);
}

不确定,但这是我的分析

您正在使用相同的变量,random1, 2, 3 绘制两条不同的线。

我不知道 stroke() 应该如何划线,但由于您正在更改 random1, 2, 3 以便将它们重新用于第二个 stroke() 方法,因此您将更改参考第一笔画,这可能会导致在同一行上拖两次。

+ 你似乎在 for 循环之外声明了这个变量。

以下可能是快速解决方法

编辑:您可以使用下面摘自 this question

的第一个或第二个 randomNumber() 函数
/**
 * Returns a random number between min (inclusive) and max (exclusive)
 */
function randomNumber(min, max) {
    return Math.random() * (max - min) + min;
}

/**
 * Returns a random integer between min (inclusive) and max (inclusive).
 * The value is no lower than min (or the next integer greater than min
 * if min isn't an integer) and no greater than max (or the next integer
 * lower than max if max isn't an integer).
 * Using Math.round() will give you a non-uniform distribution!
 */
function randomNumber(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

for (var i = 0; i < 11; i++) {
  
  stroke(rgb(randomNumber(0, 255), randomNumber(0, 255), randomNumber(0, 255)));
  liftUp();
  backward(100);
  turnLeft(45);
  forward(200);
  
  stroke(rgb(randomNumber(0, 255), randomNumber(0, 255), randomNumber(0, 255)));
  liftDown();
  backward(150);
  turnRight(45);
  forward(150);
  turnRight(135);
  forward(150);
}

没有测试,但这是解决您问题的唯一合乎逻辑的方法。

我喜欢@Raphael Balet 的开头,但我会进一步编辑。我假设你在 AppLab

这里的一般参考是 Code.org 的 randomNumber() API

带注释的旧代码

for (var i = 0; i < 11; i++) {
  stroke(rgb(randomNumber(0, 255), randomNumber(0, 255), randomNumber(0, 255)));
  //since lifting up no line drawn till pen placed back down
  liftUp();
  //So this code does nothing but reposition pen (so color #1 never seen :-(  )
  backward(100);
  turnLeft(45);
  forward(200);
  
  //New color
  stroke(rgb(randomNumber(0, 255), randomNumber(0, 255), randomNumber(0, 255)));
  //Pen down so will see output
  liftDown();
  backward(150);
  turnRight(45);
  forward(150);
  turnRight(135);
  forward(150);
}

新代码

for (var i = 0; i < 11; i++) {
  //reposition pen, needed?
  backward(100);
  turnLeft(45);
  forward(200);

  //Set Color
  var r = randomNumber(0, 255);
  var g = randomNumber(0, 255);
  var b = randomNumber(0, 255);
  stroke(rgb(r, g, b));

  //lower drawing implement
  liftDown();
  //Drive!
  backward(150);
  turnRight(45);
  forward(150);
  turnRight(135);
  forward(150);
}