Edit

Share via


Tutorial: Add reference variables and a timer control to your matching game WinForms app

In this series of four tutorials, you build a matching game, where the player matches pairs of hidden icons.

Your Matching Game program needs to track which Label controls the player chooses. After a player chooses the first label, the program should show the icon. After the second label is chosen, the program should display both icons for a brief time. Then it hides both icons.

Your program keeps track of which Label you choose first and second by using reference variables. A timer hides the icons and controls how long to show the icons

  • Add label references.
  • Add a timer.

Prerequisites

This tutorial builds on previous tutorials, Create a matching game application and Add icons to your matching game. Complete those tutorials first.

Add label references

In this section, you'll add two reference variables to your code. They keep track of, or refer to Label objects.

  1. Add label references to your form by using the following code in Form1.cs or Form1.vb.

    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;
    

If you're using C#, put the code after the opening curly brace and just after the class declaration (public partial class Form1 : Form). If you're using Visual Basic, put the code right after the class declaration (Public Class Form1).

These statements don't cause Label controls to appear on the form because there's no new keyword. When the program starts, both firstClicked and secondClicked are set to null for C# or Nothing for Visual Basic.

  1. Modify your Click event handler in Form1.cs or Form1.vb to use the new firstClicked reference variable. Remove the last statement in the label1_Click() event handler method (clickedLabel.ForeColor = Color.Black;) and replace it with the if statement as follows.

    /// <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. Save and run your program. Choose one of the label controls, and its icon appears. Choose the next label control, and notice that nothing happens.

    Screenshot shows the Matching Game showing one icon.

    Only the first icon that's chosen appears. The other icons are invisible.

The program is already keeping track of the first label that the player chose. The reference firstClicked isn't null in C# or Nothing in Visual Basic. When your if statement finds that firstClicked isn't equal to null or Nothing, it runs the statements.

Add a timer

The Matching Game app uses a Timer control. A timer waits, and then fires an event, referred to as a tick. A timer can start an action or repeat an action regularly.

In your program, the timer enables a player to choose two icons. If the icons don't match, it hides the two icons again after a short period of time.

  1. Select the Toolbox tab, in the Components category, double-click or drag the Timer component to your form. The timer icon, called timer1, appears in a space below the form.

    Screenshot shows the timer icon below the form.

  2. Select the Timer1 icon to select the timer. In the Properties window, select the Properties button to view properties.

  3. Set the Interval property to 750, which is 750 milliseconds.

    The Interval property tells the timer how long to wait between ticks, when it triggers its Tick event. Your program calls the Start() method to start the timer after the player chooses the second label.

  4. Choose the timer control icon and then press Enter, or double-click the timer. The IDE adds an empty Tick event handler to Form1.cs or Form1.vb. Replace the code with the following code.

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

The Tick event handler does three things:

  • It makes sure the timer isn't running by calling the Stop() method.
  • It uses two reference variables, firstClicked and secondClicked, to make the icons of the two labels that the player chose invisible again.
  • It resets the firstClicked and secondClicked reference variables to null in C# and Nothing in Visual Basic.
  1. Go to the code editor and add code to the top and bottom of the label1_Click() event handler method in Form1.cs or Form1.vb. This code will check if the timer is enabled, set the secondClicked reference variable, and start the timer. The label1_Click() event handler method now looks as follows:

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

  • The code at the top of the method checks whether the timer was started by checking the value of the Enabled property. If the player chooses the first and second Label controls and the timer starts, choosing a third label won't do anything.
  • The code at the bottom of the method sets the secondClicked reference variable to track the second Label control. Then, it sets that label icon color to black to make it visible. Then, it starts the timer in one-shot mode, so that it waits 750 milliseconds and then fires a single tick. The timer's Tick event handler hides the two icons and resets the firstClicked and secondClicked reference variables. The form is ready for the player to choose another pair of icons.

Note

If you copy and paste the label1_Click() code block rather than entering the code manually, be sure to replace the existing label1_Click() code. Otherwise, you'll end up with a duplicate code block.

  1. Save and run your program. Select a square and the icon becomes visible. Choose another square. The icon appears briefly and then both icons disappear.

Your program now keeps track of the first and second icons that you choose. It uses the timer to pause before making the icons disappear.

Next steps

Advance to the next tutorial to learn how to finish your Matching Game.