tetris jetpackcompose game
1.0.0

build.gradle : implementation " androidx.compose.ui:ui:1.x.x "
implementation " androidx.compose.material:material:1.x.x "
implementation " androidx.compose.ui:ui-tooling:1.x.x "
implementation " androidx.lifecycle:lifecycle-runtime-ktx:2.x.x " การตั้งค่ากริด: กำหนดกริดที่แสดงถึงกระดาน Tetris ใช้อาร์เรย์ 2D หรือรายการของรายการเพื่อติดตามสถานะของเกม (เช่นกรอก, ว่างเปล่า, สีบล็อก)
val grid = Array ( 20 ) { Array ( 10 ) { 0 } } // 20 rows, 10 columnsรูปร่าง Tetrimino: สร้างรูปร่างบล็อกที่แตกต่างกัน (L, T, I, O, ฯลฯ ) โดยใช้อาร์เรย์ 2D แต่ละบล็อกสามารถมีสถานะการหมุนที่อัปเดตเมื่อผู้เล่นหมุนชิ้นส่วน
val blockI = arrayOf(
arrayOf( 1 , 1 , 1 , 1 ),
arrayOf( 0 , 0 , 0 , 0 )
)LaunchedEffect กับ rememberCoroutineScope เพื่อสร้างลูปเกมที่ควบคุมสถานะเกม (บล็อกการเคลื่อนไหวการหมุนการตรวจจับการชนกัน ฯลฯ ) LaunchedEffect ( Unit ) {
while ( true ) {
delay( 500L ) // Control block speed
moveBlockDown()
}
}Canvas หรือคอมโพสิต Box แต่ละบล็อกบนกริดอาจเป็นสี่เหลี่ยมสี Canvas (modifier = Modifier .size( 300 .dp)) {
for (row in grid) {
for (cell in row) {
if (cell != 0 ) {
drawRect(color = Color . Blue , size = Size ( 30f , 30f ))
}
}
}
}Modifier.pointerInput หรือโดยการแมปไปยังปุ่มฮาร์ดแวร์เช่นปุ่มลูกศร Modifier .pointerInput( Unit ) {
detectTapGestures(onDoubleTap = { rotateBlock() })
} fun clearLines () {
for (i in grid.indices) {
if (grid[i].all { it != 0 }) {
grid.removeAt(i)
grid.add( 0 , Array ( 10 ) { 0 })
}
}
}Text remember และ MutableState เพื่อจัดการสถานะเกม (ตำแหน่งบล็อกปัจจุบัน, กริด, คะแนน) var score by remember { mutableStateOf( 0 ) }Modifier.size() เพื่อให้แน่ใจว่าเกมดูดีในขนาดหน้าจอที่แตกต่างกันบทความพิเศษ