I am trying to develop a card matching game. I watched a Youtube Tutorial about it. But the cards does not show up even if I write the exact code from the video. The aim is matching two same characters. The characters should show up when a portal is clicked. So what’s the problem here? Here is my JavaScript code:
document.addEventListener('DOMContentLoaded',()=>{
const cardArray = [
{
name: 'beth',
img: 'images/beth.png'
},
{
name: 'beth',
img: 'images/beth.png'
},
{
name: 'jerry',
img: 'images/jerry.png'
},
{
name: 'jerry',
img: 'images/jerry.png'
},
{
name: 'morty',
img: 'images/morty.png'
},
{
name: 'morty',
img: 'images/morty.png'
},
{
name: 'mrpoopybutthole',
img: 'images/mrpoopybutthole.png'
},
{
name: 'mrpoopybutthole',
img: 'images/mrpoopybutthole.png'
},
{
name: 'rick',
img: 'images/rick.png'
},
{
name: 'rick',
img: 'images/rick.png'
},
{
name: 'summer',
img: 'images/summer.png'
},
{
name: 'summer',
img: 'images/summer.png'
}
]
cardArray.sort(()=> 0.5 - Math.random());
const grid = document.querySelector('.grid');
const resultDisplay = document.querySelector('#result');
var cardsChosen = [];
var cardChosenId = [];
var cardsWon = [];
function createBoard() {
for(let i=0; i<cardArray.length; i++){
var card = document.createElement('img');
card.setAttribute('src','images/portal.png');
card.setAttribute('data-id', i);
card.addEventListener('click', flipCard);
grid.appendChild(card);
}
}
function checkForMatch(){
var cards = document.querySelectorAll('img');
const optionOneId = cardsChosenId[0];
const optionTwoId = cardsChosenId[1];
if (cardsChosen[0] === cardsChosen[1]) {
alert('You found a match');
cards[optionOneId].setAttribute('src', 'images/white.png');
cards[optionTwoId].setAttribute('src', 'images/white.png');
cardsWon.push(cardsChosen);
}
else {
cards[optionOneId].setAttribute('src', 'images/portal.png');
cards[optionTwoId].setAttribute('src', 'image/portal.png');
alert('Sorry, try again');
}
cardsChosen = [];
cardChosenId= [];
resultDisplay.textContent = cardsWon.length;
if (cardsWon.length === cardArray.length/2){
resultDisplay.textContent = 'Congratulations! You found them all!';
}
}
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();
});