2 回答
TA贡献1805条经验 获得超10个赞
您的问题是这部分overlaps
功能:
overlap = false;
您的代码中发生的情况是,您会继续检查房间是否重叠,但如果您找到重叠的房间,则继续检查。然后当你找到一个不重叠的房间时,你重置标志。实际上,该代码等同于仅检查最后一个房间。
完全删除重叠标志。而不是overlap = true;
put 语句return true;
(因为此时我们知道至少有一个房间是重叠的)。当你发现房间没有与其他房间重叠时不要做任何事情(在 for 循环中)。最后,在 for 循环之后return false;
,代码执行到那个点意味着没有重叠的空间(否则它会刚刚返回)
注意:我认为这个条件!r2.intersects(r1) && !r1.intersects(r2)
是多余的。.intersects(r)
应该是可交换的,这意味着r1.intersects(r2)
并r2.intersects(r1)
给出相同的结果。
TA贡献1876条经验 获得超7个赞
对于您已初始化第一个房间的第一个问题,您不必这样做。
rooms[0] = new Room(0,10,10,5); // For some reason doesn't work without this?
您只需要检查第一个房间,无需检查重叠,因为它是第一个房间。对于第二个问题,您可以在第一次找到相交时返回 true,否则在循环结束时返回 false。
代码供您参考。
class Room {
int x;
int y;
int height;
int width;
public Room(int rx, int ry, int rwidth, int rheight) {
x = rx;
y = ry;
height = rheight;
width = rwidth;
}
boolean overlaps(Room[] roomlist) {
Rectangle r1 = new Rectangle(x, y, width, height);
if (roomlist != null) {
for (int i = 0; i < roomlist.length; i++) {
if (roomlist[i] != null) {
Rectangle r2 = new Rectangle(roomlist[i].x, roomlist[i].y, roomlist[i].width, roomlist[i].height);
if (r2.intersects(r1)) {
return true;
}
}
}
}
return false;
}
}
public class RoomGenerator {
private static final int ROOMS = 10;
private static final int WIDTH = 1200;
private static final int HEIGHT = 1000;
private static final int MINROOMSIZE = 10;
private static final int MAXROOMSIZE = 120;
public static void main(String[] args) {
generateMap();
}
public static void generateMap() {
Room rooms[] = new Room[10];
for (int i = 0; i < ROOMS; i++) {
int x = randomWithRange(0, WIDTH);
int y = randomWithRange(0, HEIGHT);
int height = randomWithRange(MINROOMSIZE, MAXROOMSIZE);
int width = randomWithRange(MINROOMSIZE, MAXROOMSIZE);
while (x + width > WIDTH) {
x--;
}
while (y + height > HEIGHT) {
y--;
}
Room room = new Room(x, y, width, height);
if( i ==0)
{
rooms[0] = room;
}else if (room.overlaps(rooms) == false) {
rooms[i] = room;
}
}
}
private static int randomWithRange(int min, int max) {
// TODO Auto-generated method stub
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}
}
添加回答
举报