-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcatmatch.js
109 lines (97 loc) · 2.32 KB
/
catmatch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
var cm = (function() {
var cm={};
var deck;
var apikey = null; // set your apikey here !
var numPairs = 6;
var firstTurned;
var pairsFound;
cm.init = function() {
$('#welcome').fadeIn('fast');
$('a').click( playGame );
}
function playGame() {
$('#welcome').fadeOut('fast');
$('#again').fadeOut('fast');
$('#loading').fadeIn('fast')
dealCards();
return false;
}
function dealCards() {
if (deck == null) {
loadCards();
} else {
var cards = selectCards();
shuffle(cards);
layout(cards);
firstTurned = null;
pairsFound = 0;
$('#loading').fadeOut('fast', function() {
$('#game').fadeIn();
});
}
}
function loadCards() {
dki.apikey = apikey;
dki.fetchImages({caption: 'cat', keywords: 'feline', limit: 100}, function(data) {
deck = data.images;
dealCards();
});
}
function selectCards() {
var cards = [];
while (cards.length < numPairs * 2) {
var card = deck[Math.floor(Math.random() * deck.length)];
if (cards.indexOf(card) == -1) {
cards.push(card, $.extend({}, card));
}
}
return cards;
}
function shuffle(cards) {
for (var i in cards) {
cards[i].order = Math.random();
}
cards.sort( function (a,b) {
return a.order - b.order;
});
}
function layout(cards) {
var cardsHtml = ich.cards({cards: cards});
$('#board').empty();
$('#board').html(cardsHtml);
$('li').click(turnCard);
}
function turnCard(evtObj) {
var card = evtObj.currentTarget;
$(card).toggleClass('flipped');
setTimeout( function() {
checkTurned(card); },
500
);
}
function checkTurned(card) {
if (firstTurned == null) {
firstTurned = card;
} else if (firstTurned == card) {
firstTurned = null;
} else {
checkMatch(card);
}
}
function checkMatch(card) {
if ($(card).data('imageid') == $(firstTurned).data('imageid')) {
$(card).toggleClass('dissolve');
$(firstTurned).toggleClass('dissolve');
pairsFound++;
if (pairsFound == numPairs) {
$('#game').fadeOut();
$('#again').fadeIn();
}
} else {
$(card).toggleClass('flipped');
$(firstTurned).toggleClass('flipped');
}
firstTurned = null;
}
return cm;
})();