Tutorial 3: Create a Matching Game


The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.

The latest version of this topic can be found at Tutorial 3: Create a Matching Game.

In this tutorial, you build a matching game, where the player must match pairs of hidden icons. You learn how to:

  • Store objects, such as icons, in a List object.

  • Use a foreach loop in Visual C# or a For Each loop in Visual Basic to iterate through items in a list.

  • Keep track of a form's state by using reference variables.

  • Build an event handler to respond to events that you can use with multiple objects.

  • Make a timer that counts down and then fires an event exactly once after being started.

When you finish this tutorial, your program will look like the following picture.

Game that you create in this tutorial
Game that you create in this tutorial

To download a completed version of the sample, see Complete Matching Game tutorial sample.

System_CAPS_ICON_note.jpg Note

In this tutorial, both Visual C# and Visual Basic are covered, so focus on information specific to the programming language that you're using.

If you get stuck or have programming questions, try posting your question on one of the MSDN forums. See Visual Basic Forum and Visual C# Forum. Also, there are great, free video learning resources available to you. To learn more about programming in Visual Basic, see Visual Basic Fundamentals: Development for Absolute Beginners. To learn more about programming in Visual C#, see C# Fundamentals: Development for Absolute Beginners.

Step 1: Create a Project and Add a Table to Your FormBegin by creating the project and adding a TableLayoutPanel control to keep the controls aligned properly.
Step 2: Add a Random Object and a List of IconsAdd a Random object and a List object, to create a list of icons.
Step 3: Assign a Random Icon to Each LabelAssign the icons randomly to the Label controls, so that each game is different.
Step 4: Add a Click Event Handler to Each LabelAdd a Click event handler that changes the color of the label that is clicked.
Step 5: Add Label ReferencesAdd reference variables to keep track of which labels are clicked.
Step 6: Add a TimerAdd a timer to the form to keep track of the time that has passed in the game.
Step 7: Keep Pairs VisibleKeep pairs of icons visible, if a matching pair is selected.
Step 8: Add a Method to Verify Whether the Player WonAdd a CheckForWinner() method to verify whether the player won.
Step 9: Try Other FeaturesTry other features, such as changing icons and colors, adding a grid, and adding sounds. Try making the board bigger and adjusting the timer.