diff --git a/index.html b/index.html index 9386faaf4..9ce763a54 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..b3b76464b 100644 --- a/src/index.js +++ b/src/index.js @@ -26,6 +26,7 @@ const cards = [ ]; const memoryGame = new MemoryGame(cards); +memoryGame.shuffleCards() window.addEventListener('load', (event) => { let html = ''; @@ -37,7 +38,7 @@ window.addEventListener('load', (event) => {
`; }); - + // Add all the divs to the HTML document.querySelector('#memory-board').innerHTML = html; @@ -45,7 +46,26 @@ 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')}`); + memoryGame.pickedCards.push(card) + card.classList.toggle('turned') + if(memoryGame.pickedCards.length === 2){ + const isPair = memoryGame.checkIfPair(memoryGame.pickedCards[0], memoryGame.pickedCards[1]); + memoryGame.checkIfFinished() + if(isPair){ + memoryGame.pickedCards[0].classList.toggle('blocked') + memoryGame.pickedCards[1].classList.toggle('blocked') + memoryGame.pickedCards = []; + } + else{ + setTimeout(function(){ + memoryGame.pickedCards[0].classList.toggle('turned') + memoryGame.pickedCards[1].classList.toggle('turned') + memoryGame.pickedCards = []; + }, 500) + } + } }); }); }); diff --git a/src/memory.js b/src/memory.js index f6644827e..d3e6dd47e 100644 --- a/src/memory.js +++ b/src/memory.js @@ -2,17 +2,38 @@ class MemoryGame { constructor(cards) { this.cards = cards; // add the rest of the class properties here + this.pickedCards = []; + this.pairClicked = 0; + this.pairGuessed = 0; } shuffleCards() { // ... write your code here + for (let i = this.cards.length - 1; i >= 0; i--) { + const randomIndex = Math.floor(Math.random() * (i + 1)); + this.cards.push(this.cards[randomIndex]); + this.cards.splice(randomIndex, 1); + } } checkIfPair(card1, card2) { - // ... write your code here + const card1Name = card1.getAttribute("data-card-name"); + const card2Name = card2.getAttribute("data-card-name"); + + this.pairsClicked++; + document.querySelector("#pairs-clicked").innerHTML = this.pairsClicked; + if (card1Name === card2Name) { + this.pairsGuessed++; + document.querySelector("#pairs-guessed").innerHTML = this.pairsGuessed; + return true; + } + return false; } checkIfFinished() { // ... write your code here + if (this.pairsGuessed === 12) { + console.log("Game is finished :)"); + } } -} +} \ No newline at end of file