我正在编写一个 NetLogo 代码来模拟乘客在房间内的移动。
我已将出口列表
exits-list
定义为补丁列表,并且我尝试访问 exits-list
中每个补丁的 x 和 y 坐标来计算乘客当前位置与每个出口之间的距离。但是,当我尝试使用语法 [patch-xcor] of patch
和 [patch-ycor] of patch
访问每个补丁的 x 和 y 坐标时,我收到一条错误消息:
expected a literal value
in "let exit-patch [patch-xcor item 0 ?, patch-ycor item 1 ?]"
如何解决这个问题并正确访问
exits-list
中每个面片的x和y坐标?
to initialize-exits
set exit1 patch 64 -13
set exit2 patch 13 -54
set exits-list (list exit1 exit2)
end
to initialize-passengers
create-passengers passenger-count [
set shape "person business"
set size 2
set color yellow
set in-seat? true
set safe? false
set dead? false
set panic? false
set current-heading 0
set target-exit nobody
set my-exits-list []
choose-exit patch-here ; Add this line to set the initial target-exit
]
ask passengers [
let target one-of patches with [accessible?]
face target
move-to target
]
end
to choose-exit [current-position]
let possible-exits []
let shortest-distance 10000
let nearest-exit nobody
foreach exits-list [
let exit-patch [patch-xcor item 0 ?, patch-ycor item 1 ?]
let distance distance current-position exit-patch
if distance < shortest-distance [
set shortest-distance distance
set nearest-exit exit-patch
set possible-exits []
]
if distance = shortest-distance [
set possible-exits lput exit-patch possible-exits
]
]
if possible-exits is-empty [
print "No exits found."
return
]
let lucky-exit one-of possible-exits
set target-exit lucky-exit
set my-exits-list lput lucky-exit my-exits-list
lucky-exit
end
问:“如何解决这个问题并正确访问
中每个补丁的x和y坐标?”exits-list
补丁拥有(拥有)属性名称
pxcor
和 pycor
您的代码也不得通过将它们用作用户定义的变量或属性名称来掩盖编程语言“保留”字样
(
distance
是这种情况之一)。
就像这里:
let distance distance current-position exit-patch
错误消息是鼠标单击并拖动可选择加上鼠标右键单击可以复制所选文本:
像这样:
observer> let exit2 patch 13 -54
ERROR: Nothing named EXIT1 has been defined.
语法突出显示和 [ 检查 ] 输出在 IDE 中不是 GUI 友好的,但它们可以作为即时交互工具,通过修复来消除错误。
这张最常见和不太常见的语法构造函数的思维导图可能会有所帮助:
这个语法并不那么简单,但是一旦你理解了它,它就非常容易了。您需要使用 NetLogo 词典中显示的第二种语法“foreach”,即使用“->”为您正在处理的列表项分配一个临时名称。对于您来说,请使用:
foreach exits-list [ next-exit -> ; Now "next-exit" is the next item on exit-list
let distance-to-exit distance patch-here next-exit
...
]