Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

java - performClick() produces StackOverflowError

Currently developing a Tictactoe game for Android. The player vs player activity works perfectly, when I click a button it will show either 'X' or 'O' with a code like this:

if (player1Turn) {
        ((Button) v).setText("x");
    } else {
        ((Button) v).setText("o");
    }

Then I added the Minimax for player vs computer activity, the AI works perfectly too as it suggest the right move to outplay the opponent. The problem is, the AI can't self-click the button. I added performClick() to call the view's onClickListener but it doesn't work and produces java.lang.StackOverflowError. This is the code snippet:

if (player1Turn) {
        if (roundCount == 0) {
            Random random = new Random();
            int randPointerOne = random.nextInt(3);
            int randPointerTwo = random.nextInt(3);
            buttons[randPointerOne][randPointerTwo].performClick();
            buttons[randPointerOne][randPointerTwo].setText("x");
            board[randPointerOne][randPointerTwo] = 'x';
        } else {
            minimax.setBoard(board);
            buttons[minimax.bestMoveRow][minimax.bestMoveCol].performClick();
            buttons[minimax.bestMoveRow][minimax.bestMoveCol].setText("x");
            board[minimax.bestMoveRow][minimax.bestMoveCol] = 'x';
        }

        //AI Suggestion for the next move in form of Text
        tvAI.setText(minimax.bestMoveRow + "R" + " " + minimax.bestMoveCol + "C");

I already defined the setOnClickListener on the onCreate() (as the official documentation says) like this

for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            String buttonID = "button_"+ i + j;
            int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
            buttons[i][j] = findViewById(resID);
            buttons[i][j].setOnClickListener(this);
        }
    }

For additional information, if I removed the performClick() on the code, it will not produces the error but the AI still can't self-click and will only generate the 'X' or 'O' if I clicked one of the buttons for the AI (and of course, when it's AI turn to move).

If I doing it wrong, what is the right implementation of the performClick() to do an AI self-click? Is there an alternative way too? Thank you for reading the whole question btw! :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...