我正在尝试使用网络徽标库中的餐饮哲学家进行精确的仿真,但使用不同的方法。我正在尝试创建一种情况,即一圈中有20位哲学家,而每位哲学家面前都有一个“叉子”。哲学家要么吃东西,要么思考,要么饿了。他们只能吃两把叉子才能吃东西,吃完后,他们放下叉子思考,直到饿了。我试图让饥饿的哲学家的2个叉转移到各自的哲学家,但是我不确定该怎么做。 到目前为止,这是我的代码:
breed [philosophers philosopher]
breed [forks fork]
philosophers-own [thinking eating hungry]
globals [x y]
;eating = green
;thinking = blue
;hungry = red
to setup
ca
cro num-philosophers [set breed philosophers
fd 10 set shape "person-1"
set color blue
ask philosophers [
set hungry hungry = false
set thinking thinking = true
set eating eating = false]
set size 3]
cro num-philosophers [set breed forks fd 8
set heading heading + 180 / num-philosophers
fd -1
lt 180
set shape "fork"
set color grey
set size 2.5
]
reset-timer
end
to go
move
end
to move
every .1 [
ask philosophers with [who mod 2 = 0] [set color red
set hungry hungry = true
set thinking thinking = false
set eating eating = false]
ask philosophers with [hungry = true] [
;this following line with in-radius was my attempt to move the forks but it doesn't work
ask [forks in-radius 4] of philosophers with [hungry = true] [setxy x y]
ask fork 21 [setxy x y]
set y [ycor] of one-of philosophers with [hungry = true]
set x [xcor] of one-of philosophers with [hungry = true]
]]
end
对如何解决此问题的任何建议表示赞赏!谢谢!
答案 0 :(得分:3)
第一个问题是您的行像set hungry hungry = false
。在NetLogo中,分配一个不带等号的变量值。假设您要将名为“ hungry”的变量设置为false
,则代码应为set hungry false
。另外,按照惯例,NetLogo布尔变量名称在末尾使用问号(以提醒您它们是布尔值),因此最好使用set hungry? false
并相应地更改philosophers-own
语句。
这将导致部分错误,因为测试的饿值是true或false,但是您没有分配true或false。因此if
语句将始终为false。
第二,由于实际上是从叉子的角度进行移动,因此移动最好是ask forks
,而不是ask philosophers
。也许像这样:
ask forks
[ let targets (philosophers in-radius 4) with [hungry?]
if any? targets
move-to target with-min [distance myself]
]
此代码未经测试。基本方法是用叉子检查在4距离之内是否有饥饿的哲学家。如果有,则叉子会移动到最近的饥饿的哲学家的位置。在NetLogo词典中查找move-to
。即使这不是您想要的答案,也可能是您要寻找的原始内容。您无需从一只乌龟那里获得xcor和ycor并将它们传递给另一只乌龟,您只需移动到乌龟(或face
乌龟然后再稍微移动forward
)
最后,我建议您逐步构建代码。例如,如果哲学家在叉子的4距离之内,可以将其变为红色。然后您可以担心移动。
在另一个问题上,实际上不太可能要使用every
。仅在您希望每个时间步都有实时时间(例如秒数)时。相反,您应该考虑使用tick
来增加时钟。您的模型将运行得更快,因为它将受到所需处理量的限制,而不是根据现实世界中的时间进行跟踪。