Skip to content Skip to sidebar Skip to footer

Android Tic Tac Toe Game - Logic Issue

I'm making 'Tic Tac Toe' game. 3x3 fields, basic. Now I made some of the logic, plus for random computer choice. But it happens sometime when I click on the field, the computer doe

Solution 1:

I think, that this fragment of code makes problem:

        Button random = myList.get(new Random().nextInt(myList.size()));
        if (!random.equals(" ")) {
            random.setText("O");
            random.setTextColor(Color.RED);
        }

For example: Player chooses first button, then it's time for computer to choose, computer as a random chooses 0, but this button was already clicked by player, so nothing is happening

You should make some function like this to make sure that computer will choose correct number.

privatevoidcomputerMove(){
    Button random = myList.get(new Random().nextInt(myList.size()));
    if (!random.equals(" ")) {
        random.setText("O");
        random.setTextColor(Color.RED);
    } else {
        computerMove();
    }
}

It's not perfect solution, it could freeze app, you should think about better aproache of choosing field by computer.

EDIT I see another problem, look at this:

myList.add(0, buttonOne);
myList.add(1, buttonTwo);
myList.add(2, buttonThree);
myList.add(3, buttonFour);
myList.add(4, buttonFive);
myList.add(5, buttonSix);
myList.add(5, buttonSeven);
myList.add(5, buttonEight);
myList.add(5, buttonNine);

You are adding buttons to the same position, position 5.

Also I refactored a little bit your function, becouse there is a lot of boilerpalte:

publicvoidonClickButton(View view) {
    if (view instanceof Button){
        Buttonbtn= (Button) view;
        CharSequencetext= btn.getText();
        if(!text.equals(" ")){
            Toast.makeText(this, "This filed is not empty, choose another.", Toast.LENGTH_SHORT).show();
        } else {
            btn.setText("X");
            btn.setTextColor(Color.GREEN);
            myList.remove(btn);
            computerMove();
        }
    }
}

Solution 2:

This might not be a solution to the problem you stated but I don't think you can use .equals() to compare a button and a string as you did here... !random.equals(" "). Why not repeat what you did here?

CharSequencetextTwo= buttonTwo.getText().toString();

Post a Comment for "Android Tic Tac Toe Game - Logic Issue"