자습서: 매칭 게임 WinForms 앱에 참조 변수 및 타이머 컨트롤 추가

이 시리즈의 4개 자습서에서는 플레이어가 숨겨진 아이콘의 쌍을 찾는 매칭 게임을 빌드합니다.

매칭 게임 프로그램에서는 플레이어가 선택하는 레이블 컨트롤을 추적해야 합니다. 플레이어가 첫 번째 레이블을 선택한 후 프로그램이 아이콘을 표시해야 합니다. 두 번째 레이블을 선택한 후에는 프로그램이 두 아이콘을 모두 잠깐 표시합니다. 그런 다음 두 아이콘을 모두 숨깁니다.

프로그램은 “참조 변수”를 사용하여 첫 번째 및 두 번째로 선택하는 레이블을 계속 추적합니다. 타이머가 아이콘을 숨기거나 표시하는 기간을 제어합니다.

  • 레이블 참조를 추가합니다.
  • 타이머 추가를 참조하세요.

전제 조건

이 자습서는 이전 자습서 매칭 게임 애플리케이션 만들기매칭 게임에 아이콘 추가를 기반으로 작성되었습니다. 먼저 해당 자습서를 완료합니다.

레이블 참조 추가

이 섹션에서는 두 개의 “참조 변수”를 코드에 추가합니다. 이들은 레이블 개체를 추적(또는 참조)합니다.

  1. 다음 코드를 사용하여 폼에 레이블 참조를 추가합니다.

    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;
    

중요

이 페이지의 오른쪽 위에 있는 프로그래밍 언어 컨트롤을 사용하여 C# 코드 조각 또는 Visual Basic 코드 조각을 볼 수 있습니다.

Programming language control for Microsoft Learn

이러한 문은 new 키워드가 없기 때문에 레이블 컨트롤이 폼에 표시되지 않습니다. 프로그램이 시작되면 firstClickedsecondClickednull(C#의 경우) 또는 Nothing(Visual Basic의 경우)으로 설정됩니다.

  1. firstClicked 참조 변수를 사용하도록 Click 이벤트 처리기를 수정합니다. label1_Click() 이벤트 처리기 메서드의 마지막 문(clickedLabel.ForeColor = Color.Black;)을 제거하고 다음과 같이 if 문으로 바꿉니다.

    /// <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 label1_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;
            }
        }
    }
    

  1. 프로그램을 저장하고 실행합니다. 레이블 컨트롤 중 하나를 선택하면 아이콘이 나타납니다. 다음 레이블 컨트롤을 선택하면 아무것도 실행되지 않습니다.

    Screenshot shows the Matching Game showing one icon.

    선택한 첫 번째 아이콘만 나타납니다. 다른 아이콘은 표시되지 않습니다.

이 프로그램은 플레이어가 선택한 첫 번째 레이블을 이미 추적하고 있습니다. 참조 firstClickednull(C#) 또는 Nothing(Visual Basic)이 아닙니다. if 문에서 firstClickednull 또는 Nothing이 아닌 것으로 확인되면 문을 실행합니다.

타이머 추가

일치 게임 앱은 컨트롤을 Timer 사용합니다. 타이머가 대기하다가 “틱”이라고 하는 이벤트를 생성합니다. 타이머는 작업을 시작하거나 정기적으로 작업을 반복할 수 있습니다.

프로그램에서 타이머는 플레이어가 두 개의 아이콘을 선택할 수 있게 합니다. 아이콘이 일치하지 않으면 잠시 후 두 아이콘을 다시 숨깁니다.

  1. 도구 상자 탭을 선택하고 구성 요소 범주에서 타이머 구성 요소를 두 번 클릭하거나 폼으로 끕니다. 폼 아래 공간에 timer1이라는 타이머 아이콘이 나타납니다.

    Screenshot shows the timer icon below the form.

  2. Timer1 아이콘을 선택하여 타이머를 선택합니다. 속성 창에서 속성 단추를 선택하여 속성을 봅니다.

  3. 간격 속성을 750(750밀리초)로 설정합니다.

    간격 속성은 타이머의 “틱” 간 대기 시간, 즉 타이머가 Tick 이벤트를 트리거하는 시점을 나타냅니다. 플레이어가 두 번째 레이블을 선택하면 프로그램이 Start() 메서드를 호출하여 타이머를 시작합니다.

  4. 타이머 컨트롤 아이콘을 선택한 다음 Enter 키를 누르거나 타이머를 두 번 클릭합니다. IDE가 빈 틱 이벤트 처리기를 추가합니다. 코드를 다음 코드로 바꿉니다.

    /// <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;
    }
    

틱 이벤트 처리기는 다음 세 가지 작업을 수행합니다.

  • Stop() 메서드를 호출하여 타이머가 실행되지 않도록 합니다.
  • firstClickedsecondClicked라는 두 개의 참조 변수를 사용하여 플레이어가 선택한 두 레이블의 아이콘을 다시 숨깁니다.
  • firstClickedsecondClicked 참조 변수를 null(C#) 및 Nothing(Visual Basic)으로 다시 설정합니다.
  1. 코드 편집기로 이동하여 label1_Click() 이벤트 처리기 메서드의 위아래에 코드를 추가합니다. 이 코드는 타이머가 활성화되어 있는지 확인하고, secondClicked 참조 변수를 설정하며, 타이머를 시작합니다. 이제 label1_Click() 이벤트 처리기 메서드는 다음과 같이 표시됩니다.

    /// <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 label1_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();
        }
    }
    

  • 메서드 위쪽의 코드는 Enabled 속성 값을 검사하여 타이머가 시작되었는지 여부를 확인합니다. 플레이어가 첫 번째 및 두 번째 레이블 컨트롤을 선택하고 타이머가 시작되는 경우 세 번째 레이블을 선택해도 아무것도 수행되지 않습니다.
  • 메서드의 맨 아래에 있는 코드는 secondClicked 참조 변수를 두 번째 레이블 컨트롤을 추적하도록 설정합니다. 그런 다음 레이블 아이콘 색을 검은색으로 설정하여 표시되도록 합니다. 그런 다음 타이머를 일회 모드로 시작합니다. 그러면 타이머가 750밀리초 동안 기다렸다가 단일 틱을 발생시킵니다. 타이머의 틱 이벤트 처리기는 두 아이콘을 숨기고 firstClickedsecondClicked 참조 변수를 다시 설정합니다. 플레이어가 다른 아이콘 쌍을 선택할 수 있도록 폼이 준비됩니다.

참고

코드를 수동으로 입력하는 대신 label1_Click() 코드 블록을 복사하여 붙여 넣는 경우에는 기존 label1_Click() 코드를 대체해야 합니다. 이렇게 하지 않으면 중복된 코드 블록이 남게 됩니다.

  1. 프로그램을 저장하고 실행합니다. 정사각형을 선택하면 아이콘이 표시됩니다. 정사각형을 또 하나 선택합니다. 해당 아이콘이 잠깐 나타났다가 두 아이콘이 모두 사라집니다.

이제 프로그램이 선택한 첫 번째 아이콘과 두 번째 아이콘을 추적합니다. 프로그램은 아이콘을 숨기기 전에 타이머를 사용하여 일시 중지합니다.

다음 단계

매칭 게임을 완료하는 방법을 알아보려면 다음 자습서로 이동합니다.