Tugas 10: Aplikasi Unscramble menggunakan ViewModel dan State pada Compose
Aplikasi Unscramble menggunakan ViewModel dan State pada Compose
Langkah 1: Membuat Proyek Baru di Android Studio
- Buka Android Studio setelah instalasi selesai.
- Klik "Start a new Android Studio project".
- Pada layar pemilihan template, pilih "Empty Compose Activity" lalu klik Next.
- Masukkan nama aplikasi (misalnya, "My Unscramble").
- Tentukan lokasi penyimpanan proyek di sistem Anda.
- Pilih Language sebagai Kotlin.
- Pastikan Use AndroidX artifacts dicentang.
- Klik Finish.
- Pada halaman "Select a minimum SDK", pilih API Level 24: Android 7.0 (Nougat) sebagai Minimum SDK.
- Android Studio akan mulai membangun proyek Anda. Tunggu hingga proses ini selesai.
Langkah 2: Mengonfigurasi File Main, dan file-file lainnya
- Setelah proyek selesai dibangun, tambahkan ViewModel untuk mengelola status UI aplikasi, seperti kata acak, skor, dan tebakan pengguna. Berikut adalah contoh implementasi ViewModel:
import androidx.lifecycle.ViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow class GameViewModel : ViewModel() { private val _uiState = MutableStateFlow(GameUiState()) val uiState: StateFlow = _uiState var userGuess by mutableStateOf("") private set private lateinit var currentWord: String private var usedWords: MutableSet = mutableSetOf() fun pickRandomWordAndShuffle(): String { currentWord = allWords.random() if (usedWords.contains(currentWord)) { return pickRandomWordAndShuffle() } else { usedWords.add(currentWord) return shuffleCurrentWord(currentWord) } } fun shuffleCurrentWord(word: String): String { val tempWord = word.toCharArray() tempWord.shuffle() while (String(tempWord).equals(word)) { tempWord.shuffle() } return String(tempWord) } fun updateUserGuess(guessedWord: String) { userGuess = guessedWord } fun checkUserGuess() { if (userGuess.equals(currentWord, ignoreCase = true)) { updateGameState() } else { _uiState.value = _uiState.value.copy(isGuessedWordWrong = true) } userGuess = "" } private fun updateGameState() { _uiState.update { currentState -> currentState.copy( currentScrambledWord = pickRandomWordAndShuffle(), score = currentState.score + 20 // Example scoring ) } } }Setelah proyek selesai dibangun, tambahkan ViewModel untuk mengelola status UI aplikasi, seperti kata acak, skor, dan tebakan pengguna. Berikut adalah contoh implementasi ViewModel:
- Buat UI menggunakan Jetpack Compose
@Composable
fun GameScreen(gameViewModel: GameViewModel = viewModel()) {
val gameUiState by gameViewModel.uiState.collectAsState()
Column(modifier = Modifier.padding(16.dp)) {
Text("Unscramble Game", style = MaterialTheme.typography.h5)
GameLayout(
currentScrambledWord = gameUiState.currentScrambledWord,
userGuess = gameViewModel.userGuess,
onUserGuessChanged = { gameViewModel.updateUserGuess(it) },
onKeyboardDone = { gameViewModel.checkUserGuess() }
)
GameStatus(score = gameUiState.score)
if (gameUiState.isGameOver) {
FinalScoreDialog(
score = gameUiState.score,
onPlayAgain = { gameViewModel.resetGame() }
)
}
}
}
@Composable
fun GameLayout(
currentScrambledWord: String,
userGuess: String,
onUserGuessChanged: (String) -> Unit,
onKeyboardDone: () -> Unit,
modifier: Modifier = Modifier
) {
Column(modifier = modifier) {
Text(text = currentScrambledWord, style = MaterialTheme.typography.h6)
OutlinedTextField(
value = userGuess,
onValueChange = onUserGuessChanged,
label = { Text("Enter your word") },
isError = false,
keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = onKeyboardDone)
)
}
}
@Composable
fun GameStatus(score: Int) {
Text("Score: $score", style = MaterialTheme.typography.body1)
}
@Composable
fun FinalScoreDialog(score: Int, onPlayAgain: () -> Unit) {
AlertDialog(
onDismissRequest = { /* Handle dismiss */ },
title = { Text("Congratulations!") },
text = { Text("You scored: $score") },
confirmButton = {
TextButton(onClick = onPlayAgain) {
Text("Play Again")
}
},
dismissButton = {
TextButton(onClick = { /* Handle exit */ }) {
Text("Exit")
}
}
)
}
@Composable fun GameScreen(gameViewModel: GameViewModel = viewModel()) { val gameUiState by gameViewModel.uiState.collectAsState() Column(modifier = Modifier.padding(16.dp)) { Text("Unscramble Game", style = MaterialTheme.typography.h5) GameLayout( currentScrambledWord = gameUiState.currentScrambledWord, userGuess = gameViewModel.userGuess, onUserGuessChanged = { gameViewModel.updateUserGuess(it) }, onKeyboardDone = { gameViewModel.checkUserGuess() } ) GameStatus(score = gameUiState.score) if (gameUiState.isGameOver) { FinalScoreDialog( score = gameUiState.score, onPlayAgain = { gameViewModel.resetGame() } ) } } } @Composable fun GameLayout( currentScrambledWord: String, userGuess: String, onUserGuessChanged: (String) -> Unit, onKeyboardDone: () -> Unit, modifier: Modifier = Modifier ) { Column(modifier = modifier) { Text(text = currentScrambledWord, style = MaterialTheme.typography.h6) OutlinedTextField( value = userGuess, onValueChange = onUserGuessChanged, label = { Text("Enter your word") }, isError = false, keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done), keyboardActions = KeyboardActions(onDone = onKeyboardDone) ) } } @Composable fun GameStatus(score: Int) { Text("Score: $score", style = MaterialTheme.typography.body1) } @Composable fun FinalScoreDialog(score: Int, onPlayAgain: () -> Unit) { AlertDialog( onDismissRequest = { /* Handle dismiss */ }, title = { Text("Congratulations!") }, text = { Text("You scored: $score") }, confirmButton = { TextButton(onClick = onPlayAgain) { Text("Play Again") } }, dismissButton = { TextButton(onClick = { /* Handle exit */ }) { Text("Exit") } } ) }
- Sesuaikan Konfigurasi Perangkat
class GameViewModel : ViewModel() {
private val _uiState = MutableStateFlow(GameUiState())
val uiState: StateFlow = _uiState.asStateFlow()
init {
resetGame()
}
private fun resetGame() {
_uiState.value = GameUiState(currentScrambledWord = pickRandomWordAndShuffle())
}
}
- Verifikasi Tebakan Pengguna dan Pembaruan Skor
fun checkUserGuess() {
if (userGuess.equals(currentWord, ignoreCase = true)) {
val updatedScore = _uiState.value.score + 20
updateGameState(updatedScore)
} else {
_uiState.update { it.copy(isGuessedWordWrong = true) }
}
userGuess = ""
}
- Dialog Akhir Permainan
class GameViewModel : ViewModel() { private val _uiState = MutableStateFlow(GameUiState()) val uiState: StateFlow = _uiState.asStateFlow() init { resetGame() } private fun resetGame() { _uiState.value = GameUiState(currentScrambledWord = pickRandomWordAndShuffle()) } }
- Verifikasi Tebakan Pengguna dan Pembaruan Skor
fun checkUserGuess() { if (userGuess.equals(currentWord, ignoreCase = true)) { val updatedScore = _uiState.value.score + 20 updateGameState(updatedScore) } else { _uiState.update { it.copy(isGuessedWordWrong = true) } } userGuess = "" }
- Dialog Akhir Permainan
@Composable fun FinalScoreDialog(score: Int, onPlayAgain: () -> Unit) { AlertDialog( onDismissRequest = { /* Handle dismiss */ }, title = { Text("Game Over") }, text = { Text("Your score is: $score") }, confirmButton = { TextButton(onClick = onPlayAgain) { Text("Play Again") } }, dismissButton = { TextButton(onClick = { /* Exit the game */ }) { Text("Exit") } } ) }
Langkah 3: Menjalankan Aplikasi
- Klik "Run" (ikon hijau di toolbar) untuk menjalankan aplikasi.
- Pilih Emulator yang sudah Anda siapkan atau sambungkan perangkat fisik Android Anda.
- Android Studio akan membangun dan menjalankan aplikasi.
- Isi kolom dengan tebakan kata yang bisa anda rangkai dari huruf-huruf yang disediakan.

.jpeg)
.jpeg)
Comments
Post a Comment