Site icon DataFlair

Create Flip Card Memory Game in JavaScript

Free Web development courses with real-time projects Start Now!!

Learn how to develop flip card memory game in JavaScript. It is a simple and fun game. In this game project, you need to match the pair of images by flipping them.

You all might have played the game because it is a super old and popular game. Now let’s see how we can create this.

Project Prerequisites

To implement this project you need to know the following :

Download JavaScript Memory Game Source Code

Please download the source code of flip card memory game project: Flip Card Memory Game Code

Steps to Build the JavaScript Project

1. Creating Html File – index.html

HTML provides the basic structure. So it is the very first step of this project. The Following code contains some basic HTML tags like div, h1, title, etc.

We’ve used some bootstrap buttons and classes to keep the designing part simple.

Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous" 0="">
    <title>DataFlair Memory game</title>
    
    <script src="static/script.js"></script>
    <style>
        .imgdiv{
            position: relative;
            display: inline-block;
            width:150px;
            height: 150px;
            line-height: 150px;
            font-size: 20px;
            padding: 10px;
            text-align: center;
            border: 2px solid black;
            cursor: pointer;
        }
        
        img{
            width:120px;
            height: 120px;
            padding: 10px;;
        }
 
        .hide{
            padding: 10px;
            visibility: hidden;
        }
 
        .match, .showimg{
            visibility: visible !important;
        }
 
    </style>
</head>
<body>
    <div class="container">
        <h1 class ="jumbotron">DataFlair Memory game</h1>
        <button class="btn btn-success" onclick="start()">Start game</button><br><br>
  <div id="score"></div>
 
        <div id="boardgame"></div>
    </div>
    
</body>
</html>

We have used very simple HTML tags and for styling we have used very basic CSS and some bootstrap classes.

CSS

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

The important classes in CSS are ‘.match’, ‘.hide’ and ‘.showimg’. Here .hide class is added to all the images initially so that all the images are hidden and it hides the images using a simple CSS property ‘visibility: hidden;’.
.showimg and .match just override the hidden property and change it to visible with !importnant so that both the classes always override the hidden property, irrespective of their priority.

2. Creating JavaScript File – script.js

It is a good programming practice to create separate folders for different files therefore, our JS files will be in a static folder, so make sure you make one in your project folder.

Code:

availableImages=['Images/bean.jpg','Images/doraemon.jpg','Images/minion.jpg','Images/mouse.jpg','Images/noddy.jpg','Images/popeye.jpg','Images/scooby.jpg','Images/shinchan.jpg','Images/bean.jpg','Images/doraemon.jpg','Images/minion.jpg','Images/mouse.jpg','Images/noddy.jpg','Images/popeye.jpg','Images/scooby.jpg','Images/shinchan.jpg']
 
function start(){
    let moves =0;
    while (maindiv.firstChild) {
        maindiv.removeChild(maindiv.lastChild);
    }
    const scorediv = document.getElementById("score");
    while (scorediv.firstChild) {
       scorediv.removeChild(scorediv.lastChild);
    }
 
    var row = document.createElement('div')
    ImagesCopy= JSON.parse(JSON.stringify( availableImages))
    for(let j=1;j<=16;j++){
        var div = document.createElement('div');
        div.setAttribute('class','imgdiv')
        var image = document.createElement('img')
        randomImg = ImagesCopy.splice(Math.floor(Math.random() * ImagesCopy.length),1);
        image.setAttribute('src',randomImg);
        image.setAttribute('class','hide')
        div.appendChild(image)
        row.appendChild(div);
        
        if(j%4==0){
            document.getElementById('boardgame').append(row)
            row = document.createElement('div')
        }
 
        div.addEventListener('click',function(event){
            moves++;
            let curr = event.currentTarget.children
            let currImg = curr[0]
           var currentlyshowing = document.getElementsByClassName('showimg');
            currentlyshowing = document.getElementsByClassName('showimg');
            let flag=0;
            if(currentlyshowing.length >= 1){
                for(let i=0;i<currentlyshowing.length;i++)
                {
                    if(currentlyshowing[i].src != currImg.src)
                    currentlyshowing[i].classList.remove('showimg');
                    else{
                        currentlyshowing[i].classList.add('match');
                        currImg.classList.add('match')
                        flag=1;
                    }
                }
            }
 
            if(document.getElementsByClassName('match').length==16){
                alert("You won !!! ")
                let button = document.createElement('button');
                button.setAttribute('class' , 'btn btn-warning');
                let node= document.createTextNode("You won!!! Moves "+moves);
                button.appendChild(node)
                document.getElementById('score').appendChild(button) 
            }
 
            if(flag==0)
            currImg.classList.add('showimg');
        })
    }
}

Let’s understand the code line by line

Flip Card Memory Game in JavaScript – Output

 

Summary

We have successfully developed Flip Card Memory Game in JavaScript. This is a fairly simple tutorial so it should be easy to follow. If you face any issues you can comment it down.

Exit mobile version