Memory Game In Javascript With Source Code
The Memory Game In Javascript was developed using JavaScript, CSS and HTML, This Javascript Project With Source Code will put your short-term memory to the test. While playing this game, a sequence of images will emerge in a box-shaped region. To win the battle, the player must locate two identical images and click on them.
A Memory Game In Javascript Code is a straightforward HTML, CSS, and JavaScript project. In terms of the game’s mechanics, the user must click the same two photos in order to get points.
How to play Memory Game In Javascript?
- Click on the cards or press the keyboard keys to reconstruct the pairs of images by turning them 2 by 2 and discover the image hidden underneath!
- If the cards turned face up are the same (a pair), you win and get points for it!
- Otherwise, the cards are automatically turned face down and you will lose your point!
This Javascript Project With Source Code also includes a downloadable javascript source code for free, just find the downloadable source code below and click to start downloading.
I have here a suggested list of Best JavaScript Projects with Source Code Free to download and I’m sure this can help you to improve your skills in JavaScript programming and web development as a whole.
To start executing a Memory Game In Javascript With Source Code, makes sure that you have any platform in creating a JavaScript, CSS, bootstrap, and HTML installed in your computer, in my case I will use Sublime Text.
Memory Game In Javascript With Source Code : Steps on how to create the project
Time needed: 5 minutes
These are the steps on how to create Memory Game In Javascript With Source Code
- Step 1: Create a folder.
First, create a folder and named it.
- Step 2: Open the folder in “Sublime Text”.
Second ,after creating a folder, open it in “sublime text“.
- Step 3: Create a html file.
Third, create a “html” file and save it as “index.html“
The code given below is for the html module
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="Description" content="Enter your description here"/> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.2/css/all.css" integrity="sha384-vSIIfh2YWi9wW0r9iZe7RJPrKwp6bG+s9QZMoITbCckVJqGCCRhc+ccxNcdpHuYu" crossorigin="anonymous"> <title>Memory Minder</title> </head> <body> <div class="text-center text-uppercase mt-5"> <h1>Memory Game</h1> <p><strong>Test your Memory:</strong>Match the pairs as quickly as possible, in as few moves as possible</p> </div> <div id="gameboard" class="container"> <div class="row"> <div class="col-3 gametile" id="tile1"></div> <div class="col-3 gametile" id="tile2"></div> <div class="col-3 gametile" id="tile3"></div> <div class="col-3 gametile" id="tile4"></div> <div class="col-3 gametile" id="tile5"></div> <div class="col-3 gametile" id="tile6"></div> <div class="col-3 gametile" id="tile7"></div> <div class="col-3 gametile" id="tile8"></div> <div class="col-3 gametile" id="tile9"></div> <div class="col-3 gametile" id="tile10"></div> <div class="col-3 gametile" id="tile11"></div> <div class="col-3 gametile" id="tile12"></div> </div> <div class="row"> <div class="col-4 label"><h3>Timer</h3></div> <div class="col-4 label"><h3>Moves</h3></div> <div class="col-4 label"><h3>Score</h3></div> <div class="col-4" id="timer"><div></div></div> <div class="col-4" id="clicks"><div></div></div> <div class="col-4" id="score"><div></div></div> </div> <div class="row"> <div class="col-6 mt-4"> <button id="startGame" class="btn btn-success">Start Game</button> </div> <div class="col-6 mt-4"> <button id="endGame" class="btn btn-danger"> End Game </button> </div> <div class="col-2 mx-auto"> <button id="reset" class="btn btn-warning"><a style="text-decoration: none;" href="index.html">Reset</a></button> </div> </div> </div> </body> </html>
In this module which is the html module of the simple project.
The code given below is for the css module
<style> @import url('https://fonts.googleapis.com/css2?family=Fascinate&family=Finger+Paint&display=swap'); body{ font-family: 'jokerman', cursive; background-color: skyblue; } h1{ color: white; } #gameboard{ margin: 5vh auto; height: 60vh; width: 60vw; } .gametile{ height: 15vh; width: 15vw; line-height: 15vh; background-color: #44445a; color: white; text-align: center; font-size: 0em; border: 2px solid #55555a } #timer div, #score div, #clicks div{ margin: 10px auto 25px auto; height: 80px; line-height: 80px; text-align: center; border: 3px solid #555; background-color: #f5f5f5; border-radius: 10px; font-weight: 600; font-size: 2em; text-transform: capitalize; } .label{ margin-top: 20px; text-transform: uppercase; color: white; text-align: center; } .btn{ text-align: center; width: 100%; padding: 2%; margin-bottom: 10%; font-weight: 600; font-size: 2.5em; } .displayTile{ font-size: 3em; } .hideTile{ font-size: 0em; background-color: #44445a; } .correctAnswer{ background-color: green; } .falseAnswer{ background-color: red; } </style>
In this module which is the css module of the simple project.
The code given below is for the javascript module
<script> //on page load -> generate game board; window.onload = function(){ console.log("Page Loaded") setRandomTileOrder(12); setTiles(); } //global variable let i = 0; let clicks; let timeScore; /*start button initiates game and starts counter initiates game start on button press*/ let startButton = document.getElementById("startGame") startButton.addEventListener("click", startGame); function startGame() { tiles.forEach(tile => tile.addEventListener("click", displayTile)); resetTiles(); startButton.disabled = true; console.log(randomOrderArray); startTimer(); } //end button stops the game document.getElementById('endGame').addEventListener("click", endGame); function endGame() { function endTimer() { timeScore = document.getElementById("timer").innerText; console.log(timeScore); clearInterval(timer); } randomOrderArray= []; startButton.innerText = "New Game"; startButton.disabled = false; endTimer(); calculateScore(); } /* createRandom number function creates random number which will later be assigned an icon creates an array of 12 random numbers*/ let randomOrderArray = []; function setRandomTileOrder(numberOfTiles) { while (randomOrderArray.length < numberOfTiles) { let randomNum = Math.random(); randomNum = randomNum * (numberOfTiles -1); randomNum = Math.round(randomNum) + 1; if (randomOrderArray.includes(randomNum)) { continue; } else { randomOrderArray.push(randomNum); } } } //Set tiles variable for use throughout code const tiles = document.querySelectorAll(".gametile"); function setTiles(){ for(tile of tiles){ tile.innerHTML = randomOrderArray[i]; i++; //replace numerical values with icon pairs if (tile.innerText < 3) { tile.innerHTML = rocket; tile.setAttribute("icon", "rocket") } else if (tile.innerHTML < 5) { tile.innerHTML = bacteria; tile.setAttribute("icon", "bacteria") } else if (tile.innerHTML < 7) { tile.innerHTML = cocktail; tile.setAttribute("icon", "cocktail") } else if (tile.innerHTML < 9) { tile.innerHTML = football; tile.setAttribute("icon", "football") } else if (tile.innerHTML < 11) { tile.innerHTML = pizza; tile.setAttribute("icon", "pizza") } else if (tile.innerHTML < 13) { tile.innerHTML = kiwi; tile.setAttribute("icon", "kiwi") } else { console.log("Error: too many tiles"); } } } //Timer Function -> starts timer when game is started end when game is complete or game is cancelled. let count; function startTimer() { clearInterval(timer); //clears timer before timer starts. This fixes issue if timer is triggered again, when already running. count = 0, timer = setInterval(function () { count = count++; document.getElementById("timer").firstChild.innerText = count++; //end timer when timer reaches -1, This displays 0. if (count === 60) { clearInterval(timer); document.getElementById("timer").firstChild.innerText = "Game Over"; } }, 1000); } /* icon assign function -> replaces random numbers with icon pairs when icon assigned, tile is also assigned an attribute icon variables */ let football = `<i class="fas fa-football-ball"></i>`; let mask = `<i class="fas fa-ufo"></i>`; let pizza = `<i class="fas fa-pizza-slice"></i>`; let lightning = `<i class="far fa-bolt"></i>`; let bulb = `<i class="fal fa-lightbulb"></i>`; let rocket = `<i class="fas fa-rocket"></i>`; let bacteria = `<i class="fas fa-bacterium"></i>`; let kiwi = `<i class="fas fa-kiwi-bird"></i>`; let cocktail = `<i class="fas fa-cocktail"></i>`; const selectedTile = '' let tileIcon; let tileIcons =[]; let tileIds =[]; //displayTile -> function which listens for click event and displays tile value on click tiles.forEach(tile => tile.addEventListener("click", displayTile)); let n = 0; function displayTile(e) { //reveal tile by changing bg color and changing font-size from 0 to 3em; this.classList.remove("hideTile"); this.classList.add("displayTile"); // logs the value of the tile's icon and Id tileIcon = e.target.getAttribute("icon"); tileIcons.push(tileIcon); let tileId = e.target.getAttribute("id"); tileIds.push(tileId); // this counts number of clicks countMoves() if(tileIcons.length % 2 == 0){ checkMatch(tileIcons, tileIds,n) n = n+2; } }; function checkMatch(tileIcons, tileIds,n){ console.log(n); console.log(n+1); if(tileIcons[n] !== tileIcons[n+1]){ console.log("no match"); setTimeout(function(){ document.getElementById(tileIds[n+1]).classList.remove("displayTile"); document.getElementById(tileIds[n]).classList.remove("displayTile"); }, 1000); } else { console.log("match"); console.log(n); document.getElementById(tileIds[n]).style.backgroundColor = "green"; document.getElementById(tileIds[n+1]).style.backgroundColor = "green"; document.getElementById(tileIds[n]).setAttribute("guess","correct") document.getElementById(tileIds[n+1]).setAttribute("guess","correct") document.getElementById(tileIds[n]).removeEventListener("click", displayTile); document.getElementById(tileIds[n+1]).removeEventListener("click", displayTile); } } //countClicks -> calculates number of user clicks -> needed to calculate score function countMoves(){ clicks = n; document.getElementById("clicks").firstChild.innerHTML = clicks; } //ClearTiles -> Clear tiles when new game is started; function clearTiles(){ for(let n = 0; n < tiles.length; n++){ tiles[n].style.fontSize = "0em"; tiles[n].style.backgroundColor = "#44445a"; } } /*match tiles -> when one tile is clicked and displayed, check if next tile clicked has the same attribute value if match icons remain displayed and correctly guessed tiles become disabled. */ //countCorrectAnswers -> count the number of tiles with value correct. each time a pair of tiles are matched, add 1 to the coundCorrectAnswers value; //completeGAme -> When the number of correct answers == the number of cells the game can end. //calculateScore -> adds number of clicks and elapsed time to calculate score & displays score upon game completion. function calculateScore(){ timeScore = parseInt(timeScore); let calculatedScore = (timeScore + clicks); console.log(calculatedScore); document.querySelector("#score").firstChild.innerHTML = calculatedScore; } //refresh/reset -> click button, invokes endGame() the reset tiles values, and return their default styling. //additional levels of difficulty //1. generateRandomColor -> generates a random background color, to make matching harder as game progresses let newRGB; function generateRGBVal() { function generateRandomColor() { let r = Math.random(); r = r * 255; r = Math.round(r); return r; } let rgbValue = []; for (let i = 0; i <= 2; i++) { let singleVal = generateRandomColor(); rgbValue.push(singleVal); } newRGB = `rgb(${rgbValue[0]},${rgbValue[1]},${rgbValue[2]})`; return newRGB; } //2. addAdditional tiles -> 12, 16, 20, 24 //3. Reduce time -> decrease amount of time available to complete the game. //4. change icons to a math problem to be matched to the correct answer; //additional iterations/Future development // publish leaderboard; //use api to generate random icon or picture function resetTiles(){ for(tile of tiles){ tile.style.backgroundColor ="#44445a"; tile.removeAttribute("state"); tile.classList.remove("hideTile"); tile.classList.remove("displayTile"); } } </script>
In this module which is the javascript module of the simple project.
Project Output
ABOUT PROJECT | PROJECT DETAILS |
---|---|
Project Name : | Memory Game In Javascript |
Project Platform : | JavaScript |
Programming Language Used: | php,javascript,html,css |
Developer Name : | itsourcecode.com |
IDE Tool (Recommended): | Sublime |
Project Type : | Web Application |
Database: | None |
Upload Date: | July 19, 2021 |
Downloadable Source Code
Summary
This JavaScript Project With Source Code is simply in HTML, CSS, and JavaScript. To start creating this Simple Javascript Project With Source Code, make sure that you have basic knowledge in HTML, CSS and Javascript.
This Javascript Game Project also includes a downloadable Javascript Game Project With Source Code for free.
Related Articles
- Todo List In JavaScript With Source Code
- Currency Converter Project in JavaScript with Source Code
- Calculator In JavaScript Source Code
- [SOLVED] How To Make A Live Chat In JavaScript With Source Code
Inquiries
If you have any questions or suggestions about Memory Game In Javascript With Source Code , please feel free to leave a comment below.