Memory the Game

Circular icon with two abstract cats

Memory the Game


In order to become better at JavaScript, I decided to create Memory the Game as a web application. The idea was create a colorful, interactive browser game in which the user can decide how many tiles he or she wants to use. It also had to work on as many browsers possible and no use of JavaScript libraries; only Vanilla JS.



The game is started by spawning a number of tiles with each number twice; meaning two tiles have the same number. The numbers are first produced by a for loop and put into an array:


window["bottomValue"].length = 0; //reset to 0 when user inputs a new number for the amount of tiles
document.getElementById("content-container").innerHTML = "";
var userNumber = parseInt(document.getElementById("userInputField").value); //the number the user inputs needs to be parsed into an integer
//create a loop which outputs 0,0,1,1,2,2 etc for the bottomValue array
for (var i = 0; i < userNumber; i++) {


Then it is time to create a tile and assign it a number from the bottomValue array:

var index = Math.floor(Math.random() * window["bottomValue"].length);
var bottomRandomValue = window["bottomValue"][index];
window["bottomValue"].splice(index, 1);</p>
<p style="text-align: left;">var divTileContainer = document.createElement("div");
divTileContainer.setAttribute("class", "tile-container");</p>
<p style="text-align: left;">window["contentContainer"].appendChild(divTileContainer);</p>
<p style="text-align: left;">var innerTileContainerFront = document.createElement("div");
innerTileContainerFront.class = "front";
innerTileContainerFront.setAttribute("class", "front");</p>
<p style="text-align: left;">var innerTileContainerBack = document.createElement("div");
innerTileContainerBack.class = "back";
innerTileContainerBack.setAttribute("class", "back");</p>
<p style="text-align: left;">divTileContainer.appendChild(innerTileContainerFront);
var NewTile = new Tile(bottomRandomValue, false, innerTileContainerBack, innerTileContainerFront, divTileContainer);
while(window["bottomValue"].length > 0);



To see if the user clicked a tile, I check for events and look for the Source Element and check it, if possible, against a different object. If their targets match, then I know the user clicked on two tiles. After that a check goes out to see whether their hiddenNumbers are a match.



When the tiles are a match it removes them from the game with a nice fade out:


To see more of the code, check out the Git repository!