在Tic Tac Toe游戏中确定获胜者时,如何避免重复? (Java)

注意:我是Java的初学者(2-3个月的经验)。

在JetBrains / Hyperskill上做一个有关制作Tic Tac Toe游戏的项目时,我发现自己在尝试确定游戏的获胜者时重复了很多代码。为了将游戏表示为坐标系(因此1,1位于左下角,而3,3位于右上角),我使用的是二维数组。 这是确定获胜者的功能:

public String determineWinner() {
    int countX = 0; // amount of X's in a row
    int countO = 0; // amount of O's in a row

    for (int y = 0; y <= 2; y++) { // for all horizontal rows
        countX = 0;
        countO = 0;
        for (int x = 0; x <= 2; x++) { // loop through all x-coordinates
            String value = this.field[x][y]; 
            if (value.equals("X")) { // if the value at that coordinate equals "X", add 1 to the count
                countX++;
            }
            if (value.equals("O")) { // same here
                countO++;
            }
        }
        if (countX == 3) { // if the count is 3 (thus 3 X's in a row), X has won
            return "X wins";
        }
        if (countO == 3) { // same here
            return "O wins";
        }
    }

    // Same thing, but for all vertical columns
    for (int x = 0; x <= 2; x++) {
        countX = 0;
        countO = 0;
        for (int y = 0; y <= 2; y++) {
            String value = this.field[x][y];
            if (value.equals("X")) {
                countX++;
            }
            if (value.equals("O")) {
                countO++;
            }
        }
        if (countX == 3) {
            return "X wins";
        }
        if (countO == 3) {
            return "O wins";
        }
    }

    // Same thing, but for diagonal
    countX = 0;
    countO = 0;
    for (int i = 0; i <= 2; i++) {
        String value = this.field[i][i];
        if (value.equals("X")) {
            countX++;
        }
        if (value.equals("O")) {
            countO++;
        }
    }
    if (countX == 3) {
        return "X wins";
    }
    if (countO == 3) {
        return "O wins";
    }

    // Same thing, but for other diagonal
    countX = 0;
    countO = 0;
    for (int i = 0; i <= 2; i++) {
        String value = this.field[i][2-i];
        if (value.equals("X")) {
            countX++;
        }
        if (value.equals("O")) {
            countO++;
        }
    }
    if (countX == 3) {
        return "X wins";
    }
    if (countO == 3) {
        return "O wins";
    }

    if (this.getNumberOfMoves() == 9) { // if the number of moves equals 9, the game is over and it is a draw
        return "draw";
    }

    return "game not finished";
}

当前,该代码允许您设置起始板(所有O和X的起始布置),然后进行1次移动。此后,游戏将决定谁是获胜者,或者是否是平局等。

正如人们很快注意到的那样,该函数太长了,并且有相当一部分重复,但是我无法提出任何缩短它的方法。

有人有提示吗?还是适用于所有代码的任何准则?