处理 - 为什么我的 Random Walker 总是倾向于左上角?

Processing - why does my Random Walker always tend toward the top left?

我目前正在阅读 Daniel Shiffman 的 'The Nature Of Code',并且一直在尝试第一个练习 - 一个简单的 'RandomWalker()'。我在 Java 中实现了类似的东西并且没有遇到任何问题,但是由于某种原因,我的助行器似乎总是或多或少地朝着相同的方向前进:

RandomWalker

这种情况 100% 都会发生。这是我的代码:

class Walker
{
  int x;
  int y;

  // Constructor

  Walker()
  {
    x = width / 2;
    y = height / 2;
  }

  void display()
  {
    stroke(0); // Colour
    point(x, y); // Colours one pixel in
  }

  void step()
  {
    float stepX;
    float stepY;

    stepX = random(-1, 1);
    stepY = random(-1, 1);

    x += stepX;
    y += stepY;
  }
}

Walker w;

void setup()
{
  size(640, 360);
  w = new Walker();
  background(255);
}

void draw()
{
  w.step();
  w.display();
}

这是随机函数的产物吗?我的第一个想法是它与函数的伪随机性质有关,但教科书明确指出这不应该引起注意,但这种情况每次都会发生。我想知道我的代码是否有问题?

提前致谢。

您的 xy 变量都是 int 类型。这意味着它们没有小数部分,因此无论何时您对它们进行加减,它们都会被截断。以下是一些示例:

int x = 1;
x = x + .5;
//1.5 is truncated, and x stays 1

int x = 1;
x = x - .5;
//.5 is truncated, and x becomes 0

这就是为什么您看到 xy 变量只在减少。要解决此问题,只需将 xy 更改为 float 类型,以便它们跟踪小数。

如果你真的需要 xyint 值,那么你需要 stepXstepY 也是 int 值:

int stepX;
int stepY;

stepX = (int)random(-5, 5);
stepY = (int)random(-5, 5);

x += stepX;
y += stepY;

但您可能只想将 xy 存储为 float 值。

PS:我喜欢漫游!