Ziad Abouelfarah
Ziad Abouelfarah

Reputation: 30

Unable to update Kotlin variable in inside the function

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

Upvotes: 0

Views: 707

Answers (1)

gmetax
gmetax

Reputation: 3973

you have to move the var activePlayer:Int = 1 outside of the function buSelect(view:View) think that you need it as a global variable.

Upvotes: 1

Related Questions