Your Complete Guide to Creating a Memory (Matching) Game with C# and Windows Forms

Your Complete Guide to Creating a Memory (Matching) Game with C# and Windows Forms

Your Complete Guide to Creating a Memory (Matching) Game with C# and Windows Forms

Have you ever dreamed of developing your own game but felt it was too complicated? The good news is that starting in the world of game development is easier than you think. In this tutorial, we will take you on a fun, step-by-step journey to create a classic Memory (Matching) Game using C# and the Windows Forms environment in Visual Studio.

This project is an ideal starting point for beginners, as it covers fundamental programming concepts such as user interface (UI) design, event handling, randomization, and implementing game logic. By the end of this article, you will not only have a fully functional game but also a deeper understanding of the basics of desktop application development.

Prerequisites:

  • A copy of Visual Studio (the free Community edition is perfectly suitable).
  • Basic knowledge of the C# language.

Step 1: Preparing the Workspace and Setting Up the Project

1.1 Create a New Project

  1. Open Visual Studio. From the start window, choose Create a new project.
  2. In the template search box, type Windows Forms App (.NET Framework) and select it.
  3. Click Next.
  4. Give your project a unique name, such as MemoryGame, and then click Create.

1.2 Designing the Game Interface

Once the project is created, Visual Studio will open a blank form named Form1. Let's customize it:

  1. Change the Window Title: In the Properties window (if it's not visible, press F4), find the Text property and change its value to "Memory Game".
  2. Adjust Window Dimensions: Change the Size property to 550, 550 or manually drag the form's corners to get a symmetrical square.
  3. Add the Layout Panel: From the Toolbox, drag a TableLayoutPanel control and drop it onto the form. This control is essential for arranging the game's icons neatly in a grid.

1.3 Customizing the TableLayoutPanel

Now, let's make the layout panel fill the game window and prepare it to hold the icons:

  • Select the TableLayoutPanel you just added.
  • In the Properties window, set the following:
    • BackColor: Set it to a calm color like CornflowerBlue to distinguish the game's background.
    • Dock: Set it to Fill to make the panel automatically expand to fill the entire form.
    • CellBorderStyle: Change it to Inset to add visible borders between cells.
  • Click the small arrow in the upper-right corner of the TableLayoutPanel to open its task menu. Click Add Row twice, and then Add Column twice to create a 4x4 grid (16 cells).

Step 2: Adding and Preparing the Icons

Our game will use a set of symbols from the Webdings font, which is built into Windows. We will place each symbol inside a Label control in each cell of the grid.

  1. From the Toolbox, drag a Label control and drop it into the first cell of the TableLayoutPanel.
  2. Select the Label and, in the Properties window, modify the following properties:
    • BackColor: Make it the same as the panel's background color (CornflowerBlue) to hide the icon initially.
    • AutoSize: Set it to False.
    • Dock: Set it to Fill.
    • TextAlign: Set it to MiddleCenter to place the icon exactly in the middle of the cell.
    • Font: Choose Webdings font with a size of 48.
    • Text: Temporarily change the default text to the letter c to see what the icon looks like.
  3. Repeat this process 15 more times by copying the Label you just created and pasting it into each of the remaining cells.

Step 3: Programming Randomization and Icon Distribution

To make the game fun every time, the icons must be distributed randomly. We will do this through code.

1. Open the form's code editor by right-clicking on Form1.cs in the Solution Explorer and choosing View Code.

public partial class Form1 : Form
{
    // Used to generate random numbers
    Random random = new Random();

    // A list of characters representing the icons in the Webdings font
    // Each character is duplicated to create matching pairs
    List icons = new List() 
    { 
        "!", "!", "N", "N", ",", ",", "k", "k",
        "b", "b", "v", "v", "w", "w", "z", "z"
    };

    // ... remaining code
}

3. Create a method that randomly assigns each icon from the list to a Label. Add this method inside the Form1 class:

private void AssignIconsToSquares()
{
    // Iterate over each Label in the TableLayoutPanel
    foreach (Control control in tableLayoutPanel1.Controls)
    {
        Label iconLabel = control as Label;
        if (iconLabel != null)
        {
            int randomNumber = random.Next(icons.Count);
            iconLabel.Text = icons[randomNumber];
            // Change the font color to match the background, hiding the icon
            iconLabel.ForeColor = iconLabel.BackColor;
            icons.RemoveAt(randomNumber);
        }
    }
}

For more information on how lists work in C#, you can visit Microsoft's official documentation for the List<T> Class.

Step 4: Programming the Game Logic and User Interaction

4.1 Handling Player Clicks

We need two references to track the first and second Label clicked, as well as a Timer to hide the two icons if they don't match.

// Variables to track clicks
Label firstClicked = null;
Label secondClicked = null;

2. From the designer view, drag a Timer control from the Toolbox and drop it anywhere on the form. It will appear in the bottom tray. Select it and change its Interval property to 750 (which is 750 milliseconds).

3. Now, we need to create a single Click event handler for all the Label controls.

private void label_Click(object sender, EventArgs e)
{
    // If the timer is running, ignore any other clicks
    if (timer1.Enabled == true)
        return;

    Label clickedLabel = sender as Label;

    if (clickedLabel != null)
    {
        // If the icon is already visible, do nothing
        if (clickedLabel.ForeColor == Color.Black)
            return;

        // If this is the first click
        if (firstClicked == null)
        {
            firstClicked = clickedLabel;
            firstClicked.ForeColor = Color.Black; // Show the icon
            return;
        }

        // If this is the second click
        secondClicked = clickedLabel;
        secondClicked.ForeColor = Color.Black;

        // Check for a winner
        CheckForWinner();

        // If the two icons match
        if (firstClicked.Text == secondClicked.Text)
        {
            firstClicked = null;
            secondClicked = null;
        }
        else
        {
            // If they don't match, start the timer to hide them after a short delay
            timer1.Start();
        }
    }
}

4.2 Programming the Timer and Checking for a Winner

When the icons don't match, the timer will run. We need to program what happens when the timer's interval has passed.

private void timer1_Tick(object sender, EventArgs e)
{
    // Stop the timer
    timer1.Stop();

    // Hide both icons again
    firstClicked.ForeColor = firstClicked.BackColor;
    secondClicked.ForeColor = secondClicked.BackColor;

    // Reset the variables so the player can try again
    firstClicked = null;
    secondClicked = null;
}

Finally, add a method to check if the player has revealed all matching pairs:

private void CheckForWinner()
{
    // Iterate over every Label on the board
    foreach (Control control in tableLayoutPanel1.Controls)
    {
        Label iconLabel = control as Label;

        if (iconLabel != null)
        {
            // If we find any icon that is still hidden, the game isn't over
            if (iconLabel.ForeColor == iconLabel.BackColor)
                return;
        }
    }

    // If no hidden icons were found, the player has won
    MessageBox.Show("You've matched all the icons!", "Congratulations");
    Close(); // Close the game
}

Step 5: Running the Game

The programming is almost complete! One final step remains: calling the icon distribution method when the game starts.

public Form1()
{
    InitializeComponent();
    AssignIconsToSquares(); // Distribute the icons when the game starts
}

Now, press F5 or the green Start button in Visual Studio to compile and run your program. You will see your game window, ready to play! Click on the squares and try to find the matching pairs.

Conclusion and Suggested Improvements

Congratulations! You have successfully built a complete memory game from scratch using C# and Windows Forms. Through this project, you have learned how to design interfaces, handle events, use timers, and apply basic game logic—essential skills in any developer's toolkit.

For deeper learning, you can start a structured learning journey with the C# learning path on Microsoft Learn.

As an extra challenge, try improving your game by adding:

  • A click counter: A variable that counts the number of wrong attempts.
  • A game timer: Shows how long it took the player to finish the game.
  • Difficulty levels: A larger grid (like 6x6) with more icons.
  • Sound effects: Sounds for clicks, matches, and winning.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
-->