在动态创建地图时遇到问题。当前项目下有主程序以及location类。location类由String变量name以及四个分别代表东西南北四个方向的Location变量构成。主程序下的方法中接纳一个int作为房间数量,通过random.nextInt方法取得一个随机值,分别对应将新创建的Location对象赋给当前Location的四个方向之一并将新Location作为当前Location。如果该方向已有Location,则跳过循环。输出显示当该方向已有Location时仍进行赋值而非跳过循环。
import java.util.Random;
public class mapTest {
protected Random rd = new Random();
public Location generateMap(int roomNum){
Location entrance = new Location("1");
Location current = entrance;
for (int i = 0;iint direction = rd.nextInt(4);
if (direction==0){
if (current.North == null){
Location next = new Location(Integer.toString(i+2));
System.out.println(next.name+" is at the North of "+current.name);
current.North = next;
current = current.North;
}else{
i-=1;
System.out.println("Occupied! Heading back...");
}
}else if (direction==1){
if (current.West == null){
Location next = new Location(Integer.toString(i+2));
System.out.println(next.name+" is at the West of "+current.name);
current.West = next;
current = current.West;
}else{
i-=1;
System.out.println("Occupied! Heading back...");
}
}else if (direction==2){
if (current.South == null){
Location next = new Location(Integer.toString(i+2));
System.out.println(next.name+" is at the South of "+current.name);
current.South = next;
current = current.South;
}else{
i-=1;
System.out.println("Occupied! Heading back...");
}
}else if (direction==3){
if (current.East == null){
Location next = new Location(Integer.toString(i+2));
System.out.println(next.name+" is at the East of "+current.name);
current.East = next;
current = current.East;
}else{
i-=1;
System.out.println("Occupied! Heading back...");
}
}
}
return entrance;
}
public static void main(String[] args) {
mapTest mt = new mapTest();
mt.generateMap(10);
}
}
Location类代码
public class Location {
protected String name;
protected Location North;
protected Location West;
protected Location South;
protected Location East;
public Location(String n){
this.name = n;
}
public String toString(){
return "This place is "+name;
}
}
直接在你的代码中加上创建location的代码即可。