Следующий код исправляет все заявленные и неустановленные проблемы, в том числе
- тасование
- не может выбрать одну и ту же первую карту в двух попытках
Надеюсь, это поможет
/*
* Create a list that holds all of your cards
*/
const cards = [...document.querySelectorAll('.card')];
const carddeck = document.querySelector('.deck');
let hasturnedcard = false;
let firstclick, secondclick;
//letting the board pause a little long until the cards and turned fully
let pauseboard = false;
function turncard() {
if (pauseboard)
return; //pause the board from turning tiles more than two tiles
// if the card contains show it's either already selected as the first selection, or is a match - either way ignore clicks
if (this.classList.contains('show')) {
return;
}
this.classList.add('open', 'show');
if (!hasturnedcard) {
hasturnedcard = true;
firstclick = this;
} else {
hasturnedcard = false;
secondclick = this;
matchingtiles();
}
}
// the created to see whether the tiles are matching
function matchingtiles() {
if (firstclick.dataset.name === secondclick.dataset.name) {
//its a match
firstclick.classList.add('match');
secondclick.classList.add('match');
// no need to remove click handler, since we handle logic in the click handler, and on reset we'd just add the click handler again anyway!
} else {
//not a match
tilesturning();
}
}
// if the tiles are not a match after the click function a timeout is added to slow the process of tiles turning back again
function tilesturning() {
pauseboard = true;
setTimeout(() => {
//delaying the turning process
firstclick.classList.remove('open', 'show');
secondclick.classList.remove('open', 'show');
firstclick = secondclick = null;
pauseboard = false;
}, 1000);
}
cards.forEach(card => card.addEventListener('click', turncard));
// reset the card of tiles after clicking on the reset button
document.querySelector('.restart').addEventListener('click', () => {
shuffle(cards);
cards.forEach(card => {
card.classList.remove('open', 'show', 'match');
carddeck.appendChild(card);
});
});
function shuffle(array) {
var currentIndex = array.length,
temporaryValue,
randomIndex;
while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}