发现它很有趣,所以我尝试用简单的 jQuery 来实现它
jQuery记忆游戏
var $mainTable = $('#mainTable'),
myWords = [],
valA, valB, col=4, row=3, start;
// function to create the table
var createTable = function (col, row) {
var $table = $('<table>'), i;
// construct our table internally
for(var i=0; i<row; i++){
var $tr = $('<tr data-row="'+i+'">'); // make row
for(var j=0; j<col; j++){
$tr.append($('<td data-col="'+j+'">')); // make cell
}
$table.append($tr);
}
$mainTable.html($table.html());
};
// generate an array random words from a dictionary
var giveWords = function(pairsRequested){
var dictionary = ['now','this','is','only','a','test','I','think'],
ar = dictionary.slice(0,pairsRequested);
ar = ar.concat(ar);
// taken from @ http://jsfromhell.com/array/shuffle [v1.0]
for(var j, x, i = ar.length; i; j = parseInt(Math.random() * i), x = ar[--i], ar[i] = ar[j], ar[j] = x);
return ar;
}
// initialize
createTable(col,row);
myWords = giveWords(6); // our words array
// listen
$mainTable.on('click', 'td' ,function(){
var $that = $(this),
thisCol = $that.data('col'),
thisRow = $that.closest('tr').data('row');
if(!valB && !$that.hasClass('clicked')){
var itemNum = (thisRow*(col))+thisCol;
if(!valA){ // first item clicked
valA = myWords[itemNum];
$that.addClass('clicked')
.text(valA);
} else { // we already have a clicked one
valB = myWords[itemNum];
if(valA === valB){ // if they match...
$mainTable.find('.clicked')
.add($that)
.removeClass('clicked')
.addClass('revealed')
.text(valA);
// check how many open remaining
var open = $mainTable.find('td')
.not('.revealed')
.length;
if(open===0){ // if 0, game over!
var elapsed = Date.now()-start;
alert('Congratulations! cleared the table in '+elapsed/1000+' seconds.');
}
valA = valB = undefined;
} else {
$that.addClass('clicked')
.text(valB);
setTimeout(function(){ // leave the value visible for a while
$mainTable.find('.clicked')
.removeClass('clicked')
.text('');
valA = valB = undefined;
},700);
}
}
}
if(!start){ // keep time of game completion
start=Date.now();
}
});