VictorMunoz

Reto UF2

Mar 30th, 2024
706
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.18 KB | None | 0 0
  1. package com.victormp.reto2;
  2.  
  3. import android.media.MediaPlayer;
  4. import android.os.Bundle;
  5. import android.os.Handler;
  6. import android.view.View;
  7. import android.widget.Button;
  8. import android.widget.TextView;
  9. import android.widget.Toast;
  10.  
  11. import androidx.activity.EdgeToEdge;
  12. import androidx.appcompat.app.AppCompatActivity;
  13. import androidx.core.graphics.Insets;
  14. import androidx.core.view.ViewCompat;
  15. import androidx.core.view.WindowInsetsCompat;
  16.  
  17. import java.util.Random;
  18.  
  19. public class MainActivity extends AppCompatActivity {
  20.  
  21.     // Declaración de variables
  22.     protected TextView operacionTextView;
  23.     protected int num1, num2, resultadoCorrecto;
  24.     protected String enunciado;
  25.     private final Button[] opcionesButtons = new Button[3];
  26.  
  27.     Random random = new Random();
  28.  
  29.     @Override
  30.     protected void onCreate(Bundle savedInstanceState) {
  31.         super.onCreate(savedInstanceState);
  32.         EdgeToEdge.enable(this);
  33.         setContentView(R.layout.activity_main);
  34.         ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
  35.             Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
  36.             v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
  37.             return insets;
  38.         });
  39.  
  40.         // Inicializar elementos de la UI
  41.         operacionTextView = findViewById(R.id.operacionTextView);
  42.         opcionesButtons[0] = findViewById(R.id.opcion1Button);
  43.         opcionesButtons[1] = findViewById(R.id.opcion2Button);
  44.         opcionesButtons[2] = findViewById(R.id.opcion3Button);
  45.  
  46.         // Iterar por todos los botones agrupados en el array
  47.         for (Button button : opcionesButtons) {
  48.             // Crear Click Listeners que comproben si se ha marcado la respuesta correcta
  49.             button.setOnClickListener(new View.OnClickListener() {
  50.                 @Override
  51.                 public void onClick(View v) {
  52.                     Button btn = (Button) v;
  53.                     // Obtener el texto del botón seleccionado y parsearlo a INT
  54.                     int opcionSeleccionada = Integer.parseInt(btn.getText().toString());
  55.                     // Llamar a la función para comprobar la respuesta seleccionada por el usuario
  56.                     verifyAnswer(opcionSeleccionada);
  57.                 }
  58.             });
  59.         }
  60.  
  61.         // Crear una suma inicial al arrancar MainActivity
  62.         createSum ();
  63.     }
  64.  
  65.     // Método para crear una nueva suma / enunciado
  66.     private void createSum () {
  67.         // Generar números aleatorios entre 1 y 9 para la suma
  68.         num1 = random.nextInt(9)+1; // Bound 9, + 1 para evitar que genere un valor 0
  69.         num2 = random.nextInt(9)+1;
  70.         // Concatenar ambos números para crear el String del enunciado
  71.         enunciado = num1 + " + " + num2 + " = ?";
  72.         operacionTextView.setText(enunciado);
  73.         // Calcular la respuesta correcta
  74.         resultadoCorrecto = num1 + num2;
  75.  
  76.         // Asignar el resultado correcto a uno de los botones de forma aleatoria a partir de su posición en el array
  77.         int indexResultadoCorrecto = random.nextInt(opcionesButtons.length);
  78.         opcionesButtons[indexResultadoCorrecto].setText(String.valueOf(resultadoCorrecto));
  79.  
  80.         // Generar valores para los otros botones (puede crear resultados erróneos idénticos al no comprobarse entre ellos)
  81.         for (int i = 0; i < opcionesButtons.length; i++) {
  82.             if (i != indexResultadoCorrecto) {
  83.                 // Crear un valor de confusión para asemejarlo al resultado:
  84.                 // Dividirlo entre 2 y añadir 1 (para evitar que confusión tenga valor 0 y coincida con la respuesta correcta)
  85.                 int confusion = random.nextInt(resultadoCorrecto / 2) + 1;
  86.                 // Aleatoriamente (50/50) suma o resta el valor de confusión al resultado
  87.                 if (random.nextBoolean()) {
  88.                     opcionesButtons[i].setText(String.valueOf(resultadoCorrecto - confusion));
  89.                 } else {
  90.                     opcionesButtons[i].setText(String.valueOf(resultadoCorrecto + confusion));
  91.                 }
  92.             }
  93.         }
  94.     }
  95.  
  96.     // Método para comprobar la respuesta seleccionada
  97.     private void verifyAnswer(int respuestaSeleccionada){
  98.         // Declarar la variable para reproducir efectos musicales
  99.         MediaPlayer soundEffect;
  100.  
  101.         // Comprobar si se ha marcado la respuesta correcta
  102.         if (respuestaSeleccionada == resultadoCorrecto) {
  103.             // Mostrar mensaje de éxito
  104.             Toast.makeText(this, "¡Respuesta correcta!", Toast.LENGTH_SHORT).show();
  105.             // Reproducir sonido de respuesta correcta
  106.             soundEffect = MediaPlayer.create(MainActivity.this, R.raw.correct);
  107.             soundEffect.start();
  108.             // Listener para detener la reprodución cuando termine de reproducirse y evitar bucles
  109.             soundEffect.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
  110.                 @Override
  111.                 public void onCompletion(MediaPlayer soundEffect) {
  112.                     soundEffect.stop();
  113.                 }
  114.             });
  115.             // Crear un Handler para crear una nueva suma (resetear la actividad) con 2 segundos de delay
  116.             new Handler().postDelayed(new Runnable() {
  117.                 @Override
  118.                 public void run() {
  119.                     createSum();
  120.                 }
  121.             }, 2000);
  122.  
  123.         // si se ha seleccionado una respuesta errrónea
  124.         } else {
  125.             // Mostrar mensaje de fallo
  126.             Toast.makeText(this, "Respuesta incorrecta, intentalo de nuevo.", Toast.LENGTH_SHORT).show();
  127.             // Reproduducir sonido de respuesta errónea
  128.             soundEffect = MediaPlayer.create(MainActivity.this, R.raw.error);
  129.             soundEffect.start();
  130.             // Listener para detener la reprodución cuando termine de reproducirse y evitar bucles
  131.             soundEffect.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
  132.                 @Override
  133.                 public void onCompletion(MediaPlayer soundEffect) {
  134.                     soundEffect.stop();
  135.                 }
  136.             });
  137.         }
  138.     }
  139. }
Advertisement
Add Comment
Please, Sign In to add comment