Share via


Paso 3: Agregar un temporizador de cuenta atrás

En la tercera parte de este tutorial, agregará un temporizador de cuenta atrás para el seguimiento del número de segundos que quedan para que el jugador finalice.

[!NOTA]

Este tema forma parte de una serie de tutoriales sobre conceptos de codificación básicos.Para obtener información general sobre el tutorial, vea Tutorial 2: Crear una prueba matemática cronometrada.

Para agregar un temporizador de cuenta atrás

  1. Agregue una variable de entero denominada timeLeft, tal y como hizo en el procedimiento anterior.El código debe tener un aspecto parecido al siguiente.

    Public Class Form1
    
        ' Create a Random object called randomizer  
        ' to generate random numbers. 
        Private randomizer As New Random
    
        ' These integer variables store the numbers  
        ' for the addition problem.  
        Private addend1 As Integer 
        Private addend2 As Integer 
    
        ' This integer variable keeps track of the  
        ' remaining time. 
        Private timeLeft As Integer
    
    public partial class Form1 : Form
    {
        // Create a Random object called randomizer  
        // to generate random numbers.
        Random randomizer = new Random();
    
        // These integer variables store the numbers  
        // for the addition problem.  
        int addend1;
        int addend2;
    
        // This integer variable keeps track of the  
        // remaining time. 
        int timeLeft;
    

    Ahora necesita un método que cuente realmente los segundos, como un temporizador, y que genere un evento después del tiempo especificado.

  2. En la ventana de diseño, mueva un control Timer de la categoría Componentes del Cuadro de herramientas al formulario.

    El control aparece en el área gris de la parte inferior de la ventana de diseño.

  3. En el formulario, elija el icono timer1 que acaba de agregar y establezca su propiedad Interval en 1000.

    Dado que el valor de intervalo está en milisegundos, el valor 1000 hace que el evento Tick se genere cada segundo.

  4. En el formulario, haga doble clic en el control Timer o selecciónelo y elija la tecla Entrar.

    Aparece un editor de código en el que se muestra el método del controlador de eventos Tick que acaba de agregar.

  5. Agregue las siguientes instrucciones al nuevo método de control de eventos.

    Private Sub Timer1_Tick() Handles Timer1.Tick
    
        If timeLeft > 0 Then 
            ' Display the new time left 
            ' by updating the Time Left label.
            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;
        }
    }
    

    En función de lo que haya agregado, el temporizador comprobará a cada segundo si se ha agotado el tiempo, determinando si la variable de entero timeLeft es mayor que 0.Si es así, todavía 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 jugador cuántos segundos quedan.

    Si no queda tiempo, el temporizador se detiene y cambia el texto del control timeLabel para que muestre que se agotó el tiempo. Un cuadro de mensaje anuncia que la prueba ha finalizado y revela la respuesta; en este caso, la suma de addend1 y addend2.La propiedad Enabled del control startButton se establece en true para que el jugador pueda iniciar otra 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.

    [!NOTA]

    El ejemplo siguiente tiene solo fines ilustrativos. No lo agregue al proyecto.

    If (something that your program will check) Then
        ' One or more statements that will run
        ' if what the program checked is true. 
    Else
        ' One or more statements that will run
        ' if what the program checked is false.
    End If
    
    if (something that your program will check)
    {
        // One or more statements that will run
        // if what the program checked is true. 
    }
    else
    {
        // One or more statements that will run
        // if what the program checked is false.
    }
    

    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;
    

    La instrucción addend1 + addend2 suma los valores de las dos variables.La primera parte (sum.Value) utiliza la propiedad Value del control NumericUpDown de la suma para mostrar la respuesta correcta.Utilizará la misma propiedad más adelante para comprobar las respuestas de la prueba.

    Los jugadores pueden escribir los números con más facilidad si se usa un control NumericUpDown. Este es el motivo por el que se utiliza este control para las respuestas a los problemas de matemáticas.Todas las respuestas posibles son números enteros comprendidos entre 0 y 100.Al dejar los valores predeterminados de las propiedades Minimum, Maximum y DecimalPlaces, se asegura de que los jugadores no puedan escribir decimales, números negativos o números que sean demasiado altos. (Si desea permitir que los jugadores escriban 3,141 pero no 3,1415, puede establecer la propiedad DecimalPlaces en 3).

  6. 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 problem  
    ''' values and starting the timer.  
    ''' </summary> 
    ''' <remarks></remarks> 
    Public Sub StartTheQuiz()
    
        ' Fill in the addition problem. 
        ' Generate two random numbers to add. 
        ' Store the values in the variables 'addend1' and 'addend2'.
        addend1 = randomizer.Next(51)
        addend2 = randomizer.Next(51)
    
        ' Convert the two randomly generated numbers 
        ' into strings so that they can be displayed 
        ' in the label controls.
        plusLeftLabel.Text = addend1.ToString()
        plusRightLabel.Text = addend2.ToString()
    
        ' 'sum' is the name of the NumericUpDown control. 
        ' This step makes sure its value is zero before 
        ' adding any values to it.
        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 problem  
    /// values and starting the timer.  
    /// </summary> 
    public void StartTheQuiz()
    {
        // Fill in the addition problem. 
        // Generate two random numbers to add. 
        // Store the values in the variables 'addend1' and 'addend2'.
        addend1 = randomizer.Next(51);
        addend2 = randomizer.Next(51);
    
        // Convert the two randomly generated numbers 
        // into strings so that they can be displayed 
        // in the label controls.
        plusLeftLabel.Text = addend1.ToString();
        plusRightLabel.Text = addend2.ToString();
    
    
        // 'sum' is the name of the NumericUpDown control. 
        // This step makes sure its value is zero before 
        // adding any values to it.
        sum.Value = 0;
    
        // Start the timer.
        timeLeft = 30;
        timeLabel.Text = "30 seconds"; 
        timer1.Start();
    }
    

    Ahora, al empezar la prueba, la variable timeLeft se establece en 30 y la propiedad Text del control timeLabel se establece en 30 segundos.A continuación, el método Start() del control Timer inicia la cuenta atrás. (La prueba no comprueba la respuesta todavía, esto viene después).

  7. Guarde el programa, ejecútelo y, a continuación, elija el botón Iniciar en el formulario.

    El temporizador iniciará la cuenta atrás.Cuando se agota el tiempo, la prueba finaliza y se muestra la respuesta.En la ilustración siguiente se muestra la prueba en curso.

    Prueba matemática en curso

    Prueba matemática en curso

Para continuar o revisar