Domanda

So I'm doing the project of an introduction to Java course and it seems that I chose something that goes way beyond what I'm able to do. :P
Any help would be greatly appreciated. This is what I'm having problems with:

You have a cursor that is controlled by a player (goes forward or turns 90°) which leaves a colored line as it goes. If you manage to go over your own line and close a polygon of any shape (only right angles though), its surface changes color into the color of your line.

I can detect when this situation arises but I am kind of lost as how to actually fill the correct polygon just closed. I can't seem to imagine an algorithm that would cover any case possible.

I looked at the Scanline fill algorithm but I think it would start having problems by the time there are already some polygons already filled in the map. The Floodfill algorithm would be perfect if I had a way of finding a point inside the polygon, but, as there are many different possibilities, I can't think of a general rule for this.

I'm using an array 2x2 of integers where each color is represented by a number.

Does anyone have an idea on how to approach this problem?

È stato utile?

Soluzione

If you can detect the situation then this can be solved in very simple manner. The question is which point to choose as start point for floodfill. The simple answer is: try all of them. Of course it makes a sense to start only with points adjacent to the one where your cursor is located. In this case you will have at most 8 points to check. Even better - at least 2 of them are definitely painted already if current point forms a polygon.

So you have 8 points to check. Launch floodfill 8 times starting from each of those points.

Two things which you probably should keep in mind:

  1. You should try filling the area in cloned version of your field in order to be able to get back if floodfill will not find a polygon.

  2. Launching floodfill second time and later you should reuse this cloned version of your field to see whether it was filled there. This will allow you to check every point at most once and this will make your 8 floodfills almost as fast as 1 floodfill.

Altri suggerimenti

Check this question, using Graphics2 and Polygon to fill an arbitrary polygon: java swing : Polygon fill color problem

Finding out whether a point is inside or outside a polygon: http://en.wikipedia.org/wiki/Point_in_polygon

Make sure you use double buffering. If you set individual pixels and don't use double buffering the component may redraw after every pixel was set.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top