我正在尝试制作一个随机地图生成器。它应该在随机坐标处创建一个随机大小的房间,并删除它与其他房间重叠的房间。但是,重叠检查不起作用。以下是代码的相关部分:
public static void generateMap() {
rooms[0] = new Room(0,10,10,5); // For some reason doesn't work without this?
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 (room.overlaps(rooms) == false) {
rooms[i] = room;
}
}
}
然后是 Room 类:
import java.awt.*;
public 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) {
boolean overlap = true;
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) && !r1.intersects(r2)) {
overlap = false;
}
else {
overlap = true;
}
}
}
}
return overlap;
}
}
所以我一直在测试这个,它每次都会删除几个房间,但是根据房间的数量,总会有一些重叠的。一定有一些我现在看不到的愚蠢简单的解决方案......另外,除非我手动添加第一个房间,否则它为什么不生成任何房间?谢谢
holdtom
幕布斯6054654
相关分类