/* * Memory - classic card game * (C) 2012 by Gavriel Fleischer * http://neswork.com/javascript/js1k/2012/ */ // define DOM selector function instead of jQuery :) function \$(s,d){if(!d)d=b;return d.querySelectorAll(s)}; // addClass function A(e,c){e.classList.add(c)} // removeClass function R(e,c){e.classList.remove(c)} // constants we use a lot of time // set up styles h=""; \$("head",document).innerHTML=h; /* */ function M(){ // counter for number of steps e=0; /* * Fill in an array that represents the pack of cards. * Put each digit twice. Those will be the pairs. */ p=[];for(i=0;i<8;i++){p[i]=p[i+8]=i} // start to draw the screen d='
0 steps ⟲ restart
'; // we need to create 16 cards for(i=16;i>0;i--) d+='
' // take out a random element from the pack +p.splice(Math.floor(i*Math.random()),1) +'
'; // add it to the DOM b.innerHTML=d+'
'; f=\$("#C"); /* * Now we set up the onclick function for each card. * * We use classes to be able to count some group of cards: * "p" is used for "paired" cards that stay visible forever * "v" is used for the 1 or 2 cards that we turned on and are currently "visible" */ [].forEach.call(\$(".w"),function(w){ w.addEventListener("click", function(){ t=this; // increase the counter and display it f.innerHTML=++e; // get the visible cards v=\$(".v"); x=v; y=v; // if 2 cards are visible we need to turn them back /*v.length==2*/ if(y){ R(x,"v"); R(y,"v"); } // if one card was visible we need to compare it with the one we just turned /* v.length==1 */ if(x&&!y&&x!=t&&x.innerHTML==t.innerHTML){ // if they match we sign them as "paired" A(t,"p"); R(x,"v"); A(x,"p") }else A(t,"v"); // otherwise we set the currently turned card to visible // see if we finished the whole pack if(\$(".p").length==16) alert("I love You!"); }) }) } M()