游戏的 Java 2D 数组对角线

标签 java loops multidimensional-array logic diagonal

澄清一下,我只想要一两个 for 循环来帮助我,最好是与我在垂直领域使用的风格相同:)

我正在使用 2D 数组制作游戏,我需要一个检查来测试在当前位置(由绿色方 block 表示)字符是否存在“l”更多字符的对角序列的一部分.

最佳答案

public static boolean diagonals(char[][] b, int row, int col, int l) {

            int counter = 1; // because we start from the current position
            char charAtPosition = b[row][col];
            int numRows = b.length;
            int numCols = b[0].length;
            int topleft = 0;
            int topright = 0;
            int bottomleft = 0;
            int bottomright = 0;
            for (int i=row-1,j=col-1;i>=0 && j>=0;i--,j--) {
                if (b[i][j]==charAtPosition) {
                    topleft++;
                } else {
                    break;
                }
            }
            for (int i=row-1,j=col+1;i>=0 && j<=numCols;i--,j++) {
                if (b[i][j]==charAtPosition) {
                    topright++;
                } else {
                    break;
                }
            }
            for (int i=row+1,j=col-1;i<=numRows && j>=0;i++,j--) {
                if (b[i][j]==charAtPosition) {
                    bottomleft++;
                } else {
                    break;
                }
            }
            for (int i=row+1,j=col+1;i<=numRows && j<=numCols;i++,j++) {
                if (b[i][j]==charAtPosition) {
                    bottomright++;
                } else {
                    break;
                }
            }
            return topleft + bottomright + 1 >= l || topright + bottomleft + 1 >= l; //in this case l is 5
    }

我们的想法是,我们朝四个方向行走并计算步数。这可能不是最有效的实现,但至少它看起来整洁且易于理解。

关于游戏的 Java 2D 数组对角线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13705431/

相关文章:

java - Intellij 15 错误 : could not find libjava. dylib

javascript - 为什么 for(var i in arguments) 不起作用?

javascript - 在没有可用标识符的情况下将所有具有特定 textContent 的 <a> 元素作为目标

C++多维数组初始化

java - NetBeans 初始化后 JFrame 未出现

java - Spring session 作用域 bean,线程安全

java - Elasticsearch 服务器发现配置

python - 在 Pandas 中循环并应用正则表达式

php - 使用另一个数组作为输入对数组进行排序

php - 使用 symfony 配置树生成器创建多维数组