如何在Netlogo中报告邻居的价值?

问题描述 投票:0回答:1

我试图创建一个列表,用行为空间来收集,报告乌龟邻居的颜色,"foreach "行是确保列表的顺序按照乌龟0,乌龟1,乌龟2等顺序。

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 "行是为了确保列表的顺序按照乌龟0,乌龟1,乌龟2等顺序排列。但是,我想让我的列表输出它们上面邻居的颜色,比如[10, 20, 10, 20, 30...]我如何才能实现这个目标?

netlogo
1个回答
1
投票

这是一个完整的模型。只要改变 print north-color-mapprint 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 是从该补丁上的所有海龟集合中选择一只海龟--NetLogo无法判断它总是有一只或没有,所以你会得到一个错误,基本上是说 "我不知道该找哪只海龟的颜色"。

第二个版本使用 map. 它的做法完全一样,但将函数应用于列表中的所有成员,而不显式地构建循环。这段代码比较简单,因为你不需要空列表和各种不同的 lput 语句。你还需要把所有的东西都以报告人的形式呈现,而不是命令。但是 map 可以是一个有点棘手的,让你的头。

© www.soinside.com 2019 - 2024. All rights reserved.