diff --git a/index.html b/index.html index 9386faaf4..74c1f1815 100644 --- a/index.html +++ b/index.html @@ -5,7 +5,7 @@ Superhero Memory Game - +
@@ -18,6 +18,8 @@

Score

- + + + diff --git a/src/index.js b/src/index.js index 37f3a672d..46e4d1ebd 100644 --- a/src/index.js +++ b/src/index.js @@ -26,9 +26,11 @@ const cards = [ ]; const memoryGame = new MemoryGame(cards); +memoryGame.shuffleCards(); window.addEventListener('load', (event) => { let html = ''; + memoryGame.cards.forEach((pic) => { html += `
@@ -38,14 +40,46 @@ window.addEventListener('load', (event) => { `; }); - // Add all the divs to the HTML + document.querySelector('#memory-board').innerHTML = html; - // Bind the click event of each element to a function + document.querySelectorAll('.card').forEach((card) => { card.addEventListener('click', () => { - // TODO: write some code here - console.log(`Card clicked: ${card}`); + card.classList.toggle('turned'); + memoryGame.pickedCards.push(card); + + if (memoryGame.pickedCards.length === 2) { + const card1Name = memoryGame.pickedCards[0].getAttribute('data-card-name'); + const card2Name = memoryGame.pickedCards[1].getAttribute('data-card-name'); + + memoryGame.pairsClicked++; + document.getElementById('pairs-clicked').innerText = memoryGame.pairsClicked; + + if (memoryGame.checkIfPair(card1Name, card2Name)) { + memoryGame.pickedCards[0].classList.add('blocked'); + memoryGame.pickedCards[1].classList.add('blocked'); + + memoryGame.pairsGuessed++ /2; + document.getElementById('pairs-guessed').innerText = memoryGame.pairsGuessed; + + if (memoryGame.checkIfFinished()) { + const victoryMessage = document.createElement('div'); + victoryMessage.id = 'victory-message'; + victoryMessage.innerHTML = `

🎉 You won!!! 🎉

`; + document.body.appendChild(victoryMessage); + } + + memoryGame.pickedCards = []; + } else { + setTimeout(() => { + memoryGame.pickedCards[0].classList.remove('turned'); + memoryGame.pickedCards[1].classList.remove('turned'); + + memoryGame.pickedCards = []; + }, 1000); + } + } }); }); }); diff --git a/src/memory.js b/src/memory.js index f6644827e..e08758730 100644 --- a/src/memory.js +++ b/src/memory.js @@ -1,18 +1,33 @@ class MemoryGame { constructor(cards) { - this.cards = cards; - // add the rest of the class properties here + this.cards = cards || []; + this.pickedCards = []; + this.pairsClicked = 0; + this.pairsGuessed = 0; } shuffleCards() { - // ... write your code here + if (!this.cards.length) { + return undefined; + } + for (let i = this.cards.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [this.cards[i], this.cards[j]] = [this.cards[j], this.cards[i]]; + } + return this.cards; } checkIfPair(card1, card2) { - // ... write your code here + this.pairsClicked++; + if (card1 === card2) { + this.pairsGuessed++; + return true; + } + return false; } checkIfFinished() { - // ... write your code here + return this.pairsGuessed === this.cards.length; } } +