Skip to content

Matching Game

David Silvan edited this page Feb 22, 2017 · 9 revisions

Overview

In this lesson we will learn how to make a matching game in Python using arrays of numbers and through the parsing of user input. For our game, we will create an array of 10 numbers, which are made up of 5 pairs of identical numbers (for example: 0,0,1,1,2,2,3,3,4,4). We will randomly put the numbers into the array and then have the user guess which indices of the array have the same value (for example, if the user enters 3 and 7, then we check to see if the numbers stored at the 3-index and 7-index of the array are of the same value). We will display the values at the indices guessed but will reset the values to be hidden if the numbers/indices entered are not of the same value.

Let's Get Started:

First, we need to create a main method. This method will be the controller for the game and will be called when the program is started. For our game implementation, we will use 2 different arrays: 1 array will hold the values of the pairs of the numbers, while the other will initially hold 'x' as a placeholder for each value (this 2nd array will be the one displayed to the user). We want there to be 10 total "cards" to match (5 pairs of matching cards) so our arrays will be of size 10. We first create a boolean variable for checking if the game has been won (we will use this later to determine if the user has matched all of the cards). We will call this boolean variable "won" and set it initially to False. Now we create our "hidden array" that only holds 'x' values. To do this we use hiddenarray = ['x'] * 10

(IMAGE1)

To be able to create our other array (the one which holds the pairs of values) efficiently and to help organize the code, we will create a separate method and call it "initarray." This method should fill an array of size 10 with 5 different pairs of matching values, so that the values are randomly distributed throughout the array. The method then returns this array to the caller. In this initarray method, we will create an array that contains 5 pairs of matching values and call it list: list = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4]. We will also create another array that is the one that gets filled with the values and is eventually returned; this array will be called "arr" : arr = [0] * 10

(IMAGE2)

Now what we want to do is randomly select a value from the "list" array and put it into the "arr" array, and then delete the value from the "list" array, and then repeat the process until the "list" array is empty and the "arr" array is full. First we will need a variable to hold the index of the "arr" array (i = 0). We also need to use a function to generate random integers. We can use the randint function that the random class provides. To use this function, at the beginning of our program we must import it: from random import randint

(IMAGE3)

Clone this wiki locally