⎇ 3ae5fa52dc10b21c431254e04a1b57e824fe7590
cubo/src/main/java/com/rizoma/cubo/data/Progreso.kt
Historia
crudo
Cubo: nuevo módulo — 2048 en 3D con OpenGL ES 2.0
1package com.rizoma.cubo.data
2
3import android.content.Context
4import androidx.datastore.core.DataStore
5import androidx.datastore.preferences.core.Preferences
6import androidx.datastore.preferences.core.edit
7import androidx.datastore.preferences.core.intPreferencesKey
8import androidx.datastore.preferences.preferencesDataStore
9import kotlinx.coroutines.flow.Flow
10import kotlinx.coroutines.flow.map
11
12private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "cubo")
13
14/** Récords del cubo, persistidos en DataStore: mejor puntuación y mejor baldosa. */
15class Progreso(context: Context) {
16 private val store = context.applicationContext.dataStore
17
18 val mejorScore: Flow<Int> = store.data.map { it[KEY_SCORE] ?: 0 }
19 val mejorBaldosa: Flow<Int> = store.data.map { it[KEY_TILE] ?: 0 }
20
21 suspend fun registrar(score: Int, baldosa: Int) {
22 store.edit { p ->
23 if (score > (p[KEY_SCORE] ?: 0)) p[KEY_SCORE] = score
24 if (baldosa > (p[KEY_TILE] ?: 0)) p[KEY_TILE] = baldosa
25 }
26 }
27
28 private companion object {
29 val KEY_SCORE = intPreferencesKey("mejor_score")
30 val KEY_TILE = intPreferencesKey("mejor_baldosa")
31 }
32}