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

Score

- + + diff --git a/src/index.js b/src/index.js index 37f3a672d..83ea27769 100644 --- a/src/index.js +++ b/src/index.js @@ -27,6 +27,8 @@ const cards = [ const memoryGame = new MemoryGame(cards); +memoryGame.shuffleCards(); + window.addEventListener('load', (event) => { let html = ''; memoryGame.cards.forEach((pic) => { @@ -43,9 +45,33 @@ window.addEventListener('load', (event) => { // Bind the click event of each element to a function document.querySelectorAll('.card').forEach((card) => { - card.addEventListener('click', () => { + card.addEventListener('click', (event) => { // TODO: write some code here console.log(`Card clicked: ${card}`); + card.classList.add('turned'); + memoryGame.pickedCards.push([card.getAttribute("data-card-name"), card]); + + if (memoryGame.checkIfPair(memoryGame.pickedCards[0][0], memoryGame.pickedCards[1][0])) { + memoryGame.pickedCards = []; + } else { + setTimeout(() => { + memoryGame.pickedCards[0][1].classList.remove("turned"); + memoryGame.pickedCards[1][1].classList.remove("turned"); + memoryGame.pickedCards = []; + }, 500); + } + + + document.getElementById('pairs-clicked').innerText = memoryGame.pairsClicked; + document.getElementById('pairs-guessed').innerText = memoryGame.pairsGuessed; + + if (memoryGame.checkIfFinished()) { + document.querySelector('#memory-board').innerHTML = ""; + document.querySelector('#memory-board').innerHTML = `
`; + setTimeout(() => { + location.reload(); + }, 2000); + } }); }); }); diff --git a/src/memory.js b/src/memory.js index f6644827e..278c8bd1b 100644 --- a/src/memory.js +++ b/src/memory.js @@ -1,18 +1,34 @@ 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 + const arr = this.cards; + if (!arr) { + return undefined; + } + for (let i = arr.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [arr[i], arr[j]] = [arr[j], arr[i]]; + } + return arr; } checkIfPair(card1, card2) { - // ... write your code here + this.pairsClicked++; + if(card1 === card2) { + this.pairsGuessed++; + return true; + } else { + return false; + } } checkIfFinished() { - // ... write your code here + return this.pairsGuessed === (this.cards.length / 2); } }