将多个对象分组

时间:2016-04-23 16:23:52

标签: java graph nearest-neighbor

我正在制作一个有很多房间的游戏,这些房间通过通道连接。整个事物是通过在整个区域创建随机大小的房间而随机生成的,然后,它找到一个尚未通过通道连接的最近房间,并在它们之间创建一条通道。

private void LinkRooms() {
    for(Room r : new ArrayList<Room>(rooms)){
        if(r != null) {
            Room r2 = getNearestNeighbour(r);
            if(r2 != null) createPassage(r, r2);
        }
    }
}

找到最近的邻居:

private Room getNearestNeighbour(Room r) {
    double dist = 10000000;
    Room room = null;
    for(Room r2 : new ArrayList<Room>(rooms)){
        if(!r.linked.contains(r2) && r2 != r){
            int cx = r.x + r.size_x/2;
            int cy = r.y + r.size_y/2;
            int cx2 = r2.x + r2.size_x/2;
            int cy2 = r2.y + r2.size_y/2;
            double distance = Math.sqrt((cx - cx2) * (cx - cx2) + (cy - cy2) * (cy - cy2));
            if(distance <= dist){ 
                dist = distance; 
                room = r2;
            }
        }
    }
    return room;
}

在两个房间之间建立通道:

private void createPassage(Room r, Room r2) {
    int centrex = roundm(r.x + r.size_x/2 - Tile.size/2);
    int centrey = roundm(r.y + r.size_y/2 - Tile.size/2);
    int centrex2 = roundm(r2.x + r2.size_x/2 - Tile.size/2);
    int centrey2 = roundm(r2.y + r2.size_y/2 - Tile.size/2);

    r.linked.add(r2);//here is where the room adds the rooms that it is directly linked to
    r2.linked.add(r);

/**I tried to approach my problem by giving rooms a unique id, 
which is equal to their position in the array, and then I thought 
it would spread this id to each of the other rooms, however, because 
of the order that they find the nearest neighbour being "random" some
would end with different id's. Note that I use the colour so that I 
can see it visually.**/

    if(r.id < r2.id){
        r2.id = r.id;
        r2.colour = r.colour;
    }else{
        r.id = r2.id;
        r.colour = r2.colour;
    }
    for(int xtile = 0; xtile < Math.abs(centrex2-centrex); xtile+=Tile.size){
        if(centrex < centrex2){
            ... // create new tile with owner "r"
        }else{
            ...
        }
    }
    for(int ytile = 0; ytile < Math.abs(centrey2-centrey); ytile+=Tile.size){
        ...
    }
}

这通常不会连接该地区的所有房间。房间倾向于形成组,但图形不是连接图。每个房间在ArrayList中存储它直接连接的房间,但是我需要将所有具有相互路径的房间组合在一起并为它们分配组ID。那么,如何将这些房间组织成每个连接图的组?

0 个答案:

没有答案