You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
sae_2a_anglais/Project/php/js/memory.js

85 lines
3.2 KiB

document.addEventListener('DOMContentLoaded', function () {
var cards = document.querySelectorAll('.card');
var nbCard = 0;
var word1;
var word2;
var clickEnabled = true;
var score = 25;
cards.forEach(function (card) {
card.addEventListener('click', function () {
if(clickEnabled === false || card.dataset.word === word1 || card.classList.contains('found')){
return;
}
card.classList.toggle('flipped');
nbCard += 1;
if (nbCard === 1) {
word1 = card.dataset.word;
} else if (nbCard === 2) {
word2 = card.dataset.word;
}
if (nbCard === 2) {
clickEnabled = false;
if (checkForMatch(word1, word2) === true) {
cards.forEach(function (card) {
if (card.dataset.word === word1 || card.dataset.word === word2) {
card.classList.add('found');
card.removeEventListener('click', null); // Remove click event listener
}
});
setTimeout(function () {
cards.forEach(function (card) {
if (card.dataset.word === word1 || card.dataset.word === word2) {
card.classList.add('invisibleFound');
card.removeEventListener('click', null); // Remove click event listener
}
});
checkGameCompletion(); // Check if all pairs are found
clickEnabled = true;
}, 2000);
} else {
cards.forEach(function (card) {
if (!card.classList.contains('found') && (card.dataset.word === word1 || card.dataset.word === word2)) {
card.classList.add('wrong');
}
});
setTimeout(function () {
cards.forEach(function (card) {
if (!card.classList.contains('found') && (card.dataset.word === word1 || card.dataset.word === word2)) {
card.classList.toggle('flipped');
card.classList.remove('wrong');
}
});
clickEnabled = true;
}, 1500);
}
nbCard = 0;
}
});
});
function checkForMatch(word1, word2) {
for (let i = 0; i < pairs.length; i++) {
const pair = pairs[i];
if (
(pair[0] === word1 && pair[1] === word2) ||
(pair[0] === word2 && pair[1] === word1)
) {
score+=10;
return true;
}
}
if(score !== 0){
score-=1;
}
return false;
}
function checkGameCompletion(){
if (document.querySelectorAll('.card.found').length === cards.length) {
window.location.href = '../resultatsJeux/' + score;
}
}
});