gpt4 book ai didi

java - 处理:为什么这个Walker对象不绘制?

转载 作者:行者123 更新时间:2023-12-01 16:18:43 24 4
gpt4 key购买 nike

我正在完成《代码本质》中的一项练习,其中涉及将现有程序转换为包含 vector 。我正在使用的原始代码是 Walker 对象的代码,该对象在“随机游走”期间倾向于向右:

https://github.com/nature-of-code/noc-examples-processing/blob/master/introduction/Exercise_I_1_WalkerTendsToDownRight/Walker.pde

根据我到目前为止所写的内容,当我尝试运行代码时,“草图”选项卡会打开,但不会绘制任何内容。

程序声明 Walker 对象的 x 和 y 分量,添加它们,然后渲染。然后是以下内容:

   void step() 
{
int rx = int(random(1));
int ry = int(random(1));

if (rx < 0.4)
{
x++;
} else
if (rx < 0.5)
{
x--;
}
else
if (ry < 0.9)
{
y++;
}
else
{
y--;
}

}
}

Walker w;
Walker location;
Walker velocity;

void setup()
{
size(200, 200);
background(255);
Walker w = new Walker(5, 5);
Walker location = new Walker(100, 100);
Walker velocity = new Walker(2.5, 3);
}

void draw()
{
location.add(velocity);
w.step();
w.render();

}

最佳答案

我假设您正在 Chapter 1 of the Nature of Code book 中进行此练习:

Exercise 1.2

Take one of the walker examples from the introduction and convert it to use PVectors.

所以你想从 WalkerTendsToDownRight example 开始并使用 vector ,对吗?保存步行者位置的 x 和 y int 字段可以用 vector 替换。我认为主要的草图代码可以保持不变。 walker 代码可能如下所示:

class Walker {
PVector location;

Walker() {
location = new PVector(width / 2, height / 2);
}

void render() {
stroke(0);
strokeWeight(2);
point(location.x, location.y);
}

// Randomly move right (40% chance), left (10% chance),
// down (40% chance), or up (10% chance).
void step() {
float randomDirection = random(1);

if (randomDirection < 0.4) {
location.x++;
} else if (randomDirection < 0.5) {
location.x--;
} else if (randomDirection < 0.9) {
location.y++;
} else {
location.y--;
}

location.x = constrain(location.x, 0, width - 1);
location.y = constrain(location.y, 0, height - 1);
}
}

Walker with vector example在 GitHub 上,他们还使用了一个 vector 来存储步行者将做出的 Action 。通过这种方法,步进函数可能会短得多(同时保持向右和/或向下移动的偏好):

void step() {
PVector move = new PVector(random(-1, 4), random(-1, 4));
location.add(move);

location.x = constrain(location.x, 0, width - 1);
location.y = constrain(location.y, 0, height - 1);
}

如果您希望步行者继续小步前进,您甚至可以添加对 limit 函数的调用:

move.limit(1);

关于java - 处理:为什么这个Walker对象不绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62331822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com