diff --git a/index.html b/index.html index 9386faaf4..43fbe8396 100644 --- a/index.html +++ b/index.html @@ -6,18 +6,25 @@ Superhero Memory Game +

Superhero Memory Game

+

Score

Pairs clicked: 0

Pairs guessed: 0

+ +
+ + + diff --git a/src/index.js b/src/index.js index 37f3a672d..031b4521f 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) => { @@ -41,10 +43,40 @@ 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 + memoryGame.pickedCards.push(card); + + card.classList.add("turned"); + + + console.log(memoryGame.pickedCards) + + if (memoryGame.pickedCards.length === 2){ + + + const card1 = memoryGame.pickedCards[0].getAttribute("data-card-name"); + const card2 = memoryGame.pickedCards[1].getAttribute("data-card-name"); + if (memoryGame.checkIfPair(card1,card2)){ + + memoryGame.pickedCards = []; + } else { + setTimeout(()=>{ + memoryGame.pickedCards.forEach(card => card.classList.remove("turned")); + memoryGame.pickedCards = []; + + },1000) + } + + } + document.getElementById("pairs-clicked").innerHTML = memoryGame.pairsClicked; + document.getElementById("pairs-guessed").innerHTML = memoryGame.pairsGuessed; + + if (memoryGame.checkIfFinished()){ + console.log("you won!!!") + } console.log(`Card clicked: ${card}`); }); }); diff --git a/src/memory.js b/src/memory.js index f6644827e..60b6aa6aa 100644 --- a/src/memory.js +++ b/src/memory.js @@ -1,18 +1,42 @@ class MemoryGame { constructor(cards) { this.cards = cards; + this.pickedCards = []; + this.pairsClicked = 0; + this.pairsGuessed = 0; + // add the rest of the class properties here } shuffleCards() { + if (!this.cards) return undefined; + for (let i = this.cards.length - 1; i > 0; i--) { + const randomIndex = Math.floor(Math.random() * (i + 1)); + [this.cards[i], this.cards[randomIndex]] = [this.cards[randomIndex], this.cards[i]]; + } // ... write your code here } checkIfPair(card1, card2) { - // ... write your code here + this.pairsClicked += 1; + if (card1 === card2){ + this.pairsGuessed += 1; + + return true; + } else { + + return false; + } } + + checkIfFinished() { - // ... write your code here + if (this.cards.length / 2 === this.pairsGuessed){ + return true; + } else if (this.cards.length !== this.pairsGuessed){ + return false; + } + } }