返回后功能重复

时间:2018-03-23 04:42:55

标签: java

我正在与电脑玩家进行Tic-Tac-Toe游戏。但是,每当我调用计算机的makeMove方法时,计算机将继续播放而用户无法执行任何操作。为了确保该功能停止,我在每次移动后都返回,但它仍然在没有用户输入的情况下播放整个游戏。

以下是相关部分:

Board上课:

public String addToBoard(char c, int square) {
        if (!spaceFull(board, square)) {
            int[] coords = getRowAndColumn(square);
            //System.out.println("[" + coords[0] + "][" + coords[1] + "]");
            board[coords[0]][coords[1]] = c;
            return "VALID";
        } else {
            System.out.println("Space Is Occupied");
            return "OCCUPIED";
        }
    }
public boolean spaceFull(char[][] b, int square) {
        return (twoDimenToOneDimen(b).get(square - 1) == 'X' || twoDimenToOneDimen(b).get(square - 1) == 'O');
    }

Computer Class

public void makeMove() {
        int square;
        //Checks For Any Winning Computer Moves
        System.out.println("Here");
        if ((square = nextMoveWinCheck(playerChar)) != 0) {
            board.addToBoard(playerChar, square);
            return;
            //Checks For Any Opponent Winning Moves
        } else if ((square = nextMoveWinCheck(opponentChar)) != 0) {
            board.addToBoard(playerChar, square);
            return;
        } else {
            //Checks If Computer Has First Move
            if (boardEmpty()) {
                board.addToBoard(playerChar, 9);
                return;
            } else {
                //Moves Into Opposite Corner if Bottom Corner is Occupied By Itself
                if (!board.spaceFull(board.board,1) && board.board[2][2] == playerChar) {
                    board.addToBoard(playerChar, 1);
                    return;
                    //Move Into Center If Second Move or Possible
                } else if (!board.spaceFull(board.board,5)) {
                    board.addToBoard(playerChar, 5);
                    return;
                } else if ((square = emptyCorner()) != 0) {
                    board.addToBoard(playerChar, square);
                    return;
                } else {
                    board.addToBoard(playerChar, randomEmptySpot());
                    return;
                }
            }
        }
    }

如果你想要完整的代码,那就是:

1 个答案:

答案 0 :(得分:1)

您的问题出在班级Computer。在第57行,您将board.board分配给tempBoard。但是,tempBoard仍然保留对象board.board的引用,所以无论你做什么修改都反映在实际的板上。要解决此问题,请将板值复制到tempboard: http://www.java2s.com/Code/Java/Collections-Data-Structure/clonetwodimensionalarray.htm