Skip to content

Commit

Permalink
Update script.js
Browse files Browse the repository at this point in the history
version 2.O
  • Loading branch information
shxxxam authored Aug 25, 2023
1 parent b1bed72 commit e7683c2
Showing 1 changed file with 195 additions and 161 deletions.
356 changes: 195 additions & 161 deletions script.js
Original file line number Diff line number Diff line change
@@ -1,167 +1,201 @@
let cardsArray = [
{
'name': 'CSS',
'img': './images/css.png',
},
{
'name': 'HTML',
'img': './images/html.png',
},
{
'name': 'jQuery',
'img': './images/jquery.png',
},
{
'name': 'Github',
'img': './images/github.png',
},
{
'name': 'Ruby',
'img': './images/ruby.png',
},
{
'name': 'Python',
'img': './images/snakes.png',
}
];


const parentDiv = document.querySelector('#card-section');

// step 2 to duplicate each card
const gameCard = cardsArray.concat(cardsArray)
// console.log(gameCard)

// steps 3
// Note that this method creates a new shuffled array instead of modifying the original one.
// Fisher reads.
const myNumbers = (array) => {
for (let i = array.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1))
// console.log(i, j)
let temp = array[i]
array[i] = array[j]
array[j] = temp
const moves = document.getElementById("moves-count");
const timeValue = document.getElementById("time");
const startButton = document.getElementById("start");
const stopButton = document.getElementById("stop");
const gameContainer = document.querySelector(".game-container");
const result = document.getElementById("result");
const controls = document.querySelector(".controls-container");
let cards;
let interval;
let firstCard = false;
let secondCard = false;

//Array containing images/cards
const item = [
{
'name': 'CSS',
'img': './images/css.png',
},
{
'name': 'HTML',
'img': './images/html.png',
},
{
'name': 'jQuery',
'img': './images/jquery.png',
},
{
'name': 'Github',
'img': './images/github.png',
},
{
'name': 'Ruby',
'img': './images/ruby.png',
},
{
'name': 'Python',
'img': './images/snakes.png',
},
{
'name': 'Discord',
'img': './images/discord.png',
},
{
'name': 'Java',
'img': './images/java.png',
}
return array
}

const shuffledChild = myNumbers(gameCard)
// let shuffledChild = Array.from(gameCard).sort(() => 0.5 - Math.random());


let clickCount = 0;
let firstCard = "";
let secondCard = "";


// styling the match card
const card_matches = () => {
let card_selected = document.querySelectorAll('.card_selected');

card_selected.forEach((curElem) => {
curElem.classList.add('card_match')
})
}


// step 7

const resetGame = () => {
firstCard = "";
secondCard = "";
clickCount = 0;

let card_selected = document.querySelectorAll('.card_selected');

card_selected.forEach((curElem) => {
curElem.classList.remove('card_selected')
})

}

