Introduction
All of us want to improve mind memory and concentration. Certainly, we know "match pairs memory game." It is an amazing game that increase memory power. It would be great if you try building this game by yourself, using your favourite images and controlling the scalability. What do you think about this game from programility perspective? Let's begin.
The game will look like 4x4 blocks, with 8 different pairs of images:
The below chart describes the general flow of the game. The game starts by showing 8 different pairs images (16 images randomly spread over 16 block) for a set number of seconds. During these seconds, the user tries to concentrate and focus on each image. Afterwards, all images will be flipped and the user tries to match images depending on his memory. For each matching pair, the user's score will be increased by 5, elsewise the score will be decreased by 5. Therefore the score could be a negative value. Once a user matches all images, the game will be finished.
The user can refresh the game at anytime using the refresh icon, then all images will be spread again randomly over the blocks.
Before any code explanation, please note that you can find the source code and all related files in the attachment part corresponding to the table below:
Now let's get started.
Step 1
Create a GameViewModel that will contain all needed properties and functions.
1.1 You notice that the game is 4x4 blocks and each block line is a row. So, create 4 observable arrays named as imgsRows, suffixed by 1,2,3,4 numbers respectively and all of these 4 previous arrays will be pushed to a main observable array named imgsrows.
- GameViewModel = function() {
- var self = this;
- self.imgsRows = ko.observableArray();
- self.imgsRow1 = ko.observableArray();
- self.imgsRow2 = ko.observableArray();
- self.imgsRow3 = ko.observableArray();
- self.imgsRow4 = ko.observableArray();
- }
1.2 As the game is 4x4, 16 images will be used with suffix for each image's name. Suffixes are 1,2,3,4,5,6,7, 8, and assume each image has a name "Img" + suffix +".png" .
In this step, you need to distinguish between two things image suffIx and image index, suffix is from [1-8] combined with image name, however, index is related to image block in the 4x4 blocks and could be a value from [0-15], for example, image could has a name "Img8.png" with index = 15.
1.3 Generate a random integer from 0-15 then using it as an index for suffix array to get the value of suffix which will be a part of an image name. After that, remove the suffix from the suffix array.
- self.getRandomImages = function() {
- var imgSuffixArray = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8];
- var randomInt = Math.floor(Math.random() * imgSuffixArray.length);
- var imgUrl = "url(Images/Images100x100/Img" + imgSuffixArray[randomInt] + ".png)";
- var imgName = "Img" + imgSuffixArray[randomInt] + ".png";
- imgSuffixArray.splice(randomInt, 1);
The above snippet code should be repeated 16 times, so use a For-Loop and assume that i variable is an index for an image.
- for (var i = 0; i < 16; i++)
As mentioned above, four observable arrays were created to carry the properties of the 16 images. Let's agree that the properties for images with indices [0-3] will be pushed into imgsRow1 array, [4-7] will be pushed into imgsRow2 array, [8-11] will be pushed into imgsRow3 array and finally, images with indices [12-15] will be pushed into imgsRow4 array.
- var imgProps ={
- 'imgName': ko.observable(imgName),
- 'imgIndex': ko.observable(i),
- 'imgUrl': ko.observable(imgUrl),
- 'imgPointerEvent': ko.observable('none'),
- 'currentShownImgUrl': ko.observable(imgUrl)
- }
-
- if (i < 4) {
- koGame.imgsRow1.push(imgProps);
- } else if (i < 8) {
- koGame.imgsRow2.push(imgProps);
- } else if (i < 12) {
- koGame.imgsRow3.push(imgProps);
- } else if (i < 16) {
- koGame.imgsRow4.push(imgProps);
- }
1.4 After finishing the For-Loop, push the four observable arrays into the main observable array imgsRows
- koGame.imgsRows.push(self.imgsRow1);
- koGame.imgsRows.push(self.imgsRow2);
- koGame.imgsRows.push(self.imgsRow3);
- koGame.imgsRows.push(self.imgsRow4);
1.5 Define an observable property
- self.emptyImgUrl = ko.observable("url(Images/Images100x100/EmptyImg.png)");
1.6 Replace the real background image of each block with an empty image by changing the observable image property "currentShowImgImage"
- setTimeout(function() {
- for (var i = 0; i < 4; i++) {
- for (var j = 0; j < 4; j++) {
- (koGame.imgsRows()[i])()[j].currentShownImgUrl(koGame.emptyImgUrl());
- }
- }
- }, 2500);
All the snippts code of points 1.3 ,1.4,1.5 and 1.6 should be written inside "getRandomImages" function inside the GameViewModel.
Step 2
Create a user interface view using HTML tags that should be written in a way to receive a knockout binding object , so create "divGame" as a container div and create a nested foreach loop for binding imgsRows array.
- <div class="container-fluid content" id="divGame">
- <classclass="row">
- <div class="col-md-12">
- <div class=" row" data-bind="style:{'display' : displayImgsRows},foreach: imgsRows">
- <div class="col-md-12" data-bind="foreach: $data">
- <div class="img" data-bind="click:$root.onClickImage , style: { 'pointer-events' : imgPointerEvent , 'background-image': currentShownImgUrl}"></div>
- </div>
- </div>
- </div>
- </div>
- </div>
Step 3
Bind GameViewModel to "divGame" container div and then call "getRandomImages"
- koGame = new GameViewModel();
- ko.applyBindings(koGame, document.getElementById("divGame"));
- koGame.getRandomImages();
Step 4
Inside GameViewModel,Create an "onClickImage" function to check if the two clicked images are the same or not. Before that, create these obserervable properties with these initialization inside GameViewModel.
- self.clickedImgName = ko.observable("");
- self.clickedImgPositionX = ko.observable(-1);
- self.clickedImgPositionY = ko.observable(-1);
- self.clickedImgIndex = ko.observable(-1);
- self.clickedImgUrl = ko.observable("");
- self.clickedShownImgUrl = ko.observable("");
- self.firstClickedImgIndex = ko.observable(-1);
- self.firstClickedImgPositionX = ko.observable(-1);
- self.firstClickedImgPositionY = ko.observable(-1);
- self.firstCurrentShownImgUrl = ko.observable("");
- self.firstClickedImgName = ko.observable("");
- self.secondClickedImgIndex = ko.observable(-1);
- self.secondClickedImgPositionX = ko.observable(-1);
- self.secondClickedImgPositionY = ko.observable(-1);
- self.secondCurrentShownImgUrl = ko.observable("");
- self.secondClickedImgName = ko.observable("");
Notice that the "onClickImage" function will be fired each time the user clicks on an image.
4.1 Fill all clicked image properties inside the "onClickImage" function.
- self.onClickImage = function(data, event) {
- koGame.clickedImgPositionX(-1);
- koGame.clickedImgPositionY(-1);
- koGame.clickedImgIndex(data.imgIndex());
- koGame.clickedImgName(data.imgName());
- koGame.clickedImgUrl(data.imgUrl());
- koGame.clickedShownImgUrl(data.currentShownImgUrl());
-
- for (var i = 0; i < 4; i++) {
- for (var j = 0; j < 4; j++) {
- if ((koGame.imgsRows()[i])()[j].imgIndex() == koGame.clickedImgIndex()) {
- (koGame.imgsRows()[i])()[j].currentShownImgUrl(koGame.clickedImgUrl());
- koGame.clickedImgPositionX(j);
- koGame.clickedImgPositionY(i);
- break;
- }
- }
- }
- }
4.2 Inside the "onClickImage" function, two important properties should be used, "koGame.firstClickedImgIndex()", and "koGame.secondClickedImgIndex() ".
The first time that the user clicks on an image, all properties related to "firstClickedImage" should be filled.
- if (koGame.firstClickedImgIndex() == -1) {
- koGame.firstClickedImgIndex(koGame.clickedImgIndex());
- koGame.firstClickedImgPositionX(koGame.clickedImgPositionX());
- koGame.firstClickedImgPositionY(koGame.clickedImgPositionY());
- koGame.firstCurrentShownImgUrl(koGame.clickedImgUrl());
- koGame.firstClickedImgName(koGame.clickedImgName());
- (koGame.imgsRows()[koGame.firstClickedImgPositionY()])()[koGame.firstClickedImgPositionX()].imgPointerEvent('none');
- }
Also, when user click on another image, all properties for the "secondClickedImage" should to be filled too.
- if (koGame.secondClickedImgIndex() == -1) {
- koGame.secondClickedImgIndex(koGame.clickedImgIndex());
- koGame.secondClickedImgPositionX(koGame.clickedImgPositionX());
- koGame.secondClickedImgPositionY(koGame.clickedImgPositionY());
- koGame.secondCurrentShownImgUrl(koGame.clickedImgUrl());
- (koGame.imgsRows()[koGame.secondClickedImgPositionY()])()[koGame.secondClickedImgPositionX()].imgPointerEvent('none');
- }
4.3 Check if the two clicked images are the same or not by comapring the imgUrl property for the first and second image. If they are equal, hide the two images and increase the score by 5. Otherwise, change the shown image URL to an empty image URL and decrease the score by 5.
- if ((koGame.imgsRows()[koGame.firstClickedImgPositionY()])()[koGame.firstClickedImgPositionX()].imgUrl() !=
- (koGame.imgsRows()[koGame.secondClickedImgPositionY()])()[koGame.secondClickedImgPositionX()].imgUrl()) {
- (koGame.imgsRows()[koGame.firstClickedImgPositionY()])()[koGame.firstClickedImgPositionX()].currentShownImgUrl(koGame.emptyImgUrl());
- (koGame.imgsRows()[koGame.secondClickedImgPositionY()])()[koGame.secondClickedImgPositionX()].currentShownImgUrl(koGame.emptyImgUrl());
- koGame.score(koGame.score() - 5);
- (koGame.imgsRows()[koGame.firstClickedImgPositionY()])()[koGame.firstClickedImgPositionX()].imgPointerEvent('auto');
- (koGame.imgsRows()[koGame.secondClickedImgPositionY()])()[koGame.secondClickedImgPositionX()].imgPointerEvent('auto');
-
- } else {
- koGame.score(koGame.score() + 5);
- (koGame.imgsRows()[koGame.firstClickedImgPositionY()])()[koGame.firstClickedImgPositionX()].imgPointerEvent('none');
- (koGame.imgsRows()[koGame.secondClickedImgPositionY()])()[koGame.secondClickedImgPositionX()].imgPointerEvent('none');
- (koGame.imgsRows()[koGame.firstClickedImgPositionY()])()[koGame.firstClickedImgPositionX()].currentShownImgUrl("");
- (koGame.imgsRows()[koGame.secondClickedImgPositionY()])()[koGame.secondClickedImgPositionX()].currentShownImgUrl("");
-
- }
Step 5
Now let's move to result part:
5.1 Inside GameViewModel,Create observable properties for result part:
- self.disapearedImgsRowsFirstPart = ko.observableArray();
- self.disapearedImgsRowsSecondPart = ko.observableArray();
- self.allImgesCount = ko.observable(16);
- self.allDisapearedImgesCount = ko.observable(0);
- self.cardsFlipped = ko.observable(0);
All the thses properties are filled once the two clicked images are matched. So, the following code should be written with an else condition in point 4.3 "koGame.allDisapearedImgesCount" property increased by 2, count of first and second images.
Two observable arrays are needed to show the images on left and right side of the result table.
- koGame.allDisapearedImgesCount(koGame.allDisapearedImgesCount() + 2);
-
- if (koGame.allDisapearedImgesCount() < 9) {
- koGame.disapearedImgsRowsFirstPart.push({
- 'imgUrl': ko.observable('url(Images/Images20x20/' + koGame.firstClickedImgName() + ')')
- });
- }
-
- if (koGame.allDisapearedImgesCount() > 9) {
- koGame.disapearedImgsRowsSecondPart.push({
- 'imgUrl': ko.observable('url(Images/Images20x20/' + koGame.firstClickedImgName() + ')')
- });
- }
-
-
- if (koGame.allImgesCount() == koGame.allDisapearedImgesCount()) {
- koGame.displayImgsRows('none');
- koGame.displaySuccessMsg('block');
- }
5.2 Create HTML tags for the result part:
- <div class="row result">
- <div class="col-md-2">
- <div class="row" data-bind="foreach: disapearedImgsRowsFirstPart">
- <div class="disapeared-img" data-bind="style: { 'background-image' : imgUrl }"></div>
- </div>
- </div>
-
- <div class="col-md-8">
- <table class="table table-bordered result-table">
- <thead>
- <tr>
- <th>Cards Flipped</th>
- <th>Score</th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td data-bind="text:cardsFlipped"></td>
- <td data-bind="text:score"></td>
- </tr>
- </tbody>
- </table>
- </div>
- <div class="col-md-2">
- <div class="row" data-bind="foreach: disapearedImgsRowsSecondPart">
- <div class="disapeared-img" data-bind="style: { 'background-image' : imgUrl }"></div>
- </div>
- </div>
- </div>
Step 6
Inside GameViewmodel create a "refresh" function to initialize all properties and clear all arrays within the viewmodel, then calling the "getRandomImages" function to restart the game.
- self.refresh = function(data, event) {
-
- koGame.disableClickOnImage(true);
- koGame.clickedImgPositionX(-1);
- koGame.clickedImgPositionY(-1);
- koGame.clickedImgIndex(-1);
- koGame.clickedImgUrl("");
- koGame.clickedShownImgUrl("");
- koGame.firstClickedImgIndex(-1);
- koGame.firstClickedImgPositionX(-1);
- koGame.firstClickedImgPositionY(-1);
- koGame.firstCurrentShownImgUrl("");
- koGame.secondClickedImgIndex(-1);
- koGame.secondClickedImgPositionX(-1);
- koGame.secondClickedImgPositionY(-1);
- koGame.secondCurrentShownImgUrl("");
- koGame.cardsFlipped(0);
- koGame.score(0);
- koGame.imgsRow1.removeAll();
- koGame.imgsRow2.removeAll();
- koGame.imgsRow3.removeAll();
- koGame.imgsRow4.removeAll();
- koGame.imgsRows.removeAll();
- koGame.disapearedImgsRowsFirstPart.removeAll();
- koGame.disapearedImgsRowsSecondPart.removeAll();
- koGame.displaySuccessMsg('none');
- koGame.getRandomImages();
-
- }
That's all , Now you can create your own version and use your own images by replacing them with the ones which are found in the images folder. Just take care about the images dimension, 100x100 px and 20x20 px.
If you have any question or any feedback please leave a comment .
Have a nice day!