This is the GameViewModel:
data class Disc(var color: Color){
}
class GameViewModel:ViewModel() {
private val boardWidth = 7
private val boardHeight = 6
private val emptyDisc = Disc(Color.White)
private val _board = mutableStateListOf<List<Disc>>()
val board: List<List<Disc>>
get() = _board
private var currentPlayer = Color.Red
fun dropDisc(columnIndex: Int) {
val column = _board[columnIndex].toMutableList()
val emptySlot = column.indexOfFirst { it.color == Color.White }
if (emptySlot != -1) {
column[emptySlot].color = currentPlayer
currentPlayer = if (currentPlayer == Color.Red) Color.Yellow else Color.Red
_board[columnIndex] = column
}
}
}
//This is my GameScreen
@Composable
fun GameScreen(
gameViewModel: GameViewModel= viewModel(),
){
ConnectFourGame(gameViewModel = gameViewModel)
}
@Composable
fun BoardView(board: List<List<Disc>>, gameViewModel: GameViewModel){
Box(
modifier = Modifier
.background(Color.Blue)
.padding(4.dp)
){
Column {
for(row in 0 until 6){
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly
){
for (column in 0 until 7){
Box(
modifier = Modifier
.size(50.dp)
.padding(4.dp)
.background(
color=board[column][row].color,
shape = CircleShape
)
.clickable {
gameViewModel.dropDisc(column)
}
)
}
}
}
}
}
}
@Composable
fun ConnectFourGame(
gameViewModel: GameViewModel = viewModel(),
){
val board = gameViewModel.board
Column (
modifier= Modifier
.fillMaxSize()
.padding(10.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
){
Text(text = "Connect Four Game")
Spacer(modifier = Modifier.height(16.dp))
BoardView(board = board, gameViewModel = gameViewModel)
}
}
I have wirtten the dropDisc as you can see but it doesnt want to work so i dont know what i can change?
I have written the code as you can see, i want the circle to change color to red then yellow when clicking on a empty circle. I have to write more but i feel like i already have explained but it doesnt let me post.... I have other parts like resetboard on the code but i couldnt put in in here