0

我正在尝试井字游戏示例项目。一旦用户执行点击,我就会收到回调,但是当尝试更新文本时,它基本上不是更新文本。下面是我的代码,请帮忙。到目前为止,我已经尝试过需要在下面输入文字以关闭 SO 错误 bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla布拉布拉:

enum class Player {
    Human, Computer
}

var board = arrayListOf("", "", "", "", "", "", "", "", "")
private var currentPlayer = Player.Computer

fun updatePosition(position: Int) {
    if (board[position].isEmpty())
        if (currentPlayer == Player.Human) {
            board[position] = "X"
            currentPlayer = Player.Computer
        } else {
            board[position] = "O"
            currentPlayer = Player.Human
        }
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        ComposeTicTacToeTheme {
            Surface(
                modifier = Modifier.fillMaxWidth(),
                color = MaterialTheme.colors.background
            ) {
                Greeting(board, this::updatePosition)
            }
        }
    }
}
@Composable
fun Greeting(board: ArrayList<String>, onclick: (Int) -> Unit) {
    Column{
        Row {
            Cell(board[0]) { onclick(0) }
            Cell(board[1]) { onclick(1) }
            Cell(board[2]) { onclick(2) }
        }
        Row {
            Cell(board[3]) { onclick(3) }
            Cell(board[4]) { onclick(4) }
            Cell(board[5]) { onclick(5) }
        }
        Row {
            Cell(board[6]) { onclick(6) }
            Cell(board[7]) { onclick(7) }
            Cell(board[8]) { onclick(8) }
        }
    }
}

@Composable
fun Cell(
    name: String,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .width(130.dp)
            .height(130.dp)
            .padding(12.dp),
        elevation = 8.dp,
        contentColor = Color.Black,
        shape = RoundedCornerShape(80.dp),
        onClick = onClick
    ) {
        Text(
            name, fontSize = 80.sp,
            textAlign = TextAlign.Center,
            modifier = Modifier
                .background(color = Color.Yellow)
        )
    }
}

4

1 回答 1

1

为了让 Compose 知道需要重新组合,您必须State为您的值使用特殊的包装器。如果是数组,您可以使用mutableStateListOf代替arrayListOf

val board = mutableStateListOf("", "", "", "", "", "", "", "", "")

有关更多详细信息,我建议您从 Compose文档中的状态开始,包括这个解释基本原则的youtube 视频。

于 2022-02-10T14:47:13.653 回答