DEV Community

Cover image for Memory Game : Based on JavaScript
Raghav Khanna
Raghav Khanna

Posted on

1 1

Memory Game : Based on JavaScript

Memory Game

Live - https://memorygamebyraghav.netlify.app/

A retro grid-based game in vanilla JavaScript, HTML and CSS

For full description visit.
https://github.com/raghavkhanna30/Memorygame/blob/master/README.md

Script/code.

//create your board
function createBoard() {
for (let i = 0; i < cardArray.length; i++) {
var card = document.createElement('img')
card.setAttribute('src', 'images/blank.png')
card.setAttribute('data-id', i)
card.addEventListener('click', flipCard)
grid.appendChild(card)
}
}

Check for match function

// function checkForMatch() {
var cards = document.querySelectorAll('img')
const optionOneId = cardsChosenId[0]
const optionTwoId = cardsChosenId[1]
//if(optionOneId == optionTwoId) {
cards[optionOneId].setAttribute('src', 'images/blank.png')
cards[optionTwoId].setAttribute('src', 'images/blank.png')
alert('You have clicked the same image!')
}
else if (cardsChosen[0] === cardsChosen[1]) {
alert('You found a match')
cards[optionOneId].setAttribute('src', 'images/white.png')
cards[optionTwoId].setAttribute('src', 'images/white.png')
cards[optionOneId].removeEventListener('click', flipCard)
cards[optionTwoId].removeEventListener('click', flipCard)
cardsWon.push(cardsChosen)
} else {
cards[optionOneId].setAttribute('src', 'images/blank.png')
cards[optionTwoId].setAttribute('src', 'images/blank.png')
alert('Sorry, try again')
}
cardsChosen = []
cardsChosenId = []
resultDisplay.textContent = cardsWon.length
if (cardsWon.length === cardArray.length/2) {
resultDisplay.textContent = 'Congratulations! You found them all!'
}
}

Flipcard

//flip your card
function flipCard() {
var cardId = this.getAttribute('data-id')
cardsChosen.push(cardArray[cardId].name)
cardsChosenId.push(cardId)
this.setAttribute('src', cardArray[cardId].img)
if (cardsChosen.length ===2) {
setTimeout(checkForMatch, 500)
}
}

createBoard()
})

For full code you can visit
https://github.com/raghavkhanna30/Memorygame/blob/master/app.js

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more