我正在尝试制作一个简单的程序(目前还没有使用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)代表该符号在数组中的位置,并通过更改它们可以改变其位置的方式来给该符号提供坐标,几行,因为它只需要一个变体,但是我不知道如何将坐标链接到数组移动。任何帮助将不胜感激!
编辑:无法澄清某些内容。每个地图坐标均设置为一个称为“房间”的类,该类为其提供了描述和名称
答案 0 :(得分:0)
您应该有两个变量,分别为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) {
// ...
}