我有一个问题想要解决。假设有两种类型的特工(兔子和猎人)。我希望猎人能找到离他们最近的兔子。但如果两个猎人要找到同一只兔子(即距离猎人 103 和猎人 105 最近的兔子是兔子 99)。我希望其中一位猎人找到下一个最近的兔子。因此,每个猎人都需要检查其他猎人连接到哪些兔子,如果有任何猎人连接到同一只兔子,则找到下一个最近的兔子。任何想法如何解决这个问题。谢谢
breed [hunters hunter]
breed [rabbits rabbit]
hunters-own [rab-in-sight]
to setup
clear-all
create-hunters 20
create-rabbits 100
ask hunters [
set color red
setxy random-xcor random-ycor
]
ask rabbits [
set color white
setxy random-xcor random-ycor
]
end
to connect
ask hunters [
set rab-in-sight min-one-of rabbits in-radius 5 [distance myself]
]
end
最佳答案
您可以使用一个变量来指示兔子是否已成为目标,或者使用链接
来完成同样的事情。
链接方法
看看您的设置
的修改版本,其中猎人将他们的rab-in-sight
设置为nobody
:
breed [hunters hunter]
breed [rabbits rabbit]
hunters-own [rab-in-sight]
to setup
clear-all
create-hunters 20
create-rabbits 100
ask hunters [
set color red
setxy random-xcor random-ycor
set rab-in-sight nobody
]
ask rabbits [
set color white
setxy random-xcor random-ycor
]
reset-ticks
end
然后,使用 if
或 ifelse
语句根据当前是否正在狩猎兔子来控制猎人的行为:
to go
ask hunters [
connect
]
tick
end
to connect
; If a hunter is not already targetting a rabbit
ifelse rab-in-sight = nobody [
fd 1
; Choose a target rabbit that does not already have a link with other hunters
set rab-in-sight min-one-of ( rabbits in-radius 5 with [
not any? my-links ] ) [distance myself]
; If that rabbit exists, create a link with it so no other hunters will
; target the same rabbit
if rab-in-sight != nobody [
create-link-with rab-in-sight
]
] [
; If you're targetting a rabbit, hunt it
face rab-in-sight
ifelse distance rab-in-sight > 1 [
fd 1
] [
move-to rab-in-sight
ask rab-in-sight [
die
]
set rab-in-sight nobody
]
]
end
变量方法
标志或信号量变量方法类似 - 稍作修改的设置
现在将rab-in-sight
设置为nobody
并给出rabbits
一个设置为 false
的 targeted?
bool 变量:
breed [hunters hunter]
breed [rabbits rabbit]
hunters-own [rab-in-sight]
rabbits-own [ targeted? ]
to setup
clear-all
create-hunters 20
create-rabbits 100
ask hunters [
set color red
setxy random-xcor random-ycor
set rab-in-sight nobody
]
ask rabbits [
set color white
setxy random-xcor random-ycor
set targeted? false
]
reset-ticks
end
现在,当猎人瞄准兔子时,它会让兔子将其 targeted?
变量更改为 true
,以便其他猎人“知道”不要也瞄准它:
to go
ask hunters [
connect
]
tick
end
to connect
; If a hunter is not already targetting a rabbit
ifelse rab-in-sight = nobody [
fd 1
; Choose a target rabbit that is not currently being targeted
set rab-in-sight min-one-of ( rabbits in-radius 5 with [
not targeted? ] ) [distance myself]
; If that rabbit exists, have it set targetted? to true so
; no other hunters will target the same rabbit
if rab-in-sight != nobody [
ask rab-in-sight [
set targeted? true
]
]
] [
; If you're targetting a rabbit, hunt it
face rab-in-sight
ifelse distance rab-in-sight > 1 [
fd 1
] [
move-to rab-in-sight
ask rab-in-sight [
die
]
set rab-in-sight nobody
]
]
end
关于Netlogo,检查两个代理是否连接到同一个代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56271506/