Share via


Paso 3: Agregar un temporizador de cuenta atrás

Como esta prueba tiene límite de tiempo, vamos a agregar un temporizador de la cuenta atrás.Es preciso que el programa realice el seguimiento del número de segundos que quedan a medida que el juego progresa.

Para agregar un temporizador de cuenta atrás

  1. Agregue un valor de tipo int (Integer) denominado timeLeft, como hemos hecho previamente.El código debe tener un aspecto parecido al siguiente.

    Public Class Form1
    
        ' Create a Random object to generate random numbers.
        Dim randomizer As New Random
    
        ' These Integers will store the numbers
        ' for the addition problem.
        Dim addend1 As Integer
        Dim addend2 As Integer
    
        ' This Integer will keep track of the time left.
        Dim timeLeft As Integer
    
    public partial class Form1 : Form
    {
        // Create a Random object to generate random numbers.
        Random randomizer = new Random();
    
        // These ints will store the numbers
        // for the addition problem.
        int addend1;
        int addend2;
    
        // This int will keep track of the time left.
        int timeLeft;
    
  2. Ahora, hay que agregar algo que cuente el tiempo de verdad, como un temporizador.Vaya al Diseñador de Windows Forms y arrastre un control Timer del Cuadro de herramientas (en la categoría Componentes) hasta el formulario.Aparecerá en el área gris de la parte inferior del Diseñador de Windows Forms.

  3. Haga clic en el icono timer1 que acaba de agregar y establezca la propiedad Interval en 1000.Esto hace que el evento Tick se desencadene cada segundo.A continuación, haga doble clic en el icono para agregar el controlador de eventos Tick.El IDE cambiará al editor de código y saltará al nuevo método de control de eventos.Agregue las instrucciones siguientes.

    Private Sub Timer1_Tick() Handles Timer1.Tick
    
        If (timeLeft > 0) Then
            ' 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 (timeLeft > 0)
        {
            // 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;
        }
    }
    

    Según lo que hemos agregado, cada segundo el temporizador comprobará si se ha agotado el tiempo. Para ello, comprueba si el valor de tipo int (Integer) de timeLeft es mayor que 0.Si lo es, queda tiempo.En primer lugar, el temporizador resta 1 a timeLeft y, a continuación, actualiza la propiedad Text del control timeLabel para mostrar al usuario cuántos segundos quedan.

    Si no queda tiempo, el temporizador se detiene y cambia el texto del control timeLabel de modo que muestre que se agotó el tiempo. Aparecerá un cuadro de mensaje que indicará al usuario que la prueba ha finalizado.Se revela la respuesta. En este caso, se suman addend1 y addend2.La propiedad Enabled del control startButton se establece en true, para que botón vuelva a estar disponible.De ese modo, el usuario puede volver a empezar la prueba.

    Hemos agregado una instrucción if else, que es la manera de indicar a los programas que tomen decisiones.Una instrucción if else tiene el siguiente aspecto.

    If (something your program will check) Then
        ' statements that will get executed
        ' if the thing that the program checked is true 
    Else
        ' statements that will get executed
        ' if the thing that the program checked is NOT true
    End If
    
    if (something your program will check)
    {
        // statements that will get executed
        // if the thing that the program checked is true 
    }
    else
    {
        // statements that will get executed
        // if the thing that the program checked is NOT true
    }
    

    Vamos a fijarnos con más atención en la instrucción que hemos agregado en el bloque else, para mostrar la respuesta al problema de suma.

    sum.Value = addend1 + addend2
    
    sum.Value = addend1 + addend2;
    

    Como probablemente sabrá, addend1 + addend2 suma los dos valores.La primera parte (sum.Value) utiliza la propiedad Value del control NumericUpDown para mostrar la respuesta correcta.La propiedad Value se utiliza de nuevo más tarde, para comprobar las respuestas de la prueba.

    Un control NumericUpDown facilita al usuario la escritura de números. Este es el motivo por el que se utiliza este control para las respuestas a los problemas de matemáticas.Dado que todas las respuestas son números del 0 al 100, se dejan las propiedades predeterminadas Minimum y Maximum establecidas en 0 y 100.Esto hace que el control únicamente permita al usuario escribir un número del 0 al 100.Como las respuestas solo pueden ser números enteros, la propiedad DecimalPlaces se deja establecida en 0, lo que significa que el usuario no puede escribir decimales.(Si desea permitir que el usuario escriba 3,141 pero no 3,1415, podría establecer la propiedad DecimalPlaces en 3.)

  4. Agregue tres líneas al final de método StartTheQuiz(), de modo que el código tenga este aspecto.

    ''' <summary>
    ''' Start the quiz by filling in all of the problems
    ''' and starting the timer.
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub StartTheQuiz()
    
        ' Fill in the addition problem.
        addend1 = randomizer.Next(51)
        addend2 = randomizer.Next(51)
        plusLeftLabel.Text = addend1.ToString
        plusRightLabel.Text = addend2.ToString
        sum.Value = 0
    
        ' Start the timer.
        timeLeft = 30
        timeLabel.Text = "30 seconds"
        Timer1.Start()
    
    End Sub
    
    /// <summary>
    /// Start the quiz by filling in all of the problems
    /// and starting the timer.
    /// </summary>
    public void StartTheQuiz()
    {
        // Fill in the addition problem.
        addend1 = randomizer.Next(51);
        addend2 = randomizer.Next(51);
        plusLeftLabel.Text = addend1.ToString();
        plusRightLabel.Text = addend2.ToString();
        sum.Value = 0;
    
        // Start the timer.
        timeLeft = 30;
        timeLabel.Text = "30 seconds"; 
        timer1.Start();
    }
    

    Ahora, al empezar la prueba, establece el valor de tipo int (Integer) de timeLeft en 30 y cambia la propiedad Text del control timeLabel a 30 segundos.A continuación, llama al método Start() del control Timer para iniciar la cuenta atrás.(Todavía no comprueba la respuesta, esto viene después.)

  5. Guarde y ejecute el programa.Al hacer clic en el botón de inicio, el temporizador debería iniciar la cuenta atrás.Cuando se agota el tiempo, la prueba finaliza y se muestra la respuesta.En la siguiente imagen se muestra la prueba en marcha.

    Prueba matemática en marcha

    Prueba matemática en curso

Para continuar o revisar