NetLogo无人机模型优化:解决堆叠及异常位移问题
无人机堆叠与强制位移问题修复方案
核心问题
- 无人机(暂命名为
people)出现堆叠在同一白色斑块的情况 - 修改代码后虽能避免堆叠,但已停留在空闲斑块的无人机被强制移动,无法稳定停留
问题根源
- 原目标选择逻辑是瞬时判断:多个无人机可能同时选中同一个“当前无人”的斑块,后续移动后造成堆叠。
- 更新后的代码在接近目标时才检查冲突,此时无人机已临近目标,切换目标会导致已停留的无人机被强制位移——只要附近有其他无人机就触发重新选目标,忽略了自身已稳定停留的状态。
修复方案
1. 新增斑块占用标记,避免目标冲突
给斑块添加is-occupied?属性,标记是否被无人机占用,从根源上避免多无人机选中同一斑块。
2. 优化停留逻辑,禁止强制位移
仅在未到达目标且目标已被占用时切换目标;已稳定停留的无人机,只要满足电量条件,就保持不动,不触发目标切换。
修改后的完整代码
breed [people person] people-own [target energy] patches-own [is-occupied?] ;; 新增斑块占用状态标记 breed [houses house] to setup clear-all set-default-shape houses "house" setup-patch ;; 创建中心充电房屋 create-houses 1 [ setxy 0 0 set size 2 ] create-people number-of-people [ setxy random-xcor random-ycor set target one-of houses set energy 100 face target set color blue ] reset-ticks end to setup-patch let white-patch-count 0 ask patches [ set pcolor green set is-occupied? false ;; 初始化斑块为未占用状态 if random-float 1 < 0.2 and white-patch-count < number-of-patches [ if not any? other patches in-radius radius-size with [pcolor = white] [ set pcolor white set white-patch-count white-patch-count + 1 ] ] ] end to go ask people [ ;; 每tick消耗1点电量 set energy energy - 1 if energy <= 0 [ die ] ;; 到达目标后的行为逻辑 if distance target = 0 [ ifelse pcolor = white [ ;; 标记当前斑块为已占用 ask target [ set is-occupied? true ] ifelse energy > energy-level [ stay-at-patch ] [ ;; 离开斑块时取消占用标记 ask target [ set is-occupied? false ] set target one-of houses face target ] ] [ ;; 在充电房屋完成充电后,选择未被占用的白色斑块 set target one-of patches with [pcolor = white and not is-occupied?] face target ] ] ;; 移动逻辑:仅在未到达目标时检查冲突 ifelse distance target < 1 [ ;; 仅当目标是白色斑块且已被占用、且自身未到达时,重新选择目标 if pcolor = white and [is-occupied?] of target and not (distance target = 0) [ set target one-of patches with [pcolor = white and not is-occupied?] face target ] else [ move-to target if any? houses-here [ set energy 100 ] ] ] [ fd 1 ] ] tick end to stay-at-patch ;; 电量降至30时返回充电,离开前取消斑块占用标记 if energy = 30 [ ask target [ set is-occupied? false ] set target one-of houses face target ] end
关键修改说明
- 斑块新增
is-occupied?属性,实现目标斑块的排他性选择,从根源避免堆叠。 - 无人机到达白色斑块时标记占用,离开(返回充电)时取消标记,确保斑块状态实时更新。
- 仅在未到达目标且目标已被占用时触发目标切换,已稳定停留的无人机不会被强制移动。
- 充电完成后选择目标时,仅筛选未被标记为占用的白色斑块。
额外建议
- 后续可将
people重命名为drones,提升代码语义清晰度。 - 可根据需求调整
energy-level和stay-at-patch中的电量阈值,匹配实际任务场景。
内容的提问来源于stack exchange,提问作者robinyg
相关产品推荐
相关产品推荐

