【正文】
eighbor 。 closest one of our flockmates]to setup clearall setupturtles setuppatches resetticksendto setupturtles setdefaultshape turtles person crt population [ set color orange 2 + random 6 。 random shades look nice set size 。 easier to see setxy randomxcor randomycor] endto setuppatches ask patches [if pycor = 0 and abs(pxcor 30) 10 [set pcolor orange]]endto go ask turtles [ flock ] 。 the following line is used to make the turtles 。 animate more smoothly. repeat 5 [ ask turtles [ fd ] display ] 。 for greater efficiency, at the expense of smooth 。 animation, substitute the following line instead: 。 ask turtles [ fd 1 ] tickendto flock 。 turtle procedure findflockmates if any? flockmates [ findnearestneighbor ifelse distance nearestneighbor minimumseparation [ separate ] [ align cohere ] ] turntowardsexit disappearendto findflockmates 。 turtle procedure set flockmates other turtles inradius visionendto findnearestneighbor 。 turtle procedure set nearestneighbor minoneof flockmates [distance myself]End。 SEPARATEto separate 。 turtle procedure turnaway ([heading] of nearestneighbor) maxseparateturnend。 ALIGNto align 。 turtle procedure turntowards averageflockmateheading maxalignturnendtoreport averageflockmateheading 。 turtle procedure 。 We can39。t just average the heading variables here. 。 For example, the average of 1 and 359 should be 0, 。 not 180. So we have to use trigonometry. let xponent sum [dx] of flockmates let yponent sum [dy] of flockmates ifelse xponent = 0 and yponent = 0 [ report heading ] [ report atan xponent yponent ]end。 COHEREto cohere 。 turtle procedure turntowards averageheadingtowardsflockmates maxcohereturnendtoreport averageheadingtowardsflockmates 。 turtle procedure 。 towards myself gives us the heading from the other turtle 。 to me, but we want the heading from me to the other turtle, 。 so we add 180 let xponent mean [sin (towards myself + 180)] of flockmates let yponent mean [cos (towards myself + 180)] of flockmates ifelse xponent = 0 and yponent = 0 [ report heading ] [ report atan xponent yponent ]end。 HELPER PROCEDURESto turntowards [newheading maxturn] 。 turtle procedure turnatmost (subtractheadings newheading heading) maxturnendto turnaway [newheading maxturn] 。 turtle procedure turnatmost (subtractheadings heading newheading) maxturnend。 turn right by turn degrees (or left if turn is negative),。 but never turn more than maxturn degreesto turnatmost [turn maxturn] 。 turtle procedure ifelse abs turn maxturn [ ifelse turn 0 [ rt maxturn ] [ lt maxturn ] ] [ rt turn ]endto turntowardsexit turntowards directiontowardsexit maxexitturn endtoreport directiontowardsexit ifelse xcor 30 = 0 [ report 90 + atan abs(ycor) abs(30 xcor) ] [ report 270 atan abs(ycor) abs(xcor 30) ] endto disappear if (abs(ycor 1) 1) and (abs(xcor 29) 1) [ die ]end 。 Copyright 1998 Uri Wilensky.。 See Info tab for full copyright and license.25