【问题标题】:Assigning turtles into groups by color按颜色将海龟分组
【发布时间】:2025-05-05 07:55:01
【问题描述】:

Netlogo、* 和一般编程的新手。我想根据颜色将海龟分配给一个组,然后报告该组中的海龟数量。因此,我正在为海龟分配颜色:

设置颜色之一 [13 14 15 23 24 25 43 44 45 63 64 65 93 94 95]

我想要发生的是将彼此相距 2 位数以内的海龟分组在一起,例如颜色为 13、14 和 15 的海龟将被分组在一起。我还希望能够使用界面选项卡上的监视器报告组中的海龟数量。

【问题讨论】:

    标签: netlogo


    【解决方案1】:

    table 扩展具有美妙、超级有用的table:group-agents 原语,这正是您在这种情况下所需要的。

    这是一个如何使用它的示例:

    extensions [ table ]
    globals [ groups ]
    
    to setup
      clear-all
      create-turtles 100 [
        set color one-of [13 14 15 23 24 25 43 44 45 63 64 65 93 94 95]
      ]
      set groups table:group-agents turtles [ color - color mod 10 ]
      print groups
      foreach (range 10 100 10) [ g ->
        let turtles-in-group table:get-or-default groups g no-turtles
        print (word count turtles-in-group " turtles in group " g)
      ]
    end
    

    这里的重点是

    set groups table:group-agents turtles [ color - color mod 10 ]
    

    color - color mod 10 部分只是将 23 之类的颜色转换为 20 之类的“圆形”颜色的一个小技巧。与表达式具有相同值的海龟被放入同一组。运行此代码的结果将类似于:

    {{table: [[60 (agentset, 19 turtles)] [10 (agentset, 32 turtles)] [90 (agentset, 19 turtles)] [20 (agentset, 20 turtles)] [40 (agentset, 10 turtles)]]}}
    32 turtles in group 10
    20 turtles in group 20
    0 turtles in group 30
    10 turtles in group 40
    0 turtles in group 50
    19 turtles in group 60
    0 turtles in group 70
    0 turtles in group 80
    19 turtles in group 90
    

    如您所见,可以从表格中提取您需要的所有信息。如果您以前没有玩过牌桌,那么您应该熟悉一下牌桌的工作原理。

    我不知道你最后打算怎么做,但为你的海龟创建一个my-group 变量可能是值得的。假设你有

    turtles-own [ my-group ]
    

    在代码的顶部,您可以执行以下操作:

    foreach table:keys groups [ g ->
      ask table:get groups g [
        set my-group table:get groups g
      ]
    ]
    

    这样就可以轻松地执行以下操作:

    ask one-of turtles [ create-link-with one-of other my-group ]
    

    顺便说一下,如果您是 NetLogo 的新手,那么熟悉链接也是一件好事。

    当我与属于组的海龟一起工作时,我经常使用groups 龟品种来表示该组,并在单个海龟和它们所属的组之间建立联系。如果您有需要跟踪的“组级别”属性,这将特别有用。我很乐意对此进行扩展,但我认为这已经超出了这个特定答案的范围......

    【讨论】: