Compartir a través de


Paso 5: Agregar referencias a etiquetas

El programa necesita realizar un seguimiento de los controles Label en los que el usuario hace clic.Después de que se haga clic en la primera etiqueta, el programa muestra el correspondiente icono.Después de que se haga clic en la segunda etiqueta, el programa muestra ambos iconos durante unos instantes y, a continuación, los vuelve a ocultar.El programa realiza un seguimiento del control Label en el que se hace clic en primer lugar y del control en el que se hace clic en segundo lugar mediante variables de referencia.

Para agregar referencias de etiqueta

  1. Para agregar referencias de etiqueta a un formulario, use el siguiente código.

    Public Class Form1
    
        ' firstClicked points to the first Label control 
        ' that the player clicks, but it will be Nothing 
        ' if the player hasn't clicked a label yet
        Dim firstClicked As Label = Nothing
    
        ' secondClicked points to the second Label control 
        ' that the player clicks
        Dim secondClicked As Label = Nothing
    
    public partial class Form1 : Form
    {
        // firstClicked points to the first Label control 
        // that the player clicks, but it will be null 
        // if the player hasn't clicked a label yet
        Label firstClicked = null;
    
        // secondClicked points to the second Label control 
        // that the player clicks
        Label secondClicked = null;
    

    Nota

    Las variables de referencia parecen similares a las instrucciones usadas para agregar objetos (por ejemplo, objetos Timer, objetos List y objetos Random) a un formulario.Sin embargo, estas instrucciones no hacen aparecer dos controles Label adicionales en el formulario porque ninguna de las dos instrucciones incluye new.Sin new, no se crea ningún objeto.Por ello, firstClicked y secondClicked se denominan variables de referencia: simplemente realizan un seguimiento o hacen referencia a objetos Label.

    Nota

    Cuando una variable no realiza el seguimiento de ningún objeto, se establece en un valor especial: null en Visual C# y Nothing en Visual Basic.Por lo tanto, cuando se inicia el programa, el valor de firstClicked y el valor de secondClicked están establecidos en null o Nothing, lo que significa que las variables no realizan ningún tipo de seguimiento.

  2. Modifique el controlador de eventos Click para usar la nueva variable de referencia firstClicked.Quite la última instrucción del método de control de eventos label_Click() (clickedLabel.ForeColor = Color.Black;) y reemplácela por la instrucción if que figura a continuación.(Asegúrese de incluir el comentario así como todo lo que aparezca entre llaves.)

    ''' <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
    
        Dim clickedLabel As Label = 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
                Return
            End If
    
            ' 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
                Return
            End If
        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)
    {
        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;
            }
        }
    }
    
  3. Guarde y ejecute el programa.Haga clic en uno de los controles Label y aparecerá el correspondiente icono.

  4. Haga clic en el siguiente control Label y verá que no sucede nada.El programa ya está realizando un seguimiento de la primera etiqueta en la que se hizo clic, por lo que el valor de firstClicked no es null en Visual C# ni Nothing en Visual Basic.Cuando la instrucción if comprueba firstClicked para determinar si su valor es null o Nothing, concluye que no tiene ese valor y no ejecuta las instrucciones de la instrucción if.Por lo tanto, solo el primer icono en el que se hizo clic se vuelve negro y los demás iconos se vuelven invisibles, tal y como se muestra en la siguiente imagen.

    Juego de formar parejas con un icono visible

    Juego de formar parejas con un icono visible

Para continuar o revisar