[英]How do you move through a 2D array without for loops?
我正在尝试使用我提供的测试文件来构建寻宝游戏。 这些文本文件是字符 S、W、E、N 和 T,除了 T 是宝藏外,它们都对应于方向。 一切正常,直到它移动行/列的长度。 我怀疑它与 for 循环有关,但我不确定。 有没有办法在没有 for 循环的情况下做到这一点,或者有没有人有任何建议可以让它回到正轨?
到目前为止,这是我的更新代码:
import java.util.*;
public class NewGridGame {
public static final int FALL_OFF = -1;
public static final int GOING_IN_CIRCLES = -2;
private int row;
private int col;
private char[][] gameBoard;
NewGridGame(int conRow, int conCol, char[][] conGameBoard) {
row = conRow;
col = conCol;
gameBoard = new char[row][col];
for (int i = 0; i < gameBoard.length; i++) {
for (int j = 0; j < gameBoard[i].length; j++) {
gameBoard[i][j] = conGameBoard[i][j];
}
}
System.out.println(Arrays.deepToString(gameBoard));
}
public int playGame() {
boolean[][] beenHereBefore = new boolean[row][col];
int turns = 0;
int i = 0;
int j = 0;
while (true) {
if (beenHereBefore[i][j] == true) {
return GOING_IN_CIRCLES;
} else {
beenHereBefore[i][j] = true;
}
if (gameBoard[i][j] == 'N') {
if (i - 1 >= 0) {
i--;
turns++;
System.out.println(turns);
System.out.println(gameBoard[i][j]);
} else {
return FALL_OFF;
}
} else if (gameBoard[i][j] == 'S') {
if (i + 1 < row) {
i++;
turns++;
System.out.println(turns);
System.out.println(gameBoard[i][j]);
} else {
return FALL_OFF;
}
} else if (gameBoard[i][j] == 'E') {
if (j + 1 < col) {
j++;
turns++;
System.out.println(turns);
System.out.println(gameBoard[i][j]);
} else {
return FALL_OFF;
}
} else if (gameBoard[i][j] == 'W') {
if (j - 1 >= 0) {
j--;
turns++;
System.out.println(turns);
System.out.println(gameBoard[i][j]);
} else {
return FALL_OFF;
}
} else if (gameBoard[i][j] == 'T') {
return turns;
}
}
}
}
这里也是一个测试文件的例子。
ES
TW
这个应该返回 3,这是移动的次数(在我的代码中是转数),但它会到达 W(需要 2 次移动)并返回 -2,这仅适用于多次到达 position 的情况。 此外,并非所有 Arrays 都是正方形,例如,有些是 1x200 或 4x5。
如果你知道棋盘是这样的,从 (0, 0) 开始,你不会陷入循环或离开棋盘,你可以使用这样的东西:
public int playGame()
{
int numMoves = 0;
int currentRow = 0;
int currentCol = 0;
while(gameBoard[currentRow][currentCol] != 'T')
{
switch (gameBoard[currentRow][currentCol])
{
case 'E': currentCol++; break;
case 'W': currentCol--; break;
case 'S': currentRow--; break;
case 'N': currentRow++; break;
default:
throw new IllegalStateException("Unrecognized Move");
}
numMoves++;
}
return numMoves;
}
您可能想使用if-then-else
而不是switch
。
如果您需要检查循环或场外移动,您应该能够添加这些检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.