Java 2D阵列对角线游戏 [英] Java 2D array diagonals for game

查看:59
本文介绍了Java 2D阵列对角线游戏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了说明清楚,我只希望一个或两个for循环对我有所帮助,最好采用与垂直方式相同的样式:)

To clarify I only wanted one or two for loops to help me on my way, preferably in the same style as I had used in the vertical :)

我正在使用2D数组制作游戏,我需要检查一下该字符是否在当前位置(用绿色正方形表示)是否存在对角线序列"l"的一部分

I'm making a game using a 2D array, and I need a check that tests if at the current position (indicated by a green square) the character there is part of a diagonal sequence of "l" more of the character.

推荐答案

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
    }

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

The idea is that we walk in four directions and count the steps. This may not be the most efficient implementation, but at least it looks neat and easy to understand.

这篇关于Java 2D阵列对角线游戏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