Unable to update Kotlin variable in inside the function


#1

I’m trying to build a tic tac toe game for android.

But when I’m trying to change the active game.

The value of the variable activePlayer doesn’t change

fun buSelect(view:View){


    var butSelected = view as Button
    var callID = 0
    when(butSelected.id){
        R.id.bt1 -> callID = 1
        R.id.bt2 -> callID = 2
        R.id.bt3 -> callID = 3
        R.id.bt4 -> callID = 4
        R.id.bt5 -> callID = 5
        R.id.bt6 -> callID = 6
        R.id.bt7 -> callID = 7
        R.id.bt8 -> callID = 8
        R.id.bt9 -> callID = 9
    }

    //The Problem go from here
    var player1 = ArrayList<Int>()
    var player2 = ArrayList<Int>()
    var activePlayer:Int = 1

    fun PlayGame(callID:Int, butSelected:Button){

        if (activePlayer == 1){
            butSelected.text = "X"
            butSelected.setBackgroundResource(R.color.pink)
            player1.add(callID)
            activePlayer = 2
        }else{
            butSelected.text = "O"
            butSelected.setBackgroundResource(R.color.colorPrimaryDark)
            player2.add(callID)
            activePlayer = 1
        }

        butSelected.isEnabled = false

    }
    // until here
    PlayGame(callID, butSelected)
    }

And the testing result is this:

Test the code


#2

I don’t entirely get the problem.
I removed everything that is not directly related to your problem.
I got the following code:

fun main(){
   buSelect()
}

fun buSelect(){
    var activePlayer:Int = 1

    fun PlayGame(){
        if (activePlayer == 1){
            activePlayer = 2
        }else{
            activePlayer = 1
        }
    }

    println(activePlayer) // 1
    PlayGame()
    println(activePlayer) // 2
    PlayGame()
    println(activePlayer) // 1
    PlayGame()
}

When you run this code, the result is 1 2 1, which means the function changes the activePlayer.
I don’t know your problem, as I don’t have a problem, but I guess your variables: player1, player2 and activePlayer should be placed outside the function inside the class?
But this is just an assumption, as I don’t have enough code to see the entire problem.


#4

I found the problem
The problem was the line when I get a random number