Currently, I am developing a memory game using JavaScript. One of the features I have implemented is toggling between two card faces by changing the class back and forth. Now, I am in the process of creating a function that will check if two game cards are matched. If they match, the images will remain flipped; otherwise, they will revert back to their original state.
// Declaration of variables for game elements
let gameTiles = document.getElementsByClassName('game_tile');
let cardFace = document.getElementsByClassName('card_face');
let cardMatchCheck = [];
let cardArray =
[ "one", "one", "two", "two", "three", "three",
"four", "four", "five", "five", "six", "six",
"seven", "seven", "eight", "eight", "nine", "nine",
"ten", "ten", "eleven", "eleven", "twelve", "twelve" ];
// Assigning class to div element through loop from the cardArray
// .className += enables adding to an already assigned class
// in this case "game_tile" (our button class)
for (let i = 0; i < gameTiles.length; i++) {
for (let j = 0; j < cardArray.length; j++) {
gameTiles[i].setAttribute("class", cardArray[j]);
}
}
// Click response (working)
let gameTileClick = document.getElementsByTagName('button');
for (let i = 0; i < gameTileClick.length; i++) {
gameTileClick[i].addEventListener('click', changeCardImage);
}
// Testing grounds:
// This function runs through all card classes and switches
// between both card image states (back, front, back)
// Still need to work on implementing the pair recognition
function changeCardImage(cardArray) {
if (cardArray.className == 'one') {
cardArray.className = 'card_one_img'
cardMatchCheck.push(cardArray.className);
cardMatch();
cardMismatch();
} else if (cardArray.className == 'card_one_img') {
cardArray.className = "one"
}
...
console.log(cardMatchCheck);
// Function for checking card match/mismatch
function cardMatch() {
if (cardArray.className == cardArray.className) {
console.log('match');
}
}
function cardMismatch() {
if (cardArray.className != cardArray.className) {
cardArray.className = 'card_face';
}
}
If there's any formatting issue, please bear with me as this is my first SO post. Any guidance would be greatly appreciated. Thank you for taking the time!
Edit: To see what I have developed so far, here is the link: https://codepen.io/woolsox/pen/mMRPJK