// step 4
parentDiv.addEventListener('click', (event) => {
let curCard = event.target;

if(curCard.id === "card-section"){return false }

clickCount ++;

if(clickCount < 3){
];

if(clickCount === 1){
firstCard = curCard.parentNode.dataset.name;
curCard.parentNode.classList.add('card_selected');
}else{
secondCard = curCard.parentNode.dataset.name;
curCard.parentNode.classList.add('card_selected');
}

if(firstCard !== "" && secondCard !== ""){
if(firstCard === secondCard){
// curCard.classList.add('card_match')
setTimeout(() => {
card_matches()
resetGame()
}, 1000)
//Initializing things
let seconds = 0,
minutes = 0;
let movesCount = 0,
winCount = 0;

}else{
setTimeout(() => {
resetGame()
}, 1000)
//timer
const timeGenerator = () => {
seconds += 1;
if (seconds >= 60) {
minutes += 1;
seconds = 0;
}
//formating time
let secondsValue = seconds < 10 ? `0${seconds}` : seconds;
let minutesValue = minutes < 10 ? `0${minutes}` : minutes;
timeValue.innerHTML = `<span>Time:</span>${minutesValue}:${secondsValue}`;
};

//calculating moves
const movesCounter = () => {
movesCount += 1;
moves.innerHTML = `<span>Moves:</span>${movesCount}`;
};

//Picking random objects from the cards Array
// Fisher-Yates shuffle

const generateRandom = (size = 4) => {
//temporary array
let tempArray = [...item];
//initializes cardValues array
let cardValues = [];
//size should be double (4*4 matrix)/2 since pairs of objects would exist
size = (size * size) / 2;
//Random object selection
for (let i = 0; i < size; i++) {
const randomIndex = Math.floor(Math.random() * tempArray.length);
cardValues.push(tempArray[randomIndex]);
//once selected remove the object from temp array
tempArray.splice(randomIndex, 1);
}
return cardValues;
};

const matrixGenerator = (cardValues, size = 4) => {
gameContainer.innerHTML = "";
cardValues = [...cardValues, ...cardValues];
//simple shuffle
cardValues.sort(() => Math.random() - 0.5);
for (let i = 0; i < size * size; i++) {
/*
card description
before -> front side (contains question mark)
after -> back side (contains actual image);
data-card-values is a custom attribute which stores the names of the cards to match later.
*/
gameContainer.innerHTML += `
<div class="card-container" data-card-value="${cardValues[i].name}">
<div class="card-before">?</div>
<div class="card-after">
<img src="${cardValues[i].img}" class="image"/></div>
</div>`;
}
//Grid
gameContainer.style.gridTemplateColumns = `repeat(${size},auto)`;

//Cards
cards = document.querySelectorAll(".card-container");
cards.forEach((card) => {
card.addEventListener("click", () => {
//If selected card is not matched yet then only run (i.e already matched card when clicked would be ignored)
if (!card.classList.contains("matched")) {
//flip the cliked card
card.classList.add("flipped");
//if it is the firstcard (!firstCard since firstCard is initially false)
if (!firstCard) {
//so current card will become firstCard
firstCard = card;
//current card's value becomes firstCardValue
firstCardValue = card.getAttribute("data-card-value");
} else {
//increment moves since user selected second card
movesCounter();
//secondCard and value
secondCard = card;
let secondCardValue = card.getAttribute("data-card-value");
if (firstCardValue == secondCardValue) {
//if both cards match add matched class so these cards would beignored next time
firstCard.classList.add("matched");
secondCard.classList.add("matched");
//set firstCard to false since next card would be first now
firstCard = false;
//winCount increment as user found a correct match
winCount += 1;
// if(firstCard = false && firstCard == secondCard) winCount--;
//check if winCount ==half of cardValues
if (winCount >= Math.floor(cardValues.length / 2)) {
result.innerHTML = `<h2>You Won!</h2><h4>Moves: ${movesCount}</h4>`;
stopGame();
}
} else {
//if the cards dont match (flip the cards back to normal)
let [tempFirst, tempSecond] = [firstCard, secondCard];
firstCard = false;
secondCard = false;
let delay = setTimeout(() => {
tempFirst.classList.remove("flipped");
tempSecond.classList.remove("flipped");
}, 900);
}
}
}

}

})




// step 1 to add the card
for(let i=0; i<shuffledChild.length; i++){

const childDiv = document.createElement('div')
childDiv.classList.add('card')
childDiv.dataset.name = shuffledChild[i].name;
// childDiv.style.backgroundImage = `url(${shuffledChild[i].img})`;

const front_div = document.createElement('div');
front_div.classList.add('front-card')

const back_div = document.createElement('div');
back_div.classList.add('back-card')

back_div.style.backgroundImage = `url(${shuffledChild[i].img})`;

parentDiv.appendChild(childDiv)

childDiv.appendChild(front_div)
childDiv.appendChild(back_div)
}

//Adding timer to track the player's time.
let startTime;
let timerInterval;

function startTimer() {
startTime = Date.now();
timerInterval = setInterval(updateTimer,1000);

}

function updateTimer() {
const currentTime = Date.now();
const elapsedTime = Math.floor(60 - (currentTime - startTime) / 1000);
if(elapsedTime < 0){
document.getElementById('timer').textContent = `Looserrrr!`;
}
else{
document.getElementById('timer').textContent = `Time: ${elapsedTime} seconds`;
}
}


// Call startTimer() when the game starts and clear the interval when the game is finished.
});
});
};

//Start game
startButton.addEventListener("click", () => {
movesCount = 0;
seconds = 0;
minutes = 0;
//controls amd buttons visibility
controls.classList.add("hide");
stopButton.classList.remove("hide");
startButton.classList.add("hide");
//Start timer
interval = setInterval(timeGenerator, 1000);
//initial moves
moves.innerHTML = `<span>Moves:</span> ${movesCount}`;
initializer();
});

//Stop game
stopButton.addEventListener(
"click",
(stopGame = () => {
controls.classList.remove("hide");
stopButton.classList.add("hide");
startButton.classList.remove("hide");
clearInterval(interval);
})
);

//Initialize values and func calls
const initializer = () => {
result.innerText = "";
winCount = 0;
let cardValues = generateRandom();
console.log(cardValues);
matrixGenerator(cardValues);
};

0 comments on commit e7683c2

Please sign in to comment.