memory game
http://stackoverflow.com/questions/17282970/saving-and-comparing-table-cell-values
HTML
<table></table>
<span id="info"></span>
CSS
table td {
border:1px solid #ccc;
width:3em;
height:2em;
text-align:center;
cursor:pointer;
}
JavaScript
$(document).ready(function () {
var countCells;
var createTable = function (col, row) {
var str = '';
for (var i = 1; i <= row; i++) {
str += '<tr>';
for (var j = 1; j <= col; j++) {
str += '<td>';
}
str += '</tr>';
}
$('table').empty().html(str);
countCells = row * col;
};
createTable(6, 6);
function shuffle(o) {
for (var j, x, i = o.length; i; j = parseInt(Math.random() * i, 10), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
// http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript
var arr = [];
for (var i = 0; i < countCells / 2; i++) {
arr[i] = arr[i + countCells / 2] = i + 1;
}
shuffle(arr);
//console.log(arr);
var tds = $('table td');
tds.each(function (i) {
this.setAttribute('data-num', arr[i]);
});
var attempts = 0;
var match1 = null;
var info = $('#info');
var wait = false;
$('td').click(function () {
if (wait) {
return;
} // wait until setTimeout executes
var num = this.getAttribute('data-num');
if (match1 === null && num != 'X') { //1st click on unmatched cell
match1 = this;
this.innerHTML = num;
attempts++;
info.text('Attempts: ' + attempts);
return;
} else { //2nd click
var num1 = match1.getAttribute('data-num'); //1st num
console.log(num, num1, num == num1);
if (match1 === this) {
// clicked twice this cell
return;
} else if (num == 'X') {
// clicked on already revealed cell
return;
} else if (num == num1) {
// both cells match
info.text('Bingo! Attempts: ' + attempts);
this.innerHTML = match1.innerHTML = num1;
...