如何在 Netlogo 中报告邻居的值?
How to report value of neighbor in Netlogo?
我正在尝试创建一个列表,以收集报告海龟邻居颜色的行为空间。
to-report north-color1
set north-color []
foreach sort turtles [the-turtle -> set north-color lput [color] of neighbors4 north-color]
report north-color
end
"foreach" 行是为了确保列表的顺序遵循 turtle 0、turtle 1、turtle 2 等的顺序。但是,我希望我的列表输出上面邻居的颜色,例如 [10, 20, 10, 20, 30...] 我该如何实现?
这是一个完整的模型。只需将 print north-color-map
更改为 print north-color
即可试用 foreach
版本。
to testme
clear-all
ask patches [if random-float 1 < 0.8 [sprout 1]]
print north-color-map
end
to-report north-color
let outlist []
foreach sort-on [who] turtles
[ this-turtle -> ifelse any? turtles-on [patch-at 0 1] of this-turtle
[ set outlist lput [color] of one-of turtles-on [patch-at 0 1] of this-turtle outlist ]
[ set outlist lput "none" outlist ]
]
report outlist
end
to-report north-color-map
report map
[ this-turtle -> ifelse-value any? turtles-on [patch-at 0 1] of this-turtle
[ [color] of one-of turtles-on [patch-at 0 1] of this-turtle ]
[ "none" ]
]
sort-on [who] turtles
end
foreach
版本可能更容易理解。它非常接近您尝试做的事情 - 从一个空列表开始,然后 运行 按 who
顺序遍历所有海龟的列表(sort-on [who] turtles
创建该列表)并计算北面海龟的颜色。寻找北方是用 patch-at 0 1
完成的,但你还必须说出北方 - 因此 [patch-at 0 1] of this-turtle
。而 one-of
是那个补丁上所有海龟集合中的 select 一只海龟 - NetLogo 不能说它总是有一个或 none 所以你基本上会得到一个错误说'我不知道要找到哪只乌龟的颜色'。
第二个版本使用map
。它的作用完全相同,但将函数应用于列表的所有成员而不显式构造循环。代码稍微简单一些,因为您不需要空列表和各种 lput
语句。您还需要将所有内容呈现为记者而不是命令。但是 map
可能有点棘手。
我正在尝试创建一个列表,以收集报告海龟邻居颜色的行为空间。
to-report north-color1
set north-color []
foreach sort turtles [the-turtle -> set north-color lput [color] of neighbors4 north-color]
report north-color
end
"foreach" 行是为了确保列表的顺序遵循 turtle 0、turtle 1、turtle 2 等的顺序。但是,我希望我的列表输出上面邻居的颜色,例如 [10, 20, 10, 20, 30...] 我该如何实现?
这是一个完整的模型。只需将 print north-color-map
更改为 print north-color
即可试用 foreach
版本。
to testme
clear-all
ask patches [if random-float 1 < 0.8 [sprout 1]]
print north-color-map
end
to-report north-color
let outlist []
foreach sort-on [who] turtles
[ this-turtle -> ifelse any? turtles-on [patch-at 0 1] of this-turtle
[ set outlist lput [color] of one-of turtles-on [patch-at 0 1] of this-turtle outlist ]
[ set outlist lput "none" outlist ]
]
report outlist
end
to-report north-color-map
report map
[ this-turtle -> ifelse-value any? turtles-on [patch-at 0 1] of this-turtle
[ [color] of one-of turtles-on [patch-at 0 1] of this-turtle ]
[ "none" ]
]
sort-on [who] turtles
end
foreach
版本可能更容易理解。它非常接近您尝试做的事情 - 从一个空列表开始,然后 运行 按 who
顺序遍历所有海龟的列表(sort-on [who] turtles
创建该列表)并计算北面海龟的颜色。寻找北方是用 patch-at 0 1
完成的,但你还必须说出北方 - 因此 [patch-at 0 1] of this-turtle
。而 one-of
是那个补丁上所有海龟集合中的 select 一只海龟 - NetLogo 不能说它总是有一个或 none 所以你基本上会得到一个错误说'我不知道要找到哪只乌龟的颜色'。
第二个版本使用map
。它的作用完全相同,但将函数应用于列表的所有成员而不显式构造循环。代码稍微简单一些,因为您不需要空列表和各种 lput
语句。您还需要将所有内容呈现为记者而不是命令。但是 map
可能有点棘手。