提问人:Mattias 提问时间:11/16/2023 最后编辑:Mattias 更新时间:11/16/2023 访问量:27
我正在尝试做一个连接四游戏,我正在尝试制作一个 dropDisc 函数。我写过这个:
I am trying to do a connect four game and i am trying to make a dropDisc function. I have writen this:
问:
这是 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)
}
}
正如你所看到的,我已经使用了dropDisc,但它不想工作,所以我不知道我可以改变什么?
如您所见,我已经编写了代码,我希望在单击空圆圈时将圆圈的颜色变为红色,然后变为黄色。 我必须写更多,但我觉得我已经解释过了,但它不允许我发布......我在代码上还有其他部分,例如重置板,但我无法在此处放入
答: 暂无答案
评论