无法在函数内部更新Kotlin变量

时间:2019-01-23 07:27:45

标签: android android-studio kotlin

我正在尝试为android构建井字游戏。

但是当我尝试更改活动游戏时。

变量activePlayer的值不变

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)
    }

测试结果是这样的:

Test the code

1 个答案:

答案 0 :(得分:1)

您必须将var activePlayer:Int = 1移到函数buSelect(view:View)之外,以为您需要将其作为全局变量。