diff --git a/index.html b/index.html index 9386faaf4..d9c864ee8 100644 --- a/index.html +++ b/index.html @@ -6,6 +6,7 @@ Superhero Memory Game +
@@ -19,5 +20,7 @@

Score

+ + diff --git a/src/index.js b/src/index.js index 37f3a672d..a58da24c1 100644 --- a/src/index.js +++ b/src/index.js @@ -26,6 +26,8 @@ const cards = [ ]; const memoryGame = new MemoryGame(cards); +// shuffel +memoryGame.shuffleCards() window.addEventListener('load', (event) => { let html = ''; @@ -45,7 +47,22 @@ window.addEventListener('load', (event) => { document.querySelectorAll('.card').forEach((card) => { card.addEventListener('click', () => { // TODO: write some code here - console.log(`Card clicked: ${card}`); + console.log(`Card clicked: ${card.getAttribute('data-card-name')}`); + var picked = memoryGame.pickedCards + if (picked.includes(card)) return // card already picked + if (picked.length == 2) return // don't pick 3rd card + if (picked.length < 2) { // not enough cards to compare + card.classList.add('turned') + picked.push(card) + } + if (picked.length == 2) { + setTimeout(function() { + memoryGame.pairsClicked ++ + document.getElementById('pairs-clicked').innerText = memoryGame.pairsClicked + memoryGame.checkIfPair(picked[0], picked[1]) + memoryGame.checkIfFinished() + },1000) + } }); }); }); diff --git a/src/memory.js b/src/memory.js index f6644827e..e639f7ad9 100644 --- a/src/memory.js +++ b/src/memory.js @@ -2,17 +2,35 @@ class MemoryGame { constructor(cards) { this.cards = cards; // add the rest of the class properties here + this.pickedCards = [] + this.pairsClicked = 0 + this.pairsGuessed = 0 } shuffleCards() { - // ... write your code here + // Start from the last element and swap it with a randomly selected element before it + for (let i = this.cards.length - 1; i > 0; i--) { + // Generate a random index between 0 and i (inclusive) + const j = Math.floor(Math.random() * (i + 1)); + + // Swap array[i] with array[j] + [this.cards[i], this.cards[j]] = [this.cards[j], this.cards[i]]; + } } checkIfPair(card1, card2) { - // ... write your code here + if (card1.getAttribute('data-card-name') == card2.getAttribute('data-card-name')) { + this.pairsGuessed ++ + document.getElementById('pairs-guessed').innerText = this.pairsGuessed + } + else { + card1.classList.remove('turned') + card2.classList.remove('turned') + } + this.pickedCards = [] } checkIfFinished() { - // ... write your code here + if (this.pairsGuessed == 12) alert('Congrats! you finished the game') } }