Compartir a través de


Paso 8: Agregar un método para comprobar si el jugador ganó

Ha creado un juego divertido, pero necesita un elemento adicional.El juego debe finalizar cuando el jugador gana, de modo que necesita agregar un método CheckForWinner() para comprobar si el jugador ha ganado.

Para agregar un método que compruebe si el jugador ganó

  1. Agregue un método CheckForWinner() al formulario, tal como se muestra en el siguiente código.

    ''' <summary>
    ''' Check every icon to see if it is matched, by 
    ''' comparing its foreground color to its background color. 
    ''' If all of the icons are matched, the player wins
    ''' </summary>
    Private Sub CheckForWinner()
    
        ' Go through all of the labels in the TableLayoutPanel, 
        ' checking each one to see if its icon is matched
        For Each control In TableLayoutPanel1.Controls
            Dim iconLabel As Label = TryCast(control, Label)
            If iconLabel IsNot Nothing Then
                If (iconLabel.ForeColor = iconLabel.BackColor) Then
                    Return
                End If
            End If
        Next
    
        ' If the loop didn’t return, it didn't find 
        ' any unmatched icons
        ' That means the user won. Show a message and close the form
        MessageBox.Show("You matched all the icons!", "Congratulations")
        Close()
    
    End Sub
    
    /// <summary>
    /// Check every icon to see if it is matched, by 
    /// comparing its foreground color to its background color. 
    /// If all of the icons are matched, the player wins
    /// </summary>
    private void CheckForWinner()
    {
        // Go through all of the labels in the TableLayoutPanel, 
        // checking each one to see if its icon is matched
        foreach (Control control in tableLayoutPanel1.Controls)
        {
            Label iconLabel = control as Label;
    
            if (iconLabel != null) 
            {
                if (iconLabel.ForeColor == iconLabel.BackColor)
                    return;
            }
        }
    
        // If the loop didn’t return, it didn't find
        // any unmatched icons
        // That means the user won. Show a message and close the form
        MessageBox.Show("You matched all the icons!", "Congratulations");
        Close();
    }
    

    El método utiliza otro bucle foreach en Visual C# o For Each en Visual Basic para recorrer cada etiqueta de TableLayoutPanel.Usa el operador de igualdad (== en Visual C# y = en Visual Basic) para comprobar el color del icono de cada etiqueta y si coincide con el fondo.Si los colores coinciden, el icono sigue siendo invisible y el jugador no ha hallado las parejas de los iconos restantes.En ese caso, el programa utiliza una instrucción return para omitir el resto del método.Si el bucle pasa por todas las etiquetas sin ejecutar la instrucción return, indica que se han logrado hallar todas las parejas de iconos.El programa muestra un elemento MessageBox y, a continuación, llama al método Close() del formulario para finalizar el juego.

  2. A continuación, haga que el controlador del evento Click de la etiqueta llame al nuevo método CheckForWinner().Asegúrese de que el programa comprueba si existe un ganador después de mostrar el segundo icono en el que el jugador hace clic.Busque la línea donde estableció el color del segundo icono en el que se ha hecho clic y llame al método CheckForWinner() inmediatamente después, tal como se muestra en el siguiente código.

    ' 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
    
    ' Check to see if the player won
    CheckForWinner()
    
    ' If the player clicked two matching icons, keep them 
    ' black and reset firstClicked and secondClicked 
    ' so the player can click another icon
    If (firstClicked.Text = secondClicked.Text) Then
        firstClicked = Nothing
        secondClicked = Nothing
        Return
    End If
    
    // 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;
    
    // Check to see if the player won
    CheckForWinner();
    
    // If the player clicked two matching icons, keep them 
    // black and reset firstClicked and secondClicked 
    // so the player can click another icon
    if (firstClicked.Text == secondClicked.Text)
    {
        firstClicked = null;
        secondClicked = null;
        return;
    }
    
  3. Guarde y ejecute el programa.Reproduzca el juego y halle las coincidencias de todos los iconos.Al ganar, el programa muestra un elemento MessageBox (tal como se muestra en la siguiente imagen) y, a continuación, cierra el cuadro.

    Juego de formar parejas con MessageBox

    Juego de formar parejas con MessageBox

Para continuar o revisar