NetLogo路网模型中Turtle无法移动的代码修复求助
问题:NetLogo中实现海龟沿Shapefile路网移动的代码修复
刚入门NetLogo,正在开发基于主体的模型(Agent-based Model),已准备2个Shapefile并成功加载,但无法实现Turtle沿路网地图移动,请求给出实现思路并修复代码。
现有代码
extensions [gis] breed [cars car] turtles-own [destination] globals [ states-dataset car-blue] to custom-clear reset-ticks clear-turtles clear-patches clear-drawing clear-all-plots end to setup clear-all custom-clear ask patches [set pcolor green - 3] set states-dataset gis:load-dataset "C:/Users/ADMIN/Documents/QGIS/Export Netlogo/Format .shp/state.shp" gis:set-world-envelope gis:envelope-of states-dataset gis:set-drawing-color yellow gis:draw states-dataset 1 set route-car-blue gis:load-dataset "C:/Users/ADMIN/Desktop/routefiles/Shapefile/car/route-car-blue.shp" gis:set-drawing-color blue gis:draw angkot-permatabiru 1.5 foreach gis:feature-list-of route-car-blue [car-pb -> let location gis:location-of gis:centroid-of car-pb create-turtles 5 [ set xcor item 0 location set ycor item 1 location set shape "car" set size 1 ]] end to go ask turtles [ let new-location one-of [link-neighbors] of destination move-to new-location set destination new-location] tick end
实现思路
- 将路网Shapefile的线要素转换为NetLogo的节点(node)海龟和链接(link),构建可通行的图结构,这是海龟沿路网移动的核心基础
- 初始化每个移动海龟的
destination变量,指定其在路网中的起点节点 - 修正代码中的变量名错误(如
angkot-permatabiru应为route-car-blue),清理未使用的全局变量 - 移动逻辑改为基于路网节点的邻居链接,让海龟沿链接移动到相邻节点
修复后的完整代码
extensions [gis] breed [cars car] breed [nodes node] ; 新增节点 breed,用于表示路网的节点 turtles-own [destination] globals [ states-dataset route-car-blue] ; 修正全局变量名 to custom-clear reset-ticks clear-turtles clear-patches clear-drawing clear-all-plots end to setup clear-all custom-clear ask patches [set pcolor green - 3] ; 加载并绘制区域底图 set states-dataset gis:load-dataset "C:/Users/ADMIN/Documents/QGIS/Export Netlogo/Format .shp/state.shp" gis:set-world-envelope gis:envelope-of states-dataset gis:set-drawing-color yellow gis:draw states-dataset 1 ; 加载路网Shapefile并转换为节点和链接 set route-car-blue gis:load-dataset "C:/Users/ADMIN/Desktop/routefiles/Shapefile/car/route-car-blue.shp" gis:set-drawing-color blue gis:draw route-car-blue 1.5 ; 修正变量名错误 ; 将路网线要素转换为节点和链接 gis:create-nodes links route-car-blue ; 自动创建节点和链接 ask nodes [set shape "circle" set size 0.5 set color gray] ; 设置节点样式 ; 在路网节点上创建移动的海龟(cars) let all-nodes nodes ; 获取所有路网节点 foreach n-values 5 [i -> ; 创建5辆小车 create-cars 1 [ set shape "car" set size 1 set color red move-to one-of all-nodes ; 随机选择一个节点作为起点 set destination one-of link-neighbors ; 初始化目标为相邻节点 ] ] end to go ask cars [ if destination != nobody [ ; 确保目标节点存在 move-to destination ; 移动到目标节点 ; 更新下一个目标:从当前节点的邻居中随机选一个(避免回头可加额外条件) set destination one-of link-neighbors ] ] tick end
关键修改说明
- 新增
nodesbreed用于表示路网的节点,通过gis:create-nodes links route-car-blue自动将路网线转换为节点和链接 - 修正了
gis:draw中的变量名错误(angkot-permatabiru改为route-car-blue) - 初始化小车时,将其放置在路网节点上,并设置初始
destination为相邻节点 - 移动逻辑改为基于节点的
link-neighbors,确保海龟沿路网的链接移动
内容的提问来源于stack exchange,提问作者Fadhlin Azmi
相关产品推荐
相关产品推荐

