Java | TicTacToe правая диагональ не работает - PullRequest
0 голосов
/ 02 ноября 2018

в настоящее время работает над игрой в крестики-нолики в java, и у меня есть метод checkWin (), который работает правильно для 3 из 4 возможных условий выигрыша. У меня проблема с правильной диагональю.

Код:

public boolean checkWin(String player){
    int row = 0; // Holder to count number of player spots in row
    int d1 = 0; // Holder to count number of player spots in right diag.
    int d2 = 0; // Holder to count number of player spots in left diag.
    int[] column = new int[squares[0].length]; /* Holder to count number
    of player spots in column */

    for(int i = 0; i < size; i++){
        row = 0;
        for(int j = 0; j < size; j++){
            if(null == squares[i][j]){
                continue;
            }
            if(squares[i][j].getText().equals(player)){
                row++; /* If spot at [i][j] equals player, increase row */
                column[j]++; /* If spot at [i][j] equals player, increase 
                col */
                if(i == j){ /* If spot at i is equal to j, increase left 
                    diag */
                    d1++;
                } else if ((size - 1) == i + j){ /* If spot at i + j 
                    equals board size - 1, increase right diag. */
                    d2++;
                }
            }
        }
        if(row == size){ 
            /* 
            if spots in row is equal to size (otherwise, if it fills
            the row, return win
            */
            return true;
        }
    }
    if(size == d1 || size == d2){
        /*
        if spots in either diag is equal to size, return win
        */
        return true;
    } 
    for(int i = 0; i < column.length; i++){
        if(column[i] == size){
            /*
            if column is full of the same player character, return win
            */
            return true;
        }
    }
    /*
    otherwise, return false
    */
    return false;
}

Проблемная часть:

                else if ((size - 1) == i + j){ /* If spot at i + j 
                    equals board size - 1, increase right diag. */
                    d2++;
                }

Причина, по которой он настроен таким образом, заключается в том, как работает 2D Array, поэтому для платы 3x3:

[00] [01] [02]

[10] [11] [12]

[20] [21] [22]

И если i + j = size - 1, он будет оценивать 2 + 0, 1 + 1, 0 + 2, все равные 2, то есть size - 1, если size = 3, но когда я запускаю программу и выполняю движение по диагонали вправо, оно не возвращает истинное значение выигрыша.

Будем весьма благодарны за любые предложения, как это исправить.

1 Ответ

0 голосов
/ 02 ноября 2018
else if ((size - 1) == i + j)

^ Это оценивается только в том случае, если условие if над ним ложно.

if(i == j)

Когда i == 1 и j == 1, тогда i == j имеет значение true, и, таким образом, (size - 1) == i + j не оценивается.

TLDR: избавься от else.

...