/*
* 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)};
// set background color
function B(e,c){e.style.backgroundColor=c}
// set visibility
function V(e,v){e.style.visibility=v}
function C(e,c){e.classList.add(c)}
function R(e,c){e.classList.remove(c)}
// constants we use a lot of time
H="hidden";
S=' style="display:inline-block;';
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='
';
// 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 em")[0];
/*
* 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($("i"),function(t){
t.addEventListener("click", function(){
// increase the counter and display it
f.innerHTML=++e;
// get the visible cards
v=$("b.v");
x=v[0];
y=v[1];
// if 2 cards are visible we need to turn them back
if(v.length==2){
R(x,"v");
V(x,H);
R(y,"v");
V(y,H)
}
s=$("b",this);
z=s[0];
V(z,"visible");
// if one card was visible we need to compare it with the one we just turned
if(v.length==1&&x!=z&&x.innerHTML==z.innerHTML){
// if they match we sign them as "paired"
B(z,"#efe");
C(z,"p");
B(x,"#efe");
R(x,"v");
C(x,"p")
}else C(z,"v"); // otherwise we set the currently turned card to visible
// see if we finished the whole pack
if($("b.p").length==16)
alert("I love You!");
})
})
}
M()