我正在制作战列舰,目前遇到了我的战舰重叠的问题。我尝试加入一个 if 语句来判断是否可以放置。这是我放置两艘长度为 3 的船的示例。
public static void PlaceCruiser(String[][] board) {
ThreadLocalRandom random = ThreadLocalRandom.current();
int timesplaced = 0;
int size = 3;
while (timesplaced < 2) {
int randomcruisercheck =(int)(Math.random()*2);
if (randomcruisercheck == 0) {
int column = random.nextInt(0,9);
int row = random.nextInt(0,7);
if (row + 2 < 11 && board[row][column] == "." && board[row + 1][column] == "." && board[row + 2][column] == ".") {
for(int i = 0; i<size; i++)
{
board[row+i][column] = "#";
}
System.out.println(board[row][column]);
}
timesplaced++;
}
else if (randomcruisercheck == 1) {
int column = random.nextInt(0,9);
int row = random.nextInt(0,7);
if (column + 2 < 11 && board[row][column] == "." && board[row][column + 1] == "." && board[row][column + 2] == ".") {
for (int i = 0; i<size; i++)
{
board[row][column + i] = "#";
}
System.out.println(board[row][column]);
}
timesplaced++;
}
}
}
基本上,我使用“#”来表示“.”的 10x10 2D 数组中的一艘船。我觉得 if 语句是关于如果行或列加 1 然后加 2 是一个点,即一个自由空间,就会生成一艘船,但情况似乎并非如此。谁能帮帮我吗?
最佳答案
您的代码运行良好,您只需处理索引并初始化板:
public class Main {
public static String[][] board;
public static void main(String[] args) {
PlaceCruiser pc = new PlaceCruiser();
board = new String[10][10];
// Initialize the board
for (int i=0;i<10;i++) {
for (int j=0;j<10;j++) {
board[i][j]=".";
}
}
pc.placeCruiser(board);
// Show thew board
for (int i=0;i<10;i++) {
for (int j=0;j<10;j++) {
System.out.print(board[i][j]);
}
System.out.println();
}
}
}
结果:
..........
..###.....
..........
..........
....#.....
....#.....
....#.....
..........
..........
..........
还要检查您的初始位置是否已经是“#”。
关于java - 如何防止二维数组上的字符串重叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59181197/