다음을 통해 공유


3단계: 각 레이블에 임의 아이콘 할당

항상 같은 위치에 같은 아이콘을 숨기는 게임은 재미가 없습니다.폼에서 Label 컨트롤에 임의로 아이콘을 할당해야 합니다.이렇게 하려면 AssignIconsToSquares() 메서드를 추가합니다.

각 레이블에 임의의 아이콘을 할당하려면

  1. 다음 코드를 추가하기 전에 메서드가 동작하는 방식을 고려해야 합니다.Visual C#에는 foreach, Visual Basic에는 For Each라는 새 키워드가 사용됩니다.코드 줄 중 하나가 주석 처리되어 있으며 이에 대해서는 이 절차의 끝 부분에서 설명합니다.

    ''' <summary>
    ''' Assign each icon from the list of icons to a random square
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub AssignIconsToSquares()
    
        ' The TableLayoutPanel has 16 labels,
        ' and the icon list has 16 icons,
        ' so an icon is pulled at random from the list
        ' and added to each label
        For Each control In TableLayoutPanel1.Controls
            Dim iconLabel = TryCast(control, Label)
            If iconLabel IsNot Nothing Then
                Dim randomNumber = random.Next(icons.Count)
                iconLabel.Text = icons(randomNumber)
                ' iconLabel.ForeColor = iconLabel.BackColor
                icons.RemoveAt(randomNumber)
            End If
        Next
    
    End Sub
    
    /// <summary>
    /// Assign each icon from the list of icons to a random square
    /// </summary>
    private void AssignIconsToSquares()
    {
        // The TableLayoutPanel has 16 labels,
        // and the icon list has 16 icons,
        // so an icon is pulled at random from the list
        // and added to each label
        foreach (Control control in tableLayoutPanel1.Controls)
        {
            Label iconLabel = control as Label;
            if (iconLabel != null)
            {
                int randomNumber = random.Next(icons.Count);
                iconLabel.Text = icons[randomNumber];
                // iconLabel.ForeColor = iconLabel.BackColor;
                icons.RemoveAt(randomNumber);
            }
        }
    } 
    
  2. 이전 단계와 같이 AssignIconsToSquares() 메서드를 추가합니다.이 메서드를 2단계: 임의의 개체 및 아이콘 목록 추가에서 추가한 코드 바로 다음에 둡니다.

    AssignIconsToSquares() 메서드에 foreach 루프(Visual C#의 경우)와 For Each(Visual Basic의 경우)라는 새로운 키워드가 있습니다.같은 동작을 되풀이하여 수행하려는 경우 언제든지 For Each 루프를 사용합니다.이 경우에는 다음 코드에서 설명하는 것처럼 TableLayoutPanel의 모든 레이블에 대해 같은 문을 실행하려고 합니다.명명 된 변수 첫 줄을 만듭니다 control 는 각 컨트롤 하는 동안 한 번 문을 루프에서 실행 권한이 있는지 저장 합니다.

    For Each control In TableLayoutPanel1.Controls
        ' The statements you want to execute 
        ' for each label go here
        ' The statements use iconLabel to access 
        ' each label's properties and methods
    Next
    
    foreach (Control control in tableLayoutPanel1.Controls)
    {
        // The statements you want to execute 
        // for each label go here
        // The statements use iconLabel to access 
        // each label's properties and methods
    }
    

    [!참고]

    iconLabel 및 control과 같이 의미를 알기 쉬운 이름이 사용되었습니다.이러한 이름은 임의의 이름으로 바꿀 수 있습니다. 그리고 각 문은 루프 내에서 이름 변경으로 똑같이 작동 합니다.

    AssignIconsToSquares() 메서드는 TableLayoutPanel의 각 Label 컨트롤을 순서대로 거치며 각 컨트롤에 대해 동일한 문을 실행합니다.이러한 문은 2단계: 임의의 개체 및 아이콘 목록 추가에서 추가한 목록에서 임의의 아이콘을 끌어 옵니다.이 때문에 각 아이콘을 두 개씩 목록에 포함했습니다. 따라서 임의의 Label 컨트롤에 아이콘 쌍이 할당됩니다.

    더 가깝게 볼 때 내를 실행 하는 코드는 foreach 또는 For Each 루프.이 코드는 여기서 다시 만들어집니다.

    Dim iconLabel = TryCast(control, Label)
    If iconLabel IsNot Nothing Then
        Dim randomNumber = random.Next(icons.Count)
        iconLabel.Text = icons(randomNumber)
        ' iconLabel.ForeColor = iconLabel.BackColor
        icons.RemoveAt(randomNumber)
    End If
    
    Label iconLabel = control as Label;
    if (iconLabel != null)
    {
        int randomNumber = random.Next(icons.Count);
        iconLabel.Text = icons[randomNumber];
        // iconLabel.ForeColor = iconLabel.BackColor;
        icons.RemoveAt(randomNumber);
    }
    

    변환의 첫 번째 줄은 control 변수를 한 Label 라는 iconLabel.후 줄은 if 변환이 있는지 확인 하는 문을 작동 합니다.변환에서 작동 하지 않으면 문이 if 문을 실행 합니다.첫 번째 줄에는 if 문은 라는 변수를 만듭니다 randomNumber 는 아이콘 목록에서 항목 중 하나에 해당 하는 임의의 숫자를 포함 합니다.사용이 작업을 수행 하는 Next 메서드는 Random 이전에 만든 개체.Next 메서드는 임의의 숫자를 반환 합니다.또한이 줄을 사용 하 여는 Count 속성에는 icons 목록의 임의의 숫자를 선택할 수 있는 범위를 결정 합니다.다음 줄의 아이콘 중 하나를 목록 항목에 할당을 Text 레이블 속성.주석 줄은이 항목의 뒷부분에 설명 되어 있습니다.마지막 줄에서 마지막으로 if 문의 폼에 추가 된 아이콘 목록에서 제거 합니다.

    기억, 일부 코드의 용도 대 한 확실 하지 않은 경우 코드 요소 위로 마우스 포인터를 놓으면 및 결과 도구 설명을 검토 합니다.

  3. 프로그램이 시작되면 바로 AssignIconsToSquares() 메서드를 호출해야 합니다.Visual C# 코드를 작성하는 경우에는 Form1 생성자에서 InitializeComponent() 메서드 호출 바로 아래에 문을 추가하십시오. 그러면 폼이 표시되기 전에 폼을 설정하는 새로운 메서드가 호출됩니다.

    public Form1()
    {
        InitializeComponent();
    
        AssignIconsToSquares();
    }
    

    Visual Basic의 경우 먼저 생성자를 추가한 다음, 이 생성자에 메서드 호출을 추가합니다.방금 만든 AssignIconsToSquares() 메서드 앞에 Public Sub New()라는 코드를 입력하여 시작하십시오.Enter 키를 눌러 다음 줄로 이동하면 IntelliSense에서 다음 코드를 표시하여 생성자를 완료합니다.

    Public Sub New()
        ' This call is required by Windows Form Designer
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call
    End Sub
    

    생성자가 다음 코드와 같이 되도록 AssignIconsToSquares() 메서드 호출을 추가합니다.

    Public Sub New()
        ' This call is required by Windows Form Designer
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call
        AssignIconsToSquares()
    End Sub
    
  4. 프로그램을 저장하고 실행합니다.각 레이블에 임의의 아이콘이 할당된 폼이 나타납니다.

  5. 프로그램을 닫고 다시 실행합니다.이제 다음 그림과 같이 각 레이블에 다른 아이콘이 할당됩니다.

    임의의 아이콘을 표시하는 일치 게임

    임의의 아이콘을 표시하는 일치 게임

  6. 이제 프로그램을 중지하고 For Each 루프 내의 코드 줄에서 주석 처리를 제거합니다.

    iconLabel.ForeColor = iconLabel.BackColor
    
    iconLabel.ForeColor = iconLabel.BackColor;
    
  7. 모두 저장 도구 모음 단추를 클릭하여 프로그램을 저장하고 실행합니다.아이콘이 사라진 것처럼 보이고 파란색 배경만 나타납니다.그러나 아이콘이 임의로 할당되어 그대로 남아 있습니다.아이콘이 배경과 같은 색이므로 보이지 않는 것입니다.

계속하거나 검토하려면