首页 > 解决方案 > P5js 显示递归发生

问题描述

我在 p5js 中搞乱了递归,我想知道是否有可能显示递归正在发生。例如,我将使用 p5js 网站上提供的代码:

function setup() {
  createCanvas(720, 400);
  noStroke();
  noLoop();
}

function draw() {
  drawCircle(width / 2, 280, 6);
}

function drawCircle(x, radius, level) {
  const tt = (126 * level) / 4.0;
  fill(tt);
  ellipse(x, height / 2, radius * 2, radius * 2);
  if (level > 1) {
    level = level - 1;
    drawCircle(x - radius / 2, radius / 2, level);
    drawCircle(x + radius / 2, radius / 2, level);
  }
}

它运行它并立即显示所有内容。有没有办法可以改变它,让它显示每个单独的圆圈形成?

标签: recursiondisplay

解决方案


这可能不是最干净的方法,但您可以将每个递归步骤存储为匿名函数,并在每次draw调用时迭代这些函数。

function setup() {
  createCanvas(720, 400);
  noStroke();
  frameRate(1);
  nextLevel=[];
  nextLevel.push(() => drawCircle(width / 2, 280, 6));
}

function draw() {
  thisLevel = [...nextLevel]
  nextLevel = []
  for(func of thisLevel){
    func()
  }
}

function drawCircle(x, radius, level) {
  const tt = (126 * level) / 4.0;
  fill(tt);
  ellipse(x, height / 2, radius * 2, radius * 2);
  if (level > 1) {
    level = level - 1; 
    nextLevel.push(() => drawCircle(x - radius / 2, radius / 2, level));
    nextLevel.push(() => drawCircle(x + radius / 2, radius / 2, level));
  }
}

这将导致这个可视化:

在此处输入图像描述


推荐阅读