Skip to content

Commit

Permalink
persistencia mus
Browse files Browse the repository at this point in the history
  • Loading branch information
RodAlc24 committed Jun 3, 2024
1 parent 07a83dc commit 9e75451
Show file tree
Hide file tree
Showing 8 changed files with 206 additions and 61 deletions.
2 changes: 2 additions & 0 deletions app/src/main/java/com/rodalc/amarracos/main/PantallaInicio.kt
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ fun PantallaInicio(navController: NavController) {
*/
@Composable
fun Creditos(state: (Boolean) -> Unit) {
val version = "v0.5-beta-release"
val url = "https://github.com/RodAlc24/Amarracos"
val context = LocalContext.current
Dialog(onDismissRequest = { state(false) }) {
Expand All @@ -121,6 +122,7 @@ fun Creditos(state: (Boolean) -> Unit) {
Column(
modifier = Modifier.padding(10.dp)
) {
Text(text = version)
Text(text = "Amarracos está bajo la licencia MIT. Tanto la licencia como el código se encuentran publicados en GitHub:")
Text(text = url,
modifier = Modifier.clickable {
Expand Down
72 changes: 71 additions & 1 deletion app/src/main/java/com/rodalc/amarracos/mus/Mus.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
package com.rodalc.amarracos.mus

import android.content.Context
import com.rodalc.amarracos.storage.StateSaver
import com.rodalc.amarracos.storage.UndoStack
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.io.FileNotFoundException
import java.io.IOException

object Mus {
object Mus : StateSaver("mus.json") {
private var buenos: Pareja = Pareja("Buenos")
private var malos: Pareja = Pareja("Malos")
private var envites: Envites = Envites()
Expand Down Expand Up @@ -42,6 +48,13 @@ object Mus {
this.envites = envites
}

fun reset() {
this.buenos = Pareja("Buenos")
this.malos = Pareja("Malos")
this.envites = Envites()
this.puntos = 30
}

/**
* Almacena en el stack el estado actual de la partida.
*/
Expand Down Expand Up @@ -81,5 +94,62 @@ object Mus {
this.stack = UndoStack()
}

override fun loadState(context: Context) {
stack = UndoStack()
try {
val inputStream = context.openFileInput(filename)
val size = inputStream.available()
val buffer = ByteArray(size)
inputStream.read(buffer)
inputStream.close()

val jsonString = String(buffer, Charsets.UTF_8)
val temp = Json.decodeFromString<SerialicerMus>(jsonString)
this.buenos = temp.buenos
this.malos = temp.malos
this.envites = temp.envites
this.puntos = temp.puntos
} catch (e: FileNotFoundException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
}

override fun saveState(context: Context) {
val temp = SerialicerMus(
buenos = this.buenos,
malos = this.malos,
envites = this.envites,
puntos = this.puntos
)
val json =
Json.encodeToString(temp)
println(json)
context.openFileOutput(this.filename, Context.MODE_PRIVATE).use {
it.write(json.toByteArray())
}
}

/**
* Devuelve si se puedde cargar el estado de una partida anterior desde el disco o no.
* TODO ¿Es necesario?
*
* @return Si se puedde cargar el estado de una partida anterior desde el disco o no
*/
fun canLoadState(context: Context): Boolean {
return this.fileExist(context)
}

/**
* Elimina la copia del disco de la última partida.
* Reinicia el stack
*
* @param context El contexto actual
* @return Si se ha eliminado o no
*/
fun discardBackup(context: Context): Boolean {
this.stack = UndoStack()
return this.deleteFile(context)
}
}
82 changes: 76 additions & 6 deletions app/src/main/java/com/rodalc/amarracos/mus/PantallaMus.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import android.content.pm.ActivityInfo
import androidx.activity.ComponentActivity
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
Expand All @@ -15,6 +16,7 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
Expand All @@ -26,6 +28,7 @@ import androidx.compose.material.icons.rounded.Remove
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
Expand All @@ -44,6 +47,7 @@ import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.rodalc.amarracos.main.ToastRateLimiter
Expand All @@ -57,6 +61,7 @@ import com.rodalc.amarracos.main.ToastRateLimiter
fun PantallaMus() {
var showConfig by rememberSaveable { mutableStateOf(true) }
val context = LocalContext.current
var canLoad by rememberSaveable { mutableStateOf(Mus.canLoadState(context)) }
val lifecycleOwner = LocalLifecycleOwner.current

DisposableEffect(lifecycleOwner) {
Expand All @@ -80,11 +85,19 @@ fun PantallaMus() {
}
}

if (showConfig) {
PantallaConfiguracion(context) { showConfig = it }
if (canLoad) {
RecuperarDatos(context = context) {
showConfig = it
canLoad = false
}
} else {
PlantillaMus()
if (showConfig) {
PantallaConfiguracion(context) { showConfig = it }
} else {
PlantillaMus()
}
}

}

@Composable
Expand Down Expand Up @@ -149,6 +162,7 @@ fun PantallaConfiguracion(
Mus.getBuenos().nombre = if (buenos == "") "Buenos" else buenos
Mus.getMalos().nombre = if (malos == "") "Malos" else malos
Mus.setPuntos(if (puntos30) 30 else 40)
Mus.saveState(context)
show(false)
},
modifier = Modifier.padding(20.dp)
Expand Down Expand Up @@ -202,6 +216,7 @@ fun PlantillaMus() {

@Composable
fun ColumnaParejaLandscape(buenos: Boolean, viewModel: MusViewModel, onOrdago: () -> Unit) {
val context = LocalContext.current
val pareja by if (buenos) viewModel.buenos.collectAsState() else viewModel.malos.collectAsState()

Column(
Expand Down Expand Up @@ -229,6 +244,7 @@ fun ColumnaParejaLandscape(buenos: Boolean, viewModel: MusViewModel, onOrdago: (
} else {
viewModel.updateMalos(pareja.copy(puntos = pareja.puntos - 1))
}
Mus.saveState(context)
},
enabled = pareja.puntos > 0
) {
Expand All @@ -240,19 +256,24 @@ fun ColumnaParejaLandscape(buenos: Boolean, viewModel: MusViewModel, onOrdago: (
} else {
viewModel.updateMalos(pareja.copy(puntos = pareja.puntos + 1))
}
Mus.saveState(context)
}) {
Icon(Icons.Rounded.Add, contentDescription = "Add")
}
}
Spacer(modifier = Modifier.weight(1f))
Button(onClick = { onOrdago() }
Button(onClick = {
onOrdago()
Mus.saveState(context)
}
) { Text("Órdago") }
Spacer(modifier = Modifier.weight(5f))
}
}

@Composable
fun ColumnaEnvites(viewModel: MusViewModel, rondaEnvites: Boolean, changeRondaEmbites: () -> Unit) {
val context = LocalContext.current
val envites by viewModel.envites.collectAsState()
var canUndo by rememberSaveable { mutableStateOf(Mus.canUndo()) }
canUndo = Mus.canUndo()
Expand Down Expand Up @@ -296,6 +317,7 @@ fun ColumnaEnvites(viewModel: MusViewModel, rondaEnvites: Boolean, changeRondaEm
if (rondaEnvites) changeRondaEmbites()
Mus.popState()
viewModel.update()
Mus.saveState(context)
}, enabled = canUndo
) { Icon(Icons.AutoMirrored.Rounded.Undo, contentDescription = "Undo") }
}
Expand All @@ -309,6 +331,7 @@ fun FilaEnvite(
viewModel: MusViewModel,
updateEnvite: (Int) -> Unit
) {
val context = LocalContext.current
val buenos by viewModel.buenos.collectAsState()
val malos by viewModel.malos.collectAsState()

Expand All @@ -328,6 +351,7 @@ fun FilaEnvite(
viewModel.updateBuenos(buenos.copy(puntos = buenos.puntos + envite))
updateEnvite(0)
}
Mus.saveState(context)
},
enabled = envite > 0
) {
Expand All @@ -342,7 +366,10 @@ fun FilaEnvite(
fontSize = 20.sp,
modifier = Modifier
.clickable(
onClick = { updateEnvite(envite + 2) },
onClick = {
updateEnvite(envite + 2)
Mus.saveState(context)
},
enabled = rondaEnvites
)
.padding(10.dp)
Expand All @@ -355,6 +382,7 @@ fun FilaEnvite(
viewModel.updateMalos(malos.copy(puntos = malos.puntos + envite))
updateEnvite(0)
}
Mus.saveState(context)
}, enabled = rondaEnvites || envite != 0) {
if (rondaEnvites) {
Icon(Icons.Rounded.Add, contentDescription = "Add")
Expand All @@ -363,4 +391,46 @@ fun FilaEnvite(
}
}
}
}
}

/**
* Dyalog mostrado al principio para preguntar si se quieren recuperar los datos de la partida anterior.
*
* @param context El contexto actual
* @param showConfig Si se debe mostrar la pantalla de configuración o no
*/
@Composable
fun RecuperarDatos(context: Context, showConfig: (Boolean) -> Unit) {
Dialog(onDismissRequest = { }) {
Box(modifier = Modifier) {
Surface(
modifier = Modifier
.align(Alignment.Center)
.padding(10.dp),
shape = RoundedCornerShape(16.dp),
) {
Column(
modifier = Modifier.padding(10.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = "¿Recuperar la última partida?")
Row(
modifier = Modifier.padding(10.dp),
horizontalArrangement = Arrangement.SpaceAround
) {
Button(onClick = {
Mus.loadState((context))
showConfig(false)
}) { Text(text = "") }
Spacer(modifier = Modifier.width(10.dp))
Button(onClick = {
Mus.discardBackup(context)
Mus.reset()
showConfig(true)
}) { Text(text = "No") }
}
}
}
}
}
}
14 changes: 13 additions & 1 deletion app/src/main/java/com/rodalc/amarracos/mus/Pareja.kt
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package com.rodalc.amarracos.mus

import kotlinx.serialization.Serializable


@Serializable
data class Pareja(
var nombre: String,
var puntos: Int = 0,
var victorias: Int = 0
)

@Serializable
data class Envites(
var grande: Int = 0,
var chica: Int = 0,
Expand All @@ -16,4 +20,12 @@ data class Envites(
fun vacio(): Boolean {
return (this.grande + this.chica + this.pares + this.juego) == 0
}
}
}

@Serializable
data class SerialicerMus(
var buenos: Pareja,
var malos: Pareja,
var envites: Envites,
var puntos: Int
)
8 changes: 4 additions & 4 deletions app/src/main/java/com/rodalc/amarracos/pocha/PantallaPocha.kt
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ fun PantallaPocha() {
val context = LocalContext.current
var state by rememberSaveable { mutableStateOf(Ronda.NOMBRES) }
var duplica by rememberSaveable { mutableStateOf(false) }
var canLoad by rememberSaveable { mutableStateOf(Pocha.canLoad(context)) }
var canLoad by rememberSaveable { mutableStateOf(Pocha.canLoadState(context)) }
var jugadores by remember { mutableStateOf(Pocha.getJugadores()) }

if (canLoad) {
Expand Down Expand Up @@ -94,7 +94,7 @@ fun PantallaPocha() {
},
nextRound = {
Pocha.setJugadores(jugadores)
Pocha.save(context)
Pocha.saveState(context)
state = Ronda.APUESTAS
},
undo = {},
Expand Down Expand Up @@ -176,7 +176,7 @@ fun PantallaPocha() {
Pocha.pushState()
Pocha.actualizarPuntuacion(duplica)
duplica = false
Pocha.save(context)
Pocha.saveState(context)
state = Ronda.APUESTAS
},
undo = { state = Ronda.APUESTAS },
Expand Down Expand Up @@ -346,7 +346,7 @@ fun RecuperarDatos(context: Context, atExit: (Ronda) -> Unit) {
horizontalArrangement = Arrangement.SpaceAround
) {
Button(onClick = {
Pocha.load(context)
Pocha.loadState(context)
atExit(Ronda.APUESTAS)
}) { Text(text = "") }
Spacer(modifier = Modifier.width(10.dp))
Expand Down
Loading

0 comments on commit 9e75451

Please sign in to comment.