Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.victormp.reto2;
- import android.media.MediaPlayer;
- import android.os.Bundle;
- import android.os.Handler;
- import android.view.View;
- import android.widget.Button;
- import android.widget.TextView;
- import android.widget.Toast;
- import androidx.activity.EdgeToEdge;
- import androidx.appcompat.app.AppCompatActivity;
- import androidx.core.graphics.Insets;
- import androidx.core.view.ViewCompat;
- import androidx.core.view.WindowInsetsCompat;
- import java.util.Random;
- public class MainActivity extends AppCompatActivity {
- // Declaración de variables
- protected TextView operacionTextView;
- protected int num1, num2, resultadoCorrecto;
- protected String enunciado;
- private final Button[] opcionesButtons = new Button[3];
- Random random = new Random();
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- EdgeToEdge.enable(this);
- setContentView(R.layout.activity_main);
- ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
- Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
- v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
- return insets;
- });
- // Inicializar elementos de la UI
- operacionTextView = findViewById(R.id.operacionTextView);
- opcionesButtons[0] = findViewById(R.id.opcion1Button);
- opcionesButtons[1] = findViewById(R.id.opcion2Button);
- opcionesButtons[2] = findViewById(R.id.opcion3Button);
- // Iterar por todos los botones agrupados en el array
- for (Button button : opcionesButtons) {
- // Crear Click Listeners que comproben si se ha marcado la respuesta correcta
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Button btn = (Button) v;
- // Obtener el texto del botón seleccionado y parsearlo a INT
- int opcionSeleccionada = Integer.parseInt(btn.getText().toString());
- // Llamar a la función para comprobar la respuesta seleccionada por el usuario
- verifyAnswer(opcionSeleccionada);
- }
- });
- }
- // Crear una suma inicial al arrancar MainActivity
- createSum ();
- }
- // Método para crear una nueva suma / enunciado
- private void createSum () {
- // Generar números aleatorios entre 1 y 9 para la suma
- num1 = random.nextInt(9)+1; // Bound 9, + 1 para evitar que genere un valor 0
- num2 = random.nextInt(9)+1;
- // Concatenar ambos números para crear el String del enunciado
- enunciado = num1 + " + " + num2 + " = ?";
- operacionTextView.setText(enunciado);
- // Calcular la respuesta correcta
- resultadoCorrecto = num1 + num2;
- // Asignar el resultado correcto a uno de los botones de forma aleatoria a partir de su posición en el array
- int indexResultadoCorrecto = random.nextInt(opcionesButtons.length);
- opcionesButtons[indexResultadoCorrecto].setText(String.valueOf(resultadoCorrecto));
- // Generar valores para los otros botones (puede crear resultados erróneos idénticos al no comprobarse entre ellos)
- for (int i = 0; i < opcionesButtons.length; i++) {
- if (i != indexResultadoCorrecto) {
- // Crear un valor de confusión para asemejarlo al resultado:
- // Dividirlo entre 2 y añadir 1 (para evitar que confusión tenga valor 0 y coincida con la respuesta correcta)
- int confusion = random.nextInt(resultadoCorrecto / 2) + 1;
- // Aleatoriamente (50/50) suma o resta el valor de confusión al resultado
- if (random.nextBoolean()) {
- opcionesButtons[i].setText(String.valueOf(resultadoCorrecto - confusion));
- } else {
- opcionesButtons[i].setText(String.valueOf(resultadoCorrecto + confusion));
- }
- }
- }
- }
- // Método para comprobar la respuesta seleccionada
- private void verifyAnswer(int respuestaSeleccionada){
- // Declarar la variable para reproducir efectos musicales
- MediaPlayer soundEffect;
- // Comprobar si se ha marcado la respuesta correcta
- if (respuestaSeleccionada == resultadoCorrecto) {
- // Mostrar mensaje de éxito
- Toast.makeText(this, "¡Respuesta correcta!", Toast.LENGTH_SHORT).show();
- // Reproducir sonido de respuesta correcta
- soundEffect = MediaPlayer.create(MainActivity.this, R.raw.correct);
- soundEffect.start();
- // Listener para detener la reprodución cuando termine de reproducirse y evitar bucles
- soundEffect.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
- @Override
- public void onCompletion(MediaPlayer soundEffect) {
- soundEffect.stop();
- }
- });
- // Crear un Handler para crear una nueva suma (resetear la actividad) con 2 segundos de delay
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- createSum();
- }
- }, 2000);
- // si se ha seleccionado una respuesta errrónea
- } else {
- // Mostrar mensaje de fallo
- Toast.makeText(this, "Respuesta incorrecta, intentalo de nuevo.", Toast.LENGTH_SHORT).show();
- // Reproduducir sonido de respuesta errónea
- soundEffect = MediaPlayer.create(MainActivity.this, R.raw.error);
- soundEffect.start();
- // Listener para detener la reprodución cuando termine de reproducirse y evitar bucles
- soundEffect.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
- @Override
- public void onCompletion(MediaPlayer soundEffect) {
- soundEffect.stop();
- }
- });
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment