【问题标题】:How can I check if the first row of a 2D array with no fixed dimension all have the same value?如何检查没有固定维度的二维数组的第一行是否都具有相同的值?
【发布时间】:2021-12-29 22:28:13
【问题描述】:

我正在用 Java 制作一个带有可自定义尺寸功能的井字游戏(用户可以选择玩 3x3、4x4、5x5 等),并且正在研究寻找赢家的逻辑。目前我正在尝试找出横向检查胜利。

我有想法制作一个嵌套的 for 循环来检查托管该板的二维数组,但不知道如何执行此操作。这段代码的问题:

for (int i = 0; i < dimension; i++) {
        if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != '-') {
                // you won!
        }
}

...它的逻辑是否适用于 3x3 游戏,而不适用于任何其他维度。我只知道如何将值添加到二维数组中,那么如何检查这些值是否相等?提前谢谢你。

【问题讨论】:

    标签: java arrays for-loop multidimensional-array tic-tac-toe


    【解决方案1】:

    我不确定在更高维度中赢得井字游戏的规则,所以假设您必须填满整个行/列才能获胜。

    将 if 分为两部分:第一个字符的检查和比较。然后使用第二个 for 循环进行比较,如下所示:

    for (int i = 0; i < dimension; i++) { // iterate rows
        // check for first character
        if (board[i][0] == '-') {    // if wrong character...
            continue;                // ... check next row
        }
    
        boolean won = true;
    
        for (int j = 0; j < dimension - 1; j++) { // iterate columns
            if (board[i][j] != board[i][j+1]) {   // if other character...
                won = false;                      // ...not winnable with this column and...
                break;                            // ...stop iteration of columns
            }
        }
    
        if (won) {
            // you won!
        }
    }
    

    如果您在所有维度上以较少的十字架“X”获胜,则必须添加第三个循环来遍历可能的起点,或者您可以计算列中的十字架数量并重置数字(如果有) 'O'。

    【讨论】:

      猜你喜欢
      • 2014-05-15
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 2015-09-28
      • 1970-01-01
      • 2018-09-20
      • 1970-01-01
      • 2017-08-26
      相关资源
      最近更新 更多