有没有办法将线从一个地方随机移动到另一个地方?

Is there a way to move lines from one place to another randomly?

实际上我正在尝试将此 JavaScript 代码转换为处理代码。但是卡住了。

var leftToRight = Math.random() >= 0.5;

    if(leftToRight) {
      context.moveTo(x, y);
      context.lineTo(x + width, y + height);    
    } else {
      context.moveTo(x + width, y);
      context.lineTo(x, y + height);
    }

    context.stroke();

这是我想出来的,我知道它从根本上是错误的,但一定有办法。如果有人至少能指出我正确的方向,那就太好了。

void draw() {
  line(x1, y1, x2, y2);
  for(int i = 0; i < 1000; i++) {
    if(x1 == 0) {
      x1 = width;
      y1 = 0;
      x2 = 0;
      y2 = height;
      line(x1, y1, x2, y2);
    } else if(x1 == width) {
      x1 = 0;
      y1 = 0;
      x2 = width;
      y2 = height;
      line(x1, y1, x2, y2);
  }        
}

由于您问题的性质,很难假设您确切需要回答什么。为简单起见,我假设您希望将 Java 代码转换为 Processing。因此,我将忽略您在第二个代码片段中所写的内容。

Java 代码主要执行以下操作:

  1. 生成一个从 0.0 到 1.0 的随机数
  2. 根据数字是否大于 0.5 选择一个输出:
    • 创建一条从 (x, y) 到 (x + width, y + height) 或
    • 创建一条从 (x + width, y) 到 (x, y + height) 的直线。

这是一个处理代码示例,可以帮助您完成此操作。此代码与您提供的 Java 片段的代码非常接近,因为这正是您所要求的。

int x = 0, y = 0;

if(random(0, 1) > 0.5) line(x, y, x + width, y + height);
else line(x + width, y, x, y + height);

当 运行 时,canvas 将显示:

或者这个:

希望对您有所帮助。