P5.JS 随机游走总是在顶部边界结束

P5.JS Random Walk Always Ends Up On the Top Border

我正在学习 P5.JS“代码的本质”,并尝试第一个示例代码。

https://github.com/nature-of-code/noc-examples-p5.js/tree/master/chp00_introduction/NOC_I_01_RandomWalkTraditional

  let walker;
    
    let bg_color_x = 255;
    let bg_color_y = 51;
    let bg_color_z = 153;
    
    let stroke_color_x = 51;
    let stroke_color_y = 51;
    let stroke_color_z = 204;
    let stroke_weight = 10;
    
    let random_number_for_walking = 5;
    
    function setup() {
      var cnv = createCanvas(windowWidth, windowHeight);
      cnv.style('display', 'block');  
      background(bg_color_x, bg_color_y, bg_color_z);
    
      walker = new Walker();  
    }
    
    
    function draw() {
      walker.step();
      walker.render();
    }
    
    class Walker {
      constructor() {
        this.x = width / 2;
        this.y = height / 2;
      }
    
      render() {
       
        stroke(stroke_color_x, stroke_color_y, stroke_color_z);
        strokeWeight(stroke_weight);    
        point(this.x, this.y);
      }
    
      step() {
        var choice = floor(random(random_number_for_walking));
        if (choice === 0) {
          // this.x++;
          this.x = this.x + stroke_weight;
        } else if (choice == 1) {
          // this.x--;
          this.x = this.x - stroke_weight;      
        } else if (choice == 2) {
          // this.y++;
          this.y = this.y + stroke_weight;      
        } else {
          // this.y--;
          this.y = this.y - stroke_weight;      
        }
        this.x = constrain(this.x, 0, width - stroke_weight);
        this.y = constrain(this.y, 0, height - stroke_weight);
      }
    }
    
    
    function windowResized() {
      resizeCanvas(windowWidth, windowHeight);
      background(bg_color_x, bg_color_y, bg_color_z);
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>

不过,不管我运行多少次了,艺术都稳居榜首window。比如像这样。

我该如何解决这个问题?有没有办法让它在碰到四个边界之一时向左或向右移动?

你的random_number_for_walking错了!

您的步进函数有 4 个路径:

step() {
    var choice = floor(random(random_number_for_walking));

    if (choice === 0) {
        // Right
    } else if (choice == 1) {
        // Left
    } else if (choice == 2) {
        // Down
    } else {
        // Up
    }

    // ...
}

但是你的 random_number_for_walking 是 5 而 random(number) 给你一个介于 [0, number) 之间的数字,所以在你的情况下:0, 1, 2, 3, 4.

如果你仔细观察,你不会处理 choice == 3,而 else 你实际上处理的是 choice == 3 || choice == 4

这使得您的 Walker 上升而不是下降的可能性更大。

正确处理最后的选择并将 random_number_for_walking 减少到 4 将解决问题。