DEFINITIONS:
Any "Point (x, y)" mentioned below is really the bottom left coordinates of a 1 unit by 1 unit rectangle. A "Line" is a defined as a rectangle that is either 1 unit tall and 1 unit or greater wide, or 1 unit wide and 1 unit or greater tall. These rectangles are constructed given a Rectangle(bottomLeftX, bottomLeftY, width, height). The height and/or width can be negative. If either are it will shift the start x or y accordingly as so:
public Rectangle(int x1, int y1, int width, int height) {
_left = x1;
_right = x1;
if(width < 0)
_left += width;
else
_right += width;
_bottom = y1;
_top = y1;
if(height < 0)
_bottom += height;
else
_top += height;
}
THE GOAL:
Given two arbitrary points, define two lines (as rectangles) connecting the two points. The two lines need to randomly 'bend' at one of the two possible connections (see below). The two points aren't in any specific order. Point A's X and/or Y can be above, below or even the same as Point B's X and/or Y.
THE PROBLEM:
I have made a solution that only partially works. There is a bug in my method below where sometimes the two lines do not connect at the bend/junction. It seems to only be when the bend/junction is in the bottom right of the points' bounds.
WHAT I HAVE NOW:
A little background: I'm working on a random dungeon generator. I create rooms randomly, and then I am going to connect them using the described point and line system above. Here's what I have now. "graph" is a Map>, technically it's directional, but the reason was so that I wouldn't draw the same lines twice.
int x, y, dx, dy;
Rectangle a, b;
// loop through each edge of the graph
for(Rectangle outer:graph.keySet()) {
for(Rectangle inner:graph.get(outer)) {
// randomly set a and b
if(random.nextBoolean()) {
a = outer;
b = inner;
} else {
a = inner;
b = outer;
}
// generate the origin points based on a
x = (int) a.getCenterX();
y = (int) a.getCenterY();
// and the delta of b to a
dx = (int) b.getCenterX()-x;
dy = (int) b.getCenterY()-y;
// create line starting at a, then
// create line starting at end of above line
lines.add(new Rectangle(x, y, dx, 1));
lines.add(new Rectangle(x+dx, y+dy, 1, -dy));
}
}
Here's what it produces. Most of the time it works, however there are cases where the corners do not line up. I'm not sure how to fix this.
Any input is much appreciated.