我正在尝试制作一个简单的程序(现在对java没有太多经验,仍在学习(,在数组中的"位置"之间移动符号,因此输出看起来像
"向东">
[ ] [O] [ ]
至
[ ] [ ] [O]
我现在有一种方法可以做到,我为每一个变体写一个If语句,例如
if (map[0][2] == 'X') {//if I am in this room
if (dir.equalsIgnoreCase("north")) {
System.out.println("You can't go that way");
} else if (dir.equalsIgnoreCase("south")) {
System.out.println("You go south");
map[0][2] = ' ';//moving from one room
map[1][2] = 'X';//to the other
这意味着,如果我的房间不止几个,这种方法就会变得异常漫长。我确信有一种方法可以让它更短,通过制作两个全局变量给符号一个坐标,比如X和Y,表示它在数组中的位置,通过改变它们,我可以改变它的位置,这只需要几行,因为它只需要一个变化,但我不知道如何将坐标与数组移动联系起来。任何帮助都将不胜感激!
编辑:没有澄清什么。每个地图坐标都被设置为一个名为"房间"的类,该类为其提供了描述和名称
您应该有两个名为currentX
和currentY
:的变量
int currentX = 0;
int currentY = 0;
这些将存储X
的位置。然后你可以通过以下操作访问当前位置:
map[currentX][currentY]
这意味着你只有四种情况(四个方向(需要处理:
if (dir.equalsIgnoresCase("south")) {
if (isValidCoordinate(currentX, currentY + 1)) {
map[currentX][currentY] = ' ';
map[currentX][currentY + 1] = 'X';
currentY += 1;
} else {
// you can't go this way
}
} else if (dir.equalsIgnoresCase("east")) {
if (isValidCoordinate(currentX + 1, currentY)) {
map[currentX][currentY] = ' ';
map[currentX][currentY] = 'X';
currentX += 1;
} else {
// you can't go this way
}
} else if ...
其中isValidCoordinate
是必须实现的方法,如果可以转到该坐标,则返回true。
private boolean isValidCoordinate(int x, int y) {
// ...
}