How to replace color with another color in a polygon?

别说谁变了你拦得住时间么 提交于 2019-12-24 08:37:01

问题


I have patches as follows:

I would like to color white patches as in this figure:

Here my code to color white patches in blue:

ask patches with [pcolor = white] [
if any? neighbors with [pcolor = blue] [set pcolor blue] ]

But the problem is that I obtain this figure:

.

Thanks in advance for your help.


回答1:


Alan is right about the cause of your problem, but you don't need to create a next-pcolor patch variable. If you put both conditions inside the with block, NetLogo will first construct the agentset of patches, and then ask these patches to do stuff, thereby avoiding the timing problem that you had. Let's try it. And since you're obviously going to have to do it with both blue and cyan patches, let's build a more general version:

to color-white-patches-v1 [ c ]
  ask patches with [ pcolor = white and any? neighbors with [ pcolor = c ]] [
    set pcolor c
  ]
end

That you can then call with:

color-white-patches-v1 cyan
color-white-patches-v1 blue

Here is the result:

But it's not quite what you wanted. That's because neighbors gives you all 8 neighbors of a patch. Let's try with neighbors4 instead:

to color-white-patches-v2 [ c ]
  ask patches with [ pcolor = white and any? neighbors4 with [ pcolor = c ]] [
    set pcolor c
  ]
end

Not quite there yet. It think you are going to have to resort to something like patch-at. In this example, I look at only the patch above:

to color-white-patches-v3 [ c ]
  ask patches with [ pcolor = white and [ pcolor ] of patch-at 0 1 = c ] [
    set pcolor c
  ]
end

I'm not sure if that was exactly what you wanted and how well that applies to your general problem, but with some combination of patch-at, you should be able to get what you need.




回答2:


The problem arises because patches are being changed sequentially, so some white patches find they have new blue neighbors by the time they respond to ask.

ask patches with [pcolor = white and any? neighbors with [pcolor = blue]] [set pcolor blue]

Note: this answer is edited in response to Nicholas's observation that with will create the entire agent set before ask is called. However I stuck with neighbors since that's how I read the question.



来源:https://stackoverflow.com/questions/25082254/how-to-replace-color-with-another-color-in-a-polygon

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!