Память Game javascript Функция сброса работает только для последних двух кликов - PullRequest
0 голосов
/ 03 ноября 2019

Я играю в память, но не могу найти решение для сброса карты. На данный момент я написал небольшой код, который будет переворачивать только две последние карты, которые были нажаты в игре, но я хочу, чтобы все карты переворачивались при нажатии кнопки сброса button.

Вот кодниже:

const resetbtn = document.querySelectorAll('.restart');

function resetcard(){

  if(cards[firstclick] == cards[secondclick]){
    firstclick.classList.remove('open','show','match');
    secondclick.classList.remove('open','show','match');
  }

}

resetbtn.forEach(resetbt => resetbt.addEventListener('click',resetcard));

Ссылка на проект здесь .

Ответы [ 2 ]

1 голос
/ 03 ноября 2019

Следующий код исправляет все заявленные и неустановленные проблемы, в том числе

  • тасование
  • не может выбрать одну и ту же первую карту в двух попытках

Надеюсь, это поможет

/*
 * 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;
}
0 голосов
/ 03 ноября 2019

Похоже, вы получаете доступ к карте карт с элементами HTML в качестве ключей, вам следует использовать уникальные строки, например, вы можете использовать идентификатор элемента, например cards[firstClick.id].

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...