NetLogo中使用tie的链接未正常工作问题排查
NetLogo 车辆跟随者绑定失效问题排查
目标是创建2辆主车(cars),每辆主车后方配置6个跟随者(followers),让跟随者在主车后方均匀排成队列,通过tie链接依次绑定,实现主车移动时拉动整个队列。但当前代码仅主车与最近的第一个跟随者的tie生效,后续跟随者无法被拉动。
用户提供的代码如下:
globals [small len_small ] breed [cars car] breed [followers follower] cars-own [reg no_foll len] followers-own [reg] to setup clear-all set small 2 set len_small 7 ask patches with [pycor >= 5 or pycor <= 1][set pcolor red] ask patches with [pycor = 4 ][set pcolor blue] ask patches with [ pycor = 2][set pcolor blue + 1] ask patches with [pycor = 3][set pcolor white] make_small reset-ticks end to go ask cars [forward 2] end to make_small create-cars small [move-to one-of patches with [pcolor = white ] set shape "circle" set color red set reg who set no_foll 0 set len len_small set heading one-of [90 270]] create-followers (len_small - 1) * small [ set shape "car" set color red move-to one-of cars with [color = red and no_foll < (len_small - 1)] set heading [heading] of one-of cars-here + 180 set reg [reg] of one-of cars-here ask one-of cars-here [set no_foll no_foll + 1]] form_small_car end to form_small_car ask followers with [color = red ] [while [any? other turtles-here with [reg = [reg] of myself]][forward 1]] ask cars with [color = red] [let foll_behind_list followers-on patch-ahead -1 let foll_behind one-of foll_behind_list with [reg = [reg] of myself] create-link-to foll_behind [tie]] ask followers with [color = red and any? followers-on patch-ahead -1] [let foll_behind_list followers-on patch-ahead -1 let foll_behind one-of foll_behind_list with [reg = [reg] of myself ] create-link-to foll_behind [tie]] end
核心问题分析
- 跟随者队列排列逻辑失效:当前仅让重叠的跟随者向前挪1步,无法让同组(同reg)的跟随者形成从主车开始依次向后的有序队列。所有跟随者初始都堆在主车格子,挪步后位置依然混乱,导致后续无法准确找到队列中的下一个跟随者。
- 链接创建逻辑随机且无序:
- 主车和跟随者创建链接时用
one-of随机选择,无法确保选中的是队列中紧跟主车的第一个跟随者; - 跟随者之间创建链接时,同样随机选择
patch-ahead -1格子里的跟随者,且因队列无序,该格子里可能没有同组的下一个跟随者,导致后续链接无法创建; - 没有按队列顺序依次绑定,而是所有海龟同时执行链接创建,无法形成“主车→跟随者1→跟随者2→…→跟随者6”的链式绑定。
- 主车和跟随者创建链接时用
修正方案
要实现有序队列和链式tie绑定,需先对每个reg组的主车和跟随者排序,再按顺序绑定并排列:
修改form_small_car过程如下:
to form_small_car ; 遍历每辆主车,处理其对应的跟随者组 ask cars [ ; 筛选出当前主车的同组海龟(主车+所有对应跟随者) let my-group (turtles with [reg = [reg] of myself]) ; 按到主车的距离排序,主车为第一个,跟随者由近到远排列 let sorted-group sort-by [ [a b] -> distance myself < distance myself ] my-group ; 依次给相邻海龟创建tie链接,并排列成队列 foreach range (length sorted-group - 1) [ i -> let front-turtle item i sorted-group let back-turtle item (i + 1) sorted-group ; 前面的海龟绑定后面的海龟,确保移动时能拉动 ask front-turtle [ create-link-to back-turtle [ tie ] ] ; 让后面的海龟移动到前面海龟的正后方1格,形成整齐队列 ask back-turtle [ face front-turtle forward 1 ] ] ] end
另外可优化make_small中跟随者的初始位置,避免全部堆在主车格子:
将创建跟随者的代码中move-to one-of cars...改为:
move-to patch-ahead -1 of one-of cars with [color = red and no_foll < (len_small - 1)]
这样初始时跟随者会落在主车后方格子,减少后续排序和移动的工作量。
内容的提问来源于stack exchange,提问作者Kevin A
相关产品推荐
相关产品推荐

