;; From the NetLogo Model Library: Social Science - Segregation Model globals [ percent-similar ;; on the average, what percent of a turtle's neighbors ;; are the same color as that turtle? percent-unhappy ;; what percent of the turtles are unhappy? ] turtles-own [ happy? ;; for each turtle, indicates whether at least %-similar-wanted percent of ;; that turtles' neighbors are the same color as the turtle ] patches-own [ reds-nearby ;; how many neighboring patches have a red turtle? greens-nearby ;; ditto for green turtles total-nearby ;; sum of previous two variables ] to setup ca cct number [ setxy (random screen-size-x) ;; randomize the turtle locations (random screen-size-y) ifelse who < (number / 2) ;; turn half the turtles red, the others green [ set color red ] [ set color green ] if any other-turtles-here ;; make sure each turtle is in its own patch [ find-new-spot ] ] update-variables do-plots end to go move-unhappy-turtles update-variables do-plots if not any turtles with [not happy?] [ stop ] end to move-unhappy-turtles ask turtles [ if not happy? [ find-new-spot ] ] end to find-new-spot rt random 360 fd random 10 if any other-turtles-here [ find-new-spot ] ;; keep going until we find an unoccupied patch end to update-variables update-patches update-turtles update-globals end to update-patches ask patches [ ;; in next two lines, we use "neighbors" to test the eight patches surrounding ;; the current patch set reds-nearby count neighbors with [any turtles-here with [color = red]] set greens-nearby count neighbors with [any turtles-here with [color = green]] set total-nearby reds-nearby + greens-nearby ] end to update-turtles ask turtles [ if color = red [ set happy? reds-nearby >= ( %-similar-wanted * total-nearby / 100 ) ] if color = green [ set happy? greens-nearby >= ( %-similar-wanted * total-nearby / 100 ) ] ] end to update-globals locals [ similar-neighbors total-neighbors ] set similar-neighbors sum values-from turtles with [color = red] [reds-nearby] + sum values-from turtles with [color = green] [greens-nearby] set total-neighbors sum values-from turtles [total-nearby] set percent-similar (similar-neighbors / total-neighbors) * 100 set percent-unhappy (count turtles with [not happy?]) / (count turtles) * 100 end to do-plots set-current-plot "Percent Similar" plot percent-similar set-current-plot "Percent Unhappy" plot percent-unhappy end