Image match javascript memory game

Games !!! Its always fun to play games. i think 70% people likes to play games, out of remaining 30% percent 20% likes to play but dont find time, and remaining 10% ?? i dont want to talk about them :D. well, thats not a point we are going to discuss here.
This Image match javascript memory game idea was in my mind from long back but due to time i wasnt able to draw it in a browser. but no matter Image match javascript memory game is in browser now and i am feeling little little light, because there are still many ideas waiting for their turn.
For this Image match javascript memory game i am using one free jquery plugin named rotate3Di and i am really thankful of Zachary Johnson half of work was done my him and remaining half was done by jquery,i didnt do anything at all.Play ! Download

Image match javascript memory game Game Setup

1) Include javascript,jquery and css files


2) Put images in images folder
Make sure they are .PNG files. You can change this to any extension just dont forgot to mention it in game.js file.

3) Create HTML page
For this you just need to add few lines (If you want to show game only and dont want to show click and high scores etc)


4) Game Logic
And here is the logic, the game.js.

$(document).ready(function () {
	var counter = 0;
	var images  = new Array();
	var match = new Array();
	var check = 0;
	var blocks = "";
	var no_of_blocks = 24;

	//clear input box and load scores on bodyload event
	$("#uname").val("");
	load_scores_list();

	// add image blocks to game screen
	for(i=1;i<=no_of_blocks;i++){
	  blocks +='<li id="'+i+'"><div class="front"><a href="#"></a></div><div class="back" style="display:none;"><a href="#"></a></div></li>\n';
	}
	$("#nav-list-example").html(blocks);
	
	// shuffle images and show
	$('#nav-list-example li div.back').each(function(){
	  var randomnumber = Math.floor(Math.random()*Math.round(no_of_blocks/2));
	  
	  // generate new random number until u find unique number
	  while (get_occurance_count(randomnumber)) {
		randomnumber = Math.floor(Math.random()*Math.round(no_of_blocks/2));
	  }
	  
	  $(this).css("background","url('images/"+randomnumber+".png')").css("background-repeat","no-repeat");	
	  //$(this).css("background","url(images/"+randomnumber+".png)").css("background-repeat","no-repeat");	  
	  images.push(randomnumber);
	});

	$('#nav-list-example li div.back').hide().css('left', 0);
    
    function mySideChange(front) {
        if (front) {
            $(this).parent().find('div.front').show();
            $(this).parent().find('div.back').hide();
            
        } else {
            $(this).parent().find('div.front').hide();
            $(this).parent().find('div.back').show();
        }
    }
    
	// on image block click event
    $('#nav-list-example li').click(function(){
      id = $(this).attr("id");
	  // if 2 images are open then close all and open recently clicked image    
       if(counter == 2 && $(this).find("div").html() != null){  
        $("#nav-list-example").find('div.active').removeClass("active");  
        $("#nav-list-example").find('div').stop().rotate3Di('unflip', 200, {sideChange: mySideChange});
        counter = 0;
        match = new Array();
        flipImage(id);
      } else{
	  	flipImage(id);
      }
    });

	var clicks = 0;
	$("#list ul").live("mouseover",function(){
		$(this).find("li").css("background","black");
	});
	
	$("#list ul").live("mouseout",function(){
		$(this).find("li").css("background","#252525");
	});
	
	$("#nav-list-example li").click(function(){
		clicks++;
		$("#score").find("span").html(clicks);
	});
	
	$("#controls input").click(function(){
		document.location.href = document.location.href;
	});
	
	// save game score
	$("#save").click(function(){
		var user  = $("#uname").val();
		var score = $("#score").find("span").html();
		if(user != ""){
			$.ajax({
			   type: "POST",
			   url: "ajax_server.php",
			   data: "action=save&name="+user+"&score="+score,
			   success: function(msg){
				 $(".userinfo").fadeOut("slow");
				 $('<ul><li id="name">'+user+'</li><li>'+score+'</li></ul>').appendTo("#list");
			   }
			 });
		}
	});

	$("#cancel").click(function(){
		$(".userinfo").fadeOut("slow");
	});
	
	function load_scores_list(){
		var list = "";
		$.ajax({
		   type: "POST",
		   url: "ajax_server.php",
		   data: "action=get",
		   success: function(responce){
			 var json = jQuery.parseJSON(responce);
			 $.each(json, function(i,record){
				list += '<ul><li id="name">'+record.name+'</li><li>'+record.score+'</li></ul>';
				$("#list").html(list);
			 });
		   }
		 });
	}
	
	// check if image is there 2 times ?
    function get_occurance_count(randomnumber){
        var count = 0;
        for ( var i = 0; i < images.length; i++ ) {
            if(images[i] == randomnumber)
              count++;
        }
        if(count == 2) return true;
        return false;
    }
    
	function flipImage(id){
       if($('#nav-list-example li[id='+id+']').find('div.front').css("display") == 'block'){
          if($('#nav-list-example li[id='+id+']').find("div").html() != null){
            counter++; 
            match.push($('#nav-list-example li[id='+id+']').find('div.back').css("background-image"));
            $('#nav-list-example li[id='+id+']')
            .find('div')
            .addClass("active")
			.stop().rotate3Di('flip', 200, {direction: 'clockwise', sideChange: mySideChange,complete: checkMatch});           
          }
      }else{
          if($('#nav-list-example li[id='+id+']').find("div").html() != null){
             $('#nav-list-example li[id='+id+']').find('div').stop().rotate3Di('unflip', 200, {sideChange: mySideChange});
             counter--;
          }
      }    
    }

    function checkMatch(){
	    if(match.length == 2){
	        // check if there are 2 unique entries and not same image clicked twice
	        if(match[0] == match[1] && $("#nav-list-example").find('div.active').length == 4){
	          $('.active').fadeOut("fast",function(){$(this).remove();gameEnd();});
	        }
	        match = new Array();
  		}                
    }
    
	// check game end
    function gameEnd(){
		if(parseInt($('#nav-list-example li').find("div:visible").length) == 0)
			$(".userinfo").fadeIn("slow");
	}
}); /* End of WORLD */
Note: If you want to increase number of blocks then just change "no_of_blocks" to any EVEN number and place extra images in images folder.

 

