Netlogo笔记06:狼羊追逐

向量定向法,更新狼的移动方向

可以看出狼与羊的追逐总是会趋于稳定,狼羊距离总体是减小的趋势。

globals[flag]
breed[cats cat]
breed[dogs dog]
to update_heading;red to find black
  let x1 1
  let y1 1
  let x2 1
  let y2 1
  let hea 0
  ask turtles with [color = red][
    set x1 pxcor
    set y1 pycor 
  ]
  ask turtles with [color = white][
    set x2 pxcor - x1
    set y2 pycor - y1
  ]
  if x2 = 0 and y2 = 0
  [
    set flag 1
    stop
  ]
  let turn_corn 0
  show x2
  show y2
  set turn_corn acos( y2 / sqrt( x2 * x2 + y2 * y2 ) )
  ifelse x2 >= 0[
     ask turtles with [color = red][set heading turn_corn]
  ][
     ask turtles with [color = red][set heading 360 - turn_corn]
  ]
end

to setup
  clear-all
  reset-ticks
  set flag 0
  set-default-shape turtles "wolf"
  create-dogs 1[
    set color red
    setxy random-xcor random-ycor 
  ]
  set-default-shape turtles "sheep"
  create-cats 1[
    set color white
    setxy random-xcor random-ycor 
  ]
  ask turtles with [color = red][
    create-links-with other turtles
    if links-two = false [ask links [hide-link] ]
  ]
end 

to go
  update_heading
  ask turtles[
    if color = white[
      right random 90
      left random 90
      fd -0.3
    ]
    fd 1 
  ]
  if flag = 1[stop]
  let d 0
  ask turtles[
    if color = white[ask other turtles[set d distance myself]]
  ]
  set-current-plot "Distance"
  set-current-plot-pen "catch"
  plot d
  tick
end
经验分享 程序员 微信小程序 职场和发展