我正在尝试在 2d 屏幕上创建一个带有船只的游戏,并希望在它们离开屏幕时让它们绕行。
public static void placeBoat (char [][] boat,int x, int y ){
for(int row = 0; row < boat.length; row++){
if(row==x){
for(int column = 0; column < boat[row].length; column++){
if(column==y){boat [x][y] = '>';
boat [x][y-1] = '=';
boat [x][y-2] = '|';
boat [x][y-3] = '|';
boat [x][y-4] = '=';
boat [x][y-5] = '<';
}
}
}
}
}
举个例子,当我获得这些坐标时会发生什么,这就是它打印的内容。坐标引用打印船的前部,然后将船的其余部分打印在它的左侧。
1,18,
6,19,
2,6,
5,8,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~<=||=>~~~~~~~~~~~~~
~<=||=>~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~<=||=>~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~<=||=>~~~~~~~~~~~~
我遇到的问题是试图找出如果其中一个坐标的 y 值小于 5 时如何执行此操作,因为那么船的其他部分将离开屏幕,并且我得到 outofbounds
异常如 if y
是4
那么将会是 4-5,我会得到一个越界异常。
我本来打算做一个if(y<5)
并为此做单独的声明,但是当 y
时我必须这样做是 4
, 3
, 2
, 1
和0
.
最佳答案
如果您希望船部件向左缠绕,那么您必须在放置部件之前计算 y
位置,而循环不适合这样做。
一般来说,您的方法根本不需要循环遍历网格,因为您一次只放置一艘船。
整个方法可以替换为根据x
和y
值计算船的位置,然后直接修改网格。
public static void placeBoat(char [][] boat, int x, int y){
// the first part is at y
boat [x][y] = '>';
// size is 5 because there 5 more parts to the boat
int[] nextYs = new int[5];
for (int j = 0; j < nextYs.length; j++) {
// next y is at y - 1
int nextY = y - 1;
// next y is to the left
if (nextY >= 0) {
// set y to - 1
y = y - 1;
// next Y is to the right
} else {
// next y and y itself should be set to the last column
nextY = y = boat[x].length - 1;
}
nextYs[j] = nextY;
}
// print the other parts
boat [x][nextYs[0]] = '=';
boat [x][nextYs[1]] = '|';
boat [x][nextYs[2]] = '|';
boat [x][nextYs[3]] = '=';
boat [x][nextYs[4]] = '<';
}
关于java - 如何像横版卷轴游戏那样换行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46160727/