How to play Image match javascript memory game game

1) You will be shown blocks with faces down.
2) Click on each block and face will open.
3) Try to find the same image by clicking other blocks.
4) If you manage to find two blocks with same images then both the block will disappear.
5) Finish all the blocks game will over.
6) Try to finish the game in less clicks and you will be high scorer.

HAPPY GAMING ! 

About Amit

   Myself Amit Patil from Maharashtra (India). I have been working as a Web Application Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically i am a PHP developer but now a days exploring more in CSS and javascript.

Comments

  1. i like it 8)

  2. Thanks :) 8)

  3. Is there any update for this script available? really love it and wanan make use of it, really nice script, big thanks…

    • sent to ur email :)

      • My boss thinks this could help me learn some javascript/jquery. Can I also get the latest update of this? thanks.

        • Say thanks to ur boss from me :) I m sorry to say but i m not going to update this script because i m bz with office work and more than that bz with few advanced scripts like 1) gmail like “drag-drop” file upload (90% done) 2) Facebook like “like button” script (70% done) 3) Gmail like GTalk chat script (70% done). But if u really want to see the updates please start urself and i will help u implement the updates.

  4. Thanks a lot. Really simple and useful in Firefox. But what about updates?

    “Image match game is only supported in Firefox 3.5+. You can expect support for all browsers in newer version.”

    • Dmitry : I wanted to update the script to make it support all the browsers, But i think instead of wasting time on this script i should move to the next script, first thing is this script isnt that much useful (i made this script just for fun/experiment), and second things is, it will take toooo much time to make it work in all browser (I am not css, javascript ninja so it will be headache for me), if i utilize same time for creating other 2-3 script it will be much appreciated. so sorry to say, i am not going to work on it anymore. I am working on 2-3 scripts like 1) gmail like “drag-drop” file upload (70% done) 2) Facebook like “like button” script (60% done) 3) Gmail like GTalk chat script (50% done). I think this scripts will me more useful for my visitors…isnt it ??

  5. nice

  6. Hi Amit,
    Your blog is very useful and I have learnt a lot from your ideas. Thank you for keep posting great stuff :) .

    Actually your javascript memory game is perfect. You just miss something in the code so it shows only on firefox. Just update it as below:

    File: game.js

    Original code
    $(this).css(“background”,”url(‘images/”+randomnumber+”.png”).css(“background-repeat”,”no-repeat”);

    Updated code
    $(this).css(“background”,”url(images/”+randomnumber+”.png)”).css(“background-repeat”,”no-repeat”);

    Hope it works for you too. Have a great day!

    Cheers,
    Matt

    • Matt, I am really thankful for your help, you found the mistake. It was simple “single quote” that was making problem in browsers other than firefox. Many users was asking me for this but i thought its problem of rotating plugin and thought to look at it later but didnt found time for it. Anyways it working fine now because of you. Thanks

  7. claudioking@gmail.com' Claudio says:

    Please does anyone know how to display the name of the images that matched (right after or right before they disappear)?
    I also would like to have another separate image changing every time there’s a match. Does anyone know how do to that?
    Thank you. Great tutorial!

  8. i want to zoom the each div ,when i click that

  9. Hey Amit! Your code sample was awesome and i managed to implement it with very little changes :) but even if the game runs great, i can’t save my scores or populate the list with them. I don’t know what i’m doing wrong, but i get a ‘Uncaught SyntaxError: Unexpected token <' error with the same code i downloaded from your site!

    any ideas what i might be doing wrong? any help would be appreciated <3

    • Check your database configuration. There is some database error which throwing error (with html contents), “Unexpected token <” says it clearly that script was expecting data in JSON format, but actually its receiving html contents.

      • Turns out i was missing the
        header(‘Content-Type: application/json’);
        part in the php file :) now i can write scores in my database :) thanks for pointing me in the right direction! <3

        Now i get a null error from the get_scores function :/ i have no idea why, since i can write scores OK, but since i can't get them back to display in the scoreboard, the function never completes and it's stuck on 'loading'.

        :(

        I'm sure i'll figure it out eventually though. Thanks so much for the 'you're getting html instead of json' heads-up :)
        if you're ever in Chile, come collect your free coffee and bagel!

  10. ilham.ideaz@gmail.com' Ilham Ideaz says:

    Sorry, I’m newbie. I paste this in notepad with name game.js. But, it’s shows ; problem.
    So, mind to teach me stepby step? Thanks! :)

  11. Hi, great script!

    Any idea why it is not working in IE? Just opens all the icons until you find a pair.

    thanks in advance :)

    • “unfortunately most of the good things are not supported by IE”, Use latest IE version. Day i become rich its my dream to buy IE copyrights and throw that crap in a dustbin.

      • Hi,

        thanks for your reply, i just updated the jquery_flip.js to the latest version and its working in all IE versions now.

        Nice script :)

Speak Your Mind

*


*

Notify me of followup comments via e-mail. You can also subscribe without commenting.

More in Ajax, CSS, jQuery (21 of 39 articles)


In this Fetch Facebook friends demo i am going to demonstrate below things, in short...for more info please see ...