Paso 6: Agregar un temporizador

A continuación, agregará un temporizador al juego de formar parejas.

Para agregar un temporizador

  1. Vaya al cuadro de herramientas del Diseñador de Windows Forms.Haga doble clic en Temporizador (en la categoría Componentes) y agregue un temporizador al formulario; su icono aparece en un cuadro deshabilitado bajo el formulario, como se muestra en la siguiente ilustración.

    Temporizador

    Temporizador

  2. Haga clic en el icono timer1 para seleccionar el temporizador.Establezca la propiedad Interval en 750, pero deje la propiedad Enabled establecida en False.La propiedad Interval indica al temporizador cuánto tiempo debe esperar entre los pasos, de modo que aquí se indica al temporizador que espere tres cuartos de segundo (750 milisegundos) antes de desencadenar su primer evento Tick.No deseará que el temporizador se inicie cuando se inicie el programa.En su lugar, utilizará el método Start() para iniciar el temporizador cuando el jugador haga clic en la segunda etiqueta.

  3. Haga doble clic en el icono del control Timer en el Diseñador de Windows Forms para agregar el controlador de eventos Tick, como se muestra en el siguiente código.

    ''' <summary>
    ''' This timer is started when the player clicks 
    ''' two icons that don't match,
    ''' so it counts three quarters of a second 
    ''' and then turns itself off and hides both icons
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub Timer1_Tick() Handles Timer1.Tick
    
        ' Stop the timer
        Timer1.Stop()
    
        ' Hide both icons
        firstClicked.ForeColor = firstClicked.BackColor
        secondClicked.ForeColor = secondClicked.BackColor
    
        ' Reset firstClicked and secondClicked 
        ' so the next time a label is
        ' clicked, the program knows it's the first click
        firstClicked = Nothing
        secondClicked = Nothing
    
    End Sub
    
    /// <summary>
    /// This timer is started when the player clicks 
    /// two icons that don't match,
    /// so it counts three quarters of a second 
    /// and then turns itself off and hides both icons
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void timer1_Tick(object sender, EventArgs e)
    {
        // Stop the timer
        timer1.Stop();
    
        // Hide both icons
        firstClicked.ForeColor = firstClicked.BackColor;
        secondClicked.ForeColor = secondClicked.BackColor;
    
        // Reset firstClicked and secondClicked 
        // so the next time a label is
        // clicked, the program knows it's the first click
        firstClicked = null;
        secondClicked = null;
    }
    

    El controlador de eventos Tick realiza tres acciones: primero, detiene el temporizador mediante una llamada al método Stop().A continuación, usa las dos variables de referencia, firstClicked y secondClicked, para recuperar las dos etiquetas en las que el jugador hizo clic y volver a ocultar sus iconos.Finalmente, restablece las variables de referencia firstClicked y secondClicked en null en Visual C# y Nothing en Visual Basic.Esto es importante, porque así es como se restablece el propio programa.Ahora no realiza el seguimiento de ningún control Label y vuelve a estar listo para el primer clic del jugador.

    [!NOTA]

    Un objeto Timer tiene un método Start() que inicia el temporizador y un método Stop() que lo detiene.Al establecer la propiedad Enabled del temporizador en True en la ventana Propiedades, inicia los pasos nada más comenzar el programa.Sin embargo, si se deja establecido en False, no inicia los pasos hasta que se llama a su método Start().

    [!NOTA]

    Normalmente, un temporizador desencadena una y otra vez su evento Tick, utilizando la propiedad Interval para determinar cuántos milisegundos debe esperar entre los pasos.Es posible que haya observado cómo se llama al método Stop() del temporizador dentro del evento Tick.Esto hace que el temporizador entre en modo de un disparo, de tal forma que, cuando se llama al método Start(), espera durante el intervalo correspondiente y desencadena un único evento Tick.

  4. Para ver el nuevo temporizador en acción, vaya al editor de código y agregue el siguiente código al principio y al final del método de control de eventos label_Click().(Se agrega una instrucción if al principio y tres instrucciones al final; el resto del método no cambia).

    ''' <summary>
    ''' Every label's Click event is handled by this event handler
    ''' </summary>
    ''' <param name="sender">The label that was clicked</param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub label_Click(ByVal sender As System.Object, 
                            ByVal e As System.EventArgs) Handles Label9.Click, 
        Label8.Click, Label7.Click, Label6.Click, Label5.Click, Label4.Click,  
        Label3.Click, Label2.Click, Label16.Click, Label15.Click, Label14.Click, 
        Label13.Click, Label12.Click, Label11.Click, Label10.Click, Label1.Click
    
        ' The timer is only on after two non-matching 
        ' icons have been shown to the player, 
        ' so ignore any clicks if the timer is running
        If Timer1.Enabled Then Exit Sub
    
        Dim clickedLabel = TryCast(sender, Label)
    
        If clickedLabel IsNot Nothing Then
            ' If the clicked label is black, the player clicked
            ' an icon that's already been revealed --
            ' ignore the click
            If clickedLabel.ForeColor = Color.Black Then Exit Sub
    
            ' If firstClicked is Nothing, this is the first icon 
            ' in the pair that the player clicked, 
            ' so set firstClicked to the label that the player 
            ' clicked, change its color to black, and return
            If firstClicked Is Nothing Then
                firstClicked = clickedLabel
                firstClicked.ForeColor = Color.Black
                Exit Sub
            End If
    
            ' If the player gets this far, the timer isn't 
            ' running and firstClicked isn't Nothing, 
            ' so this must be the second icon the player clicked
            ' Set its color to black
            secondClicked = clickedLabel
            secondClicked.ForeColor = Color.Black
    
            ' If the player gets this far, the player 
            ' clicked two different icons, so start the 
            ' timer (which will wait three quarters of 
            ' a second, and then hide the icons)
            Timer1.Start()
        End If
    
    End Sub
    
    /// <summary>
    /// Every label's Click event is handled by this event handler
    /// </summary>
    /// <param name="sender">The label that was clicked</param>
    /// <param name="e"></param>
    private void label_Click(object sender, EventArgs e)
    {
        // The timer is only on after two non-matching 
        // icons have been shown to the player, 
        // so ignore any clicks if the timer is running
        if (timer1.Enabled == true)
            return;
    
        Label clickedLabel = sender as Label;
    
        if (clickedLabel != null)
        {
            // If the clicked label is black, the player clicked
            // an icon that's already been revealed --
            // ignore the click
            if (clickedLabel.ForeColor == Color.Black)
                return;
    
            // If firstClicked is null, this is the first icon
            // in the pair that the player clicked, 
            // so set firstClicked to the label that the player 
            // clicked, change its color to black, and return
            if (firstClicked == null)
            {
                firstClicked = clickedLabel;
                firstClicked.ForeColor = Color.Black;
                return;
            }
    
            // If the player gets this far, the timer isn't
            // running and firstClicked isn't null,
            // so this must be the second icon the player clicked
            // Set its color to black
            secondClicked = clickedLabel;
            secondClicked.ForeColor = Color.Black;
    
            // If the player gets this far, the player 
            // clicked two different icons, so start the 
            // timer (which will wait three quarters of 
            // a second, and then hide the icons)
            timer1.Start();
        }
    }
    

    El código que se encuentra al principio del método comprueba si el temporizador se inició en la propiedad Enabled.Así, si el jugador hace clic en el primer y segundo control Label y se inicia el temporizador, no sucederá nada al hacer clic en un tercer control.

    El código al final del método establece la variable de referencia secondClicked para que realice el seguimiento del segundo control Label en el que hizo clic el jugador, y establece el color del icono de esa etiqueta en negro para que esté visible.A continuación, inicia el temporizador en modo de un disparo de forma que espere durante 750 milisegundos antes de desencadenar el evento Tick.Es entonces cuando el controlador de eventos Tick del temporizador oculta los dos iconos y restablece las variables de referencia firstClicked y secondClicked de modo que el formulario esté listo para que el jugador haga clic en otro icono.

  5. Guarde y ejecute el programa.Haga clic en un icono para que se vuelva visible.

  6. Haga clic en otro icono.Aparece brevemente y, a continuación, ambos iconos desaparecen.Repita el proceso varias veces.Ahora, el formulario realiza el seguimiento del primer y segundo icono en los que hizo clic, y usa el temporizador para realizar una pausa antes de hacer que los iconos desaparezcan.

Para continuar o revisar