Card Flipping Memory Game made with Javascript

A memory game made with Javascript

Our example for beginner frontend web developers in this article is a memory game. You can watch the coding video above. You can also access the codes here.

The game consists of squares on a 4x4 grid. There are certain symbols on the back side of these squares and these squares do not close back when two identical symbols are opened one after the other by clicking on the square. After all couples matched, the game ends.

As usual, we create an index.html file to start our example. We get the Open Sans font family through Google Fonts and add it to our index.html file. After creating the game.css and game.js files and adding them into HTML, we finally close our HTML file with a div with game-wrapper id.

As for our CSS file, we are giving 300 pixels width for #game-wrapper. This will be the width of our game and the squares inside the grid will be sized according to this width.

For the .grid style, we provide the display:flex and flex-flow:row wrap styles to ensure that the frames we add are evenly aligned.

For .cell, we give styles display:flexand according styles for its content aligned vertically and horizontally. We need another element that will fit behind the square, and we create it with .cell::after. We also give rotation on the Y axis to the .hide style by rotateY to be used for the closed form of the squares.

We finish our CSS file by creating the styles of the panel that will be used for information display.

Now it’s our javascript codes’ turn. We create a variable named game and assign a function that will execute right after its creation. In this function, we define the necessary variables. In the symbols variable, we assign symbols to be used within the squares. We do this in the simplest way by dividing a string of letters and numbers and creating an array.

We need to keep the previous selected card in the game for comparison. We use the previousCellIndex variable for this.

We place the grid representing our grid, the cell representing the squares and the information panel elements in the DOM tree. We increase the cycle we use to create the squares by two, because we want each symbol to be a pair. Also, in this loop, we have to make a shuffling so that the symbols are not placed next to each other, we replace each square with a random previous square and iterate the loop.

We give the cellClick function to the click event of the squares. In this function, we first check the canPlay flag variable and that the clicked square is inverted.

If it is the first square clicked for a pair, we assign its index to previousCellIndex and finish the function. If it is the second square, we check if there is a match and the game is completed. After these checks, we set the previousCellIndex variable to null, print the required information on the screen and finish the function.

Software Developer, Physics Grad.