Wednesday, 29 November 2017

Basic Game : 4 x 4 Matrix puzzle by using Javascript and Jquery


In this article I had planned with a number puzzle game of 4 x 4 matrix. Here I'm working by using javascript and Jquery. In my upcoming articles I'll go with angular too definitely.
All the code I did is just based on my written algorithm or  views. We can even reduce the code that what I done with, I welcome all the code reduce inputs in comment section.
you can test the code by copying and pasting in the below link of try it editor.


Test my code here by copying the below code

 <html>  
 <head>  
 <style>  
 table {  
   border-collapse: collapse;  
 }  
 table, td, th {  
   border: 1px solid black;  
 }  
 table {  
 empty-cells:show;  
 }  
 div{  
 height:50px;  
 width:50px;  
 }  
 .cellclick{  
 text-align: center;  
 vertical-align: middle;  
 line-height: 50px;  
 }  
 </style>  
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
 <script>  
 var bookedArr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];  
 var initEmpty = randomInitEmpty(1,16);  
 var allowedClicks = [];  
 var valForLast="";  
 var clickCount=0;  
 $( document ).ready(function() {   
  bookedArr = shuffleNumbers(bookedArr);  
  console.log(bookedArr);  
  $(bookedArr).each( function( index, value ) {   
  index=index+1;   
      $('#'+index).text(value);  
 });  
      valForLast=$('#'+initEmpty).text();  
      $('#'+initEmpty).text("");  
      $('#'+16).text(valForLast);  
      setallowedclicks(initEmpty);  
      $('.cellclick').click(function(){  
      clickCount=clickCount+1;  
      $("#spTotClicks").text(clickCount);  
           //get the value of clicked cell  
           var clickedVal=$(this).text();  
           var clickedDvId = $(this).attr("id");  
           if(jQuery.inArray(clickedVal, allowedClicks) != -1) {  
                     //if Clicked cell value is allowed.  
                     $("#"+initEmpty).text(clickedVal);  
                     $("#"+clickedDvId).text('');  
                     initEmpty=clickedDvId;  
                     //Refresh the click allowed values  
                     setallowedclicks(initEmpty)  
                     //Game over check.  
           }   
           else {  
                     //if clicked cell is not allowed to move  
                     alert("Not allowed to move.");  
                     return;  
                     console.log("is NOT in array");  
           }  
      });  
 });  
 function setallowedclicks(emptyc) {  
      //alert(emptyc);  
      //Find tr of the empty cell  
           var emptyCellTr= $("table1").find("#"+emptyc).parent().parent();  
      //Find index of clicked cell row  
           var col = $("#"+emptyc).parent().parent().children().index($("#"+emptyc).parent());  
      //left & right values of empty cell  
            var resleft = $("#"+emptyc).closest('td').next().find("div").text();              
            var resright = $("#"+emptyc).closest('td').prev().find("div").text();  
      // Top and bottom values based on same column of empty cell  
            var trprev = $($("#"+emptyc).closest('tr').prev()).find('td div').eq(col).text();  
            var trnext = $($("#"+emptyc).closest('tr').next()).find('td div').eq(col).text();   
      //Pushing click allowed values into an array  
           allowedClicks = [];  
           allowedClicks.push(resleft);  
           allowedClicks.push(resright);  
           allowedClicks.push(trprev);  
           allowedClicks.push(trnext);  
           console.log(allowedClicks);  
      }       
 function randomInitEmpty(min,max)  
 {  
   return Math.floor(Math.random()*(max-min+1)+min);  
 }  
 function shuffleNumbers(array) {  
  var currentIndex = array.length, tempValue, randomIndex;  
  // While there remain elements to shuffle...  
  while (0 !== currentIndex) {  
   // Pick a remaining element...  
   randomIndex = Math.floor(Math.random() * currentIndex);  
   currentIndex -= 1;  
   // And swap it with the current element.  
   tempValue = array[currentIndex];  
   array[currentIndex] = array[randomIndex];  
   array[randomIndex] = tempValue;  
  }  
  return array;  
 }  
 </script  
 </head>  
 <body>  
 <table id="table1" style="display:inline-block">   
  <tr>  
   <td><div >1</div></td>  
   <td><div >2</div></td>  
   <td><div >3</div></td>  
      <td><div >4</div></td>  
  </tr>  
  <tr>  
   <td><div >5</div></td>  
   <td><div >6</div></td>  
      <td><div >7</div></td>  
   <td><div >8</div></td>  
  </tr>  
  <tr>  
   <td><div >9</div></td>  
      <td><div >10</div></td>  
      <td><div >11</div></td>  
      <td><div >12</div></td>  
  </tr>  
  <tr>  
   <td><div >13</div></td>  
      <td><div >14</div></td>  
      <td><div >15</div></td>  
      <td><div ></div></td>  
  </tr>  
 </table>  
 <div style="display:inline-block;width:125px">  
 Total Moves : <span id="spTotClicks" style="display:inline-block;"></span>   
 </div>  
 <table id="table1" style="display:inline-block;">   
  <tr>  
   <td><div id='1' class='cellclick'></div></td>  
   <td><div id='2' class='cellclick'></div></td>  
   <td><div id='3' class='cellclick'></div></td>  
      <td><div id='4' class='cellclick'></div></td>  
  </tr>  
  <tr>  
   <td><div id='5' class='cellclick'></div></td>  
   <td><div id='6' class='cellclick'></div></td>  
      <td><div id='7' class='cellclick'></div></td>  
   <td><div id='8' class='cellclick'></div></td>  
  </tr>  
  <tr>  
   <td><div id='9' class='cellclick'></div></td>  
      <td><div id='10' class='cellclick'></div></td>  
      <td><div id='11' class='cellclick'></div></td>  
      <td><div id='12' class='cellclick'></div></td>  
  </tr>  
  <tr>  
   <td><div id='13' class='cellclick'></div></td>  
      <td><div id='14' class='cellclick'></div></td>  
      <td><div id='15' class='cellclick'></div></td>  
      <td><div id='16' class='cellclick'></div></td>  
  </tr>  
 </table>  
 </body>  
 </html>  


Explanation with my views while developing :
Here, I'll discuss about the creation of the game board which was done over one of the table with id "table1". Steps I followed while developing are as follows :

Step 1 : 
Initially, I had thought about the board look as it is 4 x 4 matrix, One position needs to be empty and the remaining needs to filled.
I had named my empty cell as "initEmpty" which I get it by creating the javascript function named "randomInitEmpty()".To this function I will pass the two parameters like minimum and maximum number of our values as 1-16.
Step 2 :
Secondly, I thought about to fill the 4 x 4 board with a shuffle of numbers. So, here I created a function named "shuffleNumbers" which will take our array as parameter which has to fill our board numbers.
Step 3 :
The shuffled array has to fill in the board. while filling the board I had to make sure that our "initEmpty" value cell of the board to be empty. Which I had done by replacing the empty cell with the last or 16th cell value.
Step 4 :
By the above views I got my board as like ground to play.After that the only task I got is just to replace the clicked adjacent cell of empty cell value to the empty cell. Managed with a variable increment on every cell click which gives us total count for clicks.
Finally :
Hahaa, I realized that I enjoyed a lot while working over above steps.
Very soon I'll bring it by using angular JS.

Result :

On game begin :
On game end :




Thank you.

7 comments: