我正在尝试为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)
}
测试结果是这样的:
答案 0 :(得分:1)
您必须将var activePlayer:Int = 1
移到函数buSelect(view:View)
之外,以为您需要将其作为全局变量。