Share via


Paso 4: Agregar el método CheckTheAnswer()

Es preciso que la prueba compruebe si el usuario responde correctamente.Afortunadamente, escribir métodos que realizan un cálculo simple, como el método CheckTheAnswer(), no es difícil.

Nota

Para quienes están realizando este tutorial en Visual Basic, cabe destacar que, como este método devuelve un valor, en lugar de la palabra clave Sub usual deberán utilizar la palabra clave Function.Realmente es así de sencillo: las subrutinas no devuelven valores, las funciones, sí.

Para agregar el método CheckTheAnswer()

  1. Agregue el método CheckTheAnswer(), que suma addend1 y addend2, y comprueba si la adición es igual al valor del control NumericUpDown de suma.Si la suma es igual, el método devuelve true; si no, devuelve false.El código debe tener un aspecto parecido al siguiente.

    ''' <summary>
    ''' Check the answer to see if the user got everything right.
    ''' </summary>
    ''' <returns>True if the answer's correct, false otherwise.</returns>
    ''' <remarks></remarks>
    Public Function CheckTheAnswer() As Boolean
    
        If addend1 + addend2 = sum.Value Then
            Return True
        Else
            Return False
        End If
    
    End Function
    
    /// <summary>
    /// Check the answer to see if the user got everything right.
    /// </summary>
    /// <returns>True if the answer's correct, false otherwise.</returns>
    private bool CheckTheAnswer()
    {
        if (addend1 + addend2 == sum.Value)
            return true;
        else
            return false;
    }
    

    El programa debe llamar a este método para comprobar si el usuario respondió correctamente.Para ello, se agrega if else a la instrucción.La instrucción tiene un aspecto parecido al siguiente.

    If CheckTheAnswer() Then
        ' statements that will get executed
        ' if the answer is correct 
    ElseIf timeLeft > 0 Then
        ' statements that will get executed
        ' if there's still time left on the timer
    Else
        ' statements that will get executed if the timer ran out
    End If
    
    if (CheckTheAnswer())
    {
          // statements that will get executed
          // if the answer is correct 
    }
    else if (timeLeft > 0)
    {
          // statements that will get executed
          // if there's still time left on the timer
    }
    else
    {
          // statements that will get executed if the timer ran out
    }  
    
  2. Luego, se modifica el controlador de eventos Tick del temporizador para comprobar la respuesta.El nuevo controlador de eventos con comprobación de respuesta debería incluir lo siguiente.

    Private Sub Timer1_Tick() Handles Timer1.Tick
    
        If CheckTheAnswer() Then
            ' If the user got the answer right, stop the timer
            ' and show a MessageBox.
            Timer1.Stop()
            MessageBox.Show("You got all of the answers right!", "Congratulations!")
            startButton.Enabled = True
        ElseIf timeLeft > 0 Then
            ' Decrease the time left by one second and display
            ' the new time left by updating the Time Left label.
            timeLeft = timeLeft - 1
            timeLabel.Text = timeLeft & " seconds"
        Else
            ' If the user ran out of time, stop the timer, show
            ' a MessageBox, and fill in the answers.
            Timer1.Stop()
            timeLabel.Text = "Time's up!"
            MessageBox.Show("You didn't finish in time.", "Sorry")
            sum.Value = addend1 + addend2
            startButton.Enabled = True
        End If
    
    End Sub
    
    private void timer1_Tick(object sender, EventArgs e)
    {
        if (CheckTheAnswer())
        {
            // If the user got the answer right, stop the timer 
            // and show a MessageBox.
            timer1.Stop();
            MessageBox.Show("You got all the answers right!",
                            "Congratulations");
            startButton.Enabled = true;
        }
        else if (timeLeft > 0)
        {
            // Decrease the time left by one second and display 
            // the new time left by updating the Time Left label.
            timeLeft--;
            timeLabel.Text = timeLeft + " seconds";
        }
        else
        {
            // If the user ran out of time, stop the timer, show
            // a MessageBox, and fill in the answers.
            timer1.Stop();
            timeLabel.Text = "Time's up!";
            MessageBox.Show("You didn't finish in time.", "Sorry");
            sum.Value = addend1 + addend2;
            startButton.Enabled = true;
        }
    }
    

    Ahora, si el controlador de eventos del temporizador detecta que el usuario respondió correctamente, detiene el temporizador, muestra un mensaje de felicitación y hace que el botón de inicio vuelva a estar disponible.

  3. Guarde y ejecute el programa.Inicie el juego y escriba la respuesta correcta al problema de suma.

    Nota

    Al escribir la respuesta, puede que observe algo extraño en el control NumericUpDown.Si empieza a escribir sin seleccionar toda la respuesta, el cero no desaparece y hay que eliminarlo manualmente.Corregiremos esto más adelante en este tutorial.

  4. Al escribir la respuesta correcta, debe abrirse el cuadro de mensaje, detenerse el temporizador y volver a estar disponible el botón de inicio.Haga clic de nuevo en el botón de inicio para asegurarse de que suceda así.

Para continuar o revisar