https://kotlinlang.org logo
#compose
Title
# compose
n

Nat Strangerweather

02/24/2022, 4:37 PM
How can I reload (recompose) my game board on the click of a button? 🧵
Copy code
@Composable
fun GameBoard() {
    val viewModel: MainViewModel = viewModel()

    val boardLetters = viewModel.shakeLetterBag().sliceArray(0..48)

       Column(
        horizontalAlignment = Alignment.Start,
        verticalArrangement = Arrangement.Center,
    ) {
        LazyVerticalGrid(
            cells = GridCells.Fixed(7),
            verticalArrangement = <http://Arrangement.Top|Arrangement.Top>
        ) {
            items(boardLetters) { data ->
                Piece(data)
            }
        }
    }
}
Copy code
@Composable
fun HomePage() {
    Scaffold(
        floatingActionButton = {
            FloatingActionButton(onClick = {

            }) {
                Icon(imageVector = Icons.Filled.Refresh, contentDescription = "refresh icon")
            }
        }
    ) {
        Column(
            Modifier
                .fillMaxSize()
                .padding(10.dp)
        ) {
            ScoreBoard()
            WordBoard()
            GameBoard()
            Button()
        }
    }
}
I have created the FAB in my HomePage to restart the game.
c

Chris Fillmore

02/24/2022, 4:51 PM
Looking at your code, my understanding here is your
boardLetters
should be some state in your view model, like this:
Copy code
class MainViewModel : ViewModel() {
  ...
  var boardLetters by mutableStateOf(/* initial value */)
}
Your composable will recompose based on your game’s state. So as
boardLetters
gets updated, the UI will redraw. So, in order to completely reset your game, all you need to do is set
boardLetters
back to its initial value.
So you could have a button like:
Copy code
Button(onClick = {
  mainViewModel.boardLetters = /* initial value */
}) {
  Text("Reset game")
}
n

Nat Strangerweather

02/24/2022, 4:56 PM
Oh I see! Thanks very much, will try that out! 😊
👍 1