recursion - 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);
}
}
它运行它并立即显示所有内容。有没有办法可以改变它,让它显示每个单独的圆圈形成?
解决方案
这可能不是最干净的方法,但您可以将每个递归步骤存储为匿名函数,并在每次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));
}
}
这将导致这个可视化:
推荐阅读
- java - 从 java 代码执行 shell 脚本并将终端的输出附加到 .txt 文件
- firebase - 为管理员使用 Firebase 自定义声明(Firestore 和云存储)
- spring-boot - 警告:bounce_queue_lifetime 大于 maximal_queue_lifetime - 调整bounce_queue_lifetime
- ruby-on-rails - 将自定义域分配给 S3 存储桶
- javascript - 在 javascript 中重命名 JSON 键
- c# - 将多个字典合二为一
- ios - 字体(Marion 字体)未显示在 XCode 的字体系列中
- javascript - p-dropdown 未正确显示标签
- sharepoint - Microsoft 图形和 Azure Ad 用户身份验证
- android - React-Native:Listview 仅在 IOS 中不滚动到屏幕底部