记忆游戏第一张和第二张卡

时间:2018-12-19 12:56:47

标签: javascript

我还是JavaScript编程的新手,我正在做一个记忆游戏...

我想将第一张和第二张单​​击的卡设置为firscard和secondcard变量,以便我可以检查它们是否匹配,或者如果不匹配则再次翻转它们... 到目前为止,这是我的入门代码

const cards = ['fa-diamond', 'fa-diamond',
  'fa-paper-plane-o', 'fa-paper-plane-o',
  'fa-anchor', 'fa-anchor',
  'fa-bolt', 'fa-bolt',
  'fa-cube', 'fa-cube',
  ' fa-leaf', ' fa-leaf',
  'fa-bicycle', 'fa-bicycle',
  'fa-bomb', 'fa-bomb'
];

function createCard(card) {
  return `<li class="card"><i class="fa ${card}"></i></li>`;
}

const deck = document.querySelector('.deck');

function startGame() {

  const cardList = shuffle(cards).map(function(card) {
    return createCard(card);
  });

  deck.innerHTML = cardList.join('');
}
startGame();


// Shuffle function from http://stackoverflow.com/a/2450976
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;
}
let firstCard, secondCard;
const clickedCards = document.querySelectorAll('.card');


function flipCard() {
  this.classList.toggle('open');
  this.classList.toggle('show');
}

clickedCards.forEach(card => card.addEventListener('click', flipCard));
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class='deck'></div>

我只需要告诉我如何设置变量的第一次和第二次点击,以便在此之后检查匹配项。 希望我的解释是足够的,否则请告诉我! 提前致谢。

2 个答案:

答案 0 :(得分:2)

那么,这是您所追求的吗?我并没有做太多改变,只是删除了一些不必要的功能以及其他一些小功能。

编辑

我实际上已经写了一个比较完整的解决方案,对于我假设您要构建的东西,我的意思是它足够简单且足够干净。显然,您需要自己制作。

// Config sorta stuff.
let firstCard, secondCard, index = 0;
const deck = document.querySelector('.deck');
const delay = 750, completeDelay = 100;
const icons = [
  'fa-diamond', 'fa-paper-plane-o', 'fa-anchor',
  'fa-bolt', 'fa-cube', 'fa-leaf', 'fa-bicycle',
  'fa-bomb', 'fa-address-book', 'fa-grav'
];


// Rather than enter the class name twice, just make the array from some other 
// array, basically copy each item over twice.
const cards = Array.from({
  length: icons.length * 2
}, (x, i) => icons[Math.floor(i / 2)]);


// Function to shuffle the array.
const shuffle = a => {
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
};


// A simple way to create the card.
const createCard = card => `<li class="card show" id=${(new Date()).getTime() + (index++)}><i class="fa ${card}"></i></li>`;


// A simple way to hide all of the cards that are currently on display.
const hideAll = () => document.querySelectorAll('.card.show').forEach(card => card.className = 'card');


// A simple function to check that the two cards match. 
const checkMatch = () => {
  if (firstCard.innerHTML == secondCard.innerHTML) {
    firstCard.className = 'card complete'
    secondCard.className = 'card complete';
  }

  setTimeout(onComplete, completeDelay);
};


// Update the values of first card and second card.
const assignCards = card => {
  if (firstCard == null) {
    firstCard = card;
  } else if (secondCard == null && card.id != firstCard.id) {
    secondCard = card;
    checkMatch();
  } else {
    hideAll();
    card.classList.toggle('show')
    firstCard = card;
    secondCard = null;
  }
};


// A simple function that flips the card.
const flipCard = (e) => {
  e.target.closest('li').classList.toggle('show');
  assignCards(e.target.closest('li'));
};


// A simple function that's responsible for adding event listeners.
const dispatchEvents = () => {
  document.querySelectorAll('.card').forEach(card => card.addEventListener('click', flipCard));
  setTimeout(hideAll, delay);
};


// A simple function to run when the game is compelte.
const onComplete = () => {
  let isCompelte = true;

  document.querySelectorAll('.card').forEach(card => {
    if (card.className.indexOf('complete') == -1) {
      isCompelte = false;
    }
  });

  if (isCompelte) {
    alert('Complete!');
    startGame();
  }
};


// A simple function to start the process of everything.
const startGame = () => {
  const cardList = shuffle(cards).map(card => createCard(card));
  deck.innerHTML = cardList.join('');
  dispatchEvents();
};


// Start the game. 
startGame();
body {
  background: #eee;
}

.card.show {
  background: white;
  color: #666;
}

.card.complete {
  background: white;
  border-color: green;
  color: green;
}

.card {
  list-style: none;
  text-align: center;
  border: 1px solid red;
  background: red;
  color: red;
  border-bottom: 3px solid black;
  height: 20px;
  width: 20px;
  float: left;
  margin: 10px;
  padding: 10px;
}

.deck {
  display: block;
  max-width: 280px;
  border: 1px solid #888;
  background: white;
  border-radius: 2.5px;
  box-sizing: border-box;
  padding: 15px;
  overflow: auto;
  margin: 30px auto;
  box-shadow: 1px 1px 1.5px #ccc;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<div class="deck">

</div>

答案 1 :(得分:0)

看看下面的代码片段。首先要检查变量firstCard是否具有值。如果不是,请将变量设置为单击的卡片。但是,如果它确实具有值,则它将设置变量secondCard的值并检查是否匹配。在checkMatches的末尾,两个变量都被重置为null

const cards = ['fa-diamond', 'fa-diamond',
  'fa-paper-plane-o', 'fa-paper-plane-o',
  'fa-anchor', 'fa-anchor',
  'fa-bolt', 'fa-bolt',
  'fa-cube', 'fa-cube',
  ' fa-leaf', ' fa-leaf',
  'fa-bicycle', 'fa-bicycle',
  'fa-bomb', 'fa-bomb'
];

function createCard(card) {
  return `<li class="card"><i class="fa ${card}"></i></li>`;
}

const deck = document.querySelector('.deck');

function startGame() {

  const cardList = shuffle(cards).map(function(card) {
    return createCard(card);
  });

  deck.innerHTML = cardList.join('');
}
startGame();


// Shuffle function from http://stackoverflow.com/a/2450976
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;
}
let firstCard, secondCard;
const clickedCards = document.querySelectorAll('.card');


function flipCard() {
  // Code here to 'flip' the card open
  if (!firstCard) {
    // No cards have been clicked so assign the first card and then leave the method
    firstCard = this;
    return;
  } else if (firstCard !== this) {
    // The first card has been clicked so assign the second card and check for matches
    secondCard = this;
    checkMatches();
  } else {
    return;
  }
  
  this.classList.toggle('open');
  this.classList.toggle('show');
}

function checkMatches() {
  // This won't work I think, you might want to check for properties of the cards
  if (firstCard === secondCard) {
    // Code to check if the cards match
  }
  
  // Hide the cards again
  firstCard.classList.toggle('show');
  secondCard.classList.toggle('show');
  
  // Reset both variables to empty
  firstCard = secondCard = null;
}

clickedCards.forEach(card => card.addEventListener('click', flipCard));
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class='deck'></div